# Chart

Beautiful charts, rendered on the server as SVG. Copy and paste into your apps.

Source: https://webjs.dev/ui/docs/components/chart

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
  cardClass, cardContentClass, cardDescriptionClass, cardHeaderClass, cardTitleClass,
} from '#components/ui/card.ts';
import { barChart, type ChartConfig } from '#components/ui/chart.ts';

export const description = 'An interactive bar chart';

const chartData = [
  { date: '2024-04-01', desktop: 222, mobile: 150 },
  { date: '2024-04-02', desktop: 97, mobile: 180 },
  { date: '2024-04-03', desktop: 167, mobile: 120 },
  { date: '2024-04-04', desktop: 242, mobile: 260 },
  { date: '2024-04-05', desktop: 373, mobile: 290 },
  { date: '2024-04-06', desktop: 301, mobile: 340 },
  { date: '2024-04-07', desktop: 245, mobile: 180 },
  { date: '2024-04-08', desktop: 409, mobile: 320 },
  { date: '2024-04-09', desktop: 59, mobile: 110 },
  { date: '2024-04-10', desktop: 261, mobile: 190 },
  { date: '2024-04-11', desktop: 327, mobile: 350 },
  { date: '2024-04-12', desktop: 292, mobile: 210 },
  { date: '2024-04-13', desktop: 342, mobile: 380 },
  { date: '2024-04-14', desktop: 137, mobile: 220 },
  { date: '2024-04-15', desktop: 120, mobile: 170 },
  { date: '2024-04-16', desktop: 138, mobile: 190 },
  { date: '2024-04-17', desktop: 446, mobile: 360 },
  { date: '2024-04-18', desktop: 364, mobile: 410 },
  { date: '2024-04-19', desktop: 243, mobile: 180 },
  { date: '2024-04-20', desktop: 89, mobile: 150 },
  { date: '2024-04-21', desktop: 137, mobile: 200 },
  { date: '2024-04-22', desktop: 224, mobile: 170 },
  { date: '2024-04-23', desktop: 138, mobile: 230 },
  { date: '2024-04-24', desktop: 387, mobile: 290 },
  { date: '2024-04-25', desktop: 215, mobile: 250 },
  { date: '2024-04-26', desktop: 75, mobile: 130 },
  { date: '2024-04-27', desktop: 383, mobile: 420 },
  { date: '2024-04-28', desktop: 122, mobile: 180 },
  { date: '2024-04-29', desktop: 315, mobile: 240 },
  { date: '2024-04-30', desktop: 454, mobile: 380 },
];

const chartConfig = {
  views: { label: 'Page Views' },
  desktop: { label: 'Desktop', color: 'var(--chart-2)' },
  mobile: { label: 'Mobile', color: 'var(--chart-1)' },
} satisfies ChartConfig;

const total = {
  desktop: chartData.reduce((acc, curr) => acc + curr.desktop, 0),
  mobile: chartData.reduce((acc, curr) => acc + curr.mobile, 0),
};

const day = (value: unknown, opts: Intl.DateTimeFormatOptions) =>
  new Date(String(value)).toLocaleDateString('en-US', { ...opts, timeZone: 'UTC' });

// One chart per series, both served. The header's two choices are radio
// inputs, so picking one swaps the chart through :has() with no script.
function chart(key: 'desktop' | 'mobile') {
  return barChart({
    config: chartConfig,
    class: 'aspect-auto h-[250px] w-full',
    width: 590,
    height: 250,
    data: chartData,
    title: `${chartConfig[key].label} page views, April 2024`,
    margin: { left: 12, right: 12 },
    grid: { vertical: false },
    xAxis: {
      dataKey: 'date',
      tickLine: false,
      axisLine: false,
      tickMargin: 8,
      minTickGap: 32,
      tickFormatter: (value) => day(value, { month: 'short', day: 'numeric' }),
    },
    tooltip: {
      class: 'w-[150px]',
      nameKey: 'views',
      labelFormatter: (value) => day(value, { month: 'short', day: 'numeric', year: 'numeric' }),
    },
    bars: [{ dataKey: key, fill: `var(--color-${key})` }],
  });
}

export default function ChartDemo() {
  return html`
    <div data-slot="card" class=${cn(cardClass(), 'group/chart py-0 pb-4')}>
      <div data-slot="card-header" class=${cn(cardHeaderClass(), 'flex flex-col items-stretch border-b p-0! sm:flex-row')}>
        <div class="flex flex-1 flex-col justify-center gap-1 px-6 pt-4 pb-3 sm:py-0!">
          <div data-slot="card-title" class=${cardTitleClass()}>Bar Chart - Interactive</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>Showing total visitors for the last 3 months</div>
        </div>
        <div class="flex" role="radiogroup" aria-label="Series">
          ${(['desktop', 'mobile'] as const).map((key) => html`
            <label class="relative z-30 flex flex-1 cursor-pointer flex-col justify-center gap-1 border-t px-6 py-4 text-left even:border-l has-checked:bg-muted/50 has-focus-visible:ring-2 has-focus-visible:ring-ring sm:border-t-0 sm:border-l sm:px-8 sm:py-6">
              <input type="radio" name="chart-demo-series" value=${key} ?checked=${key === 'desktop'} class="sr-only">
              <span class="text-xs text-muted-foreground">${chartConfig[key].label}</span>
              <span class="text-lg leading-none font-bold sm:text-3xl">${total[key].toLocaleString('en-US')}</span>
            </label>`)}
        </div>
      </div>
      <div data-slot="card-content" class=${cn(cardContentClass(), 'px-2 sm:p-6')}>
        <div class="group-has-[input[value=mobile]:checked]/chart:hidden">${chart('desktop')}</div>
        <div class="hidden group-has-[input[value=mobile]:checked]/chart:block">${chart('mobile')}</div>
      </div>
    </div>
  `;
}
```

Introducing **Charts**. A collection of chart components that you can copy and paste into your apps.

Charts are designed to look great out of the box. They work well with the other components and are fully customizable to fit your project.

[Browse the Charts Library](https://webjs.dev/ui/charts/area).

## Component

The charts are drawn on the server as plain SVG, with no charting library. The layout engine computes the margins, scales, curves, bar layout and tick thinning on the server, and every option below shapes what it draws.

We designed the `chart` component with composition in mind. **Each chart is one function call, with the grid, the axes, the tooltip and the legend as options you add only when and where you need them**.

```ts
import { html } from '@webjsdev/core';
import { barChart } from '#components/ui/chart.ts';

export function myChart() {
  return html`
    ${barChart({
      config: chartConfig,
      data,
      bars: [{ dataKey: 'value' }],
      tooltip: {},
    })}
  `;
}
```

The first paint is the whole chart, so it reads with JavaScript off. The `<ui-chart>` element the function returns adds the tooltip, the hover cursor and the keyboard once it loads.

**The components are yours**. The three files `add chart` writes are plain source in your app.

## Installation

```bash
npx @webjsdev/ui add chart
```

### Copy and paste the following code into your project.

````ts title="components/ui/chart.ts"
/**
 * Chart: shadcn's Chart, drawn as plain SVG by the server. Tier-2. shadcn's
 * is Recharts (D10: the kit takes no third-party runtime dependency), so
 * this file ports the parts of Recharts the shadcn charts use: the bar, area,
 * line, pie, radar and radial bar layouts, Recharts' default margins and axis
 * sizes, and shadcn's tooltip and legend markup. Two files come with it and
 * are re-exported here: `chart-geometry.ts`, the maths (scales, nice ticks,
 * the d3 curves, the bar and sector paths), and `chart-element.ts`, the
 * `<ui-chart>` element with the tooltip and legend markup it draws. Each chart function returns the whole `<ui-chart>`
 * (shadcn's ChartContainer plus the chart inside it), so the first paint is
 * the complete chart and it reads with JavaScript off.
 *
 * shadcn parity:
 *   ChartContainer config className    → the chart function's `config` and `class`
 *   <BarChart> / <LineChart> / <AreaChart> → barChart({ ... }) / lineChart / areaChart
 *   <PieChart> / <RadarChart> / <RadialBarChart> → pieChart / radarChart / radialBarChart
 *   <Bar> / <Line> / <Area> children    → `bars` / `lines` / `areas` arrays (same prop names)
 *   <CartesianGrid> / <XAxis> / <YAxis> → `grid` / `xAxis` / `yAxis` (same prop names)
 *   <ChartTooltip content={<ChartTooltipContent … />} />
 *                                       → `tooltip: { indicator, hideLabel, nameKey, … }`
 *   <ChartLegend content={<ChartLegendContent />} /> → `legend: { … }`
 *   <LabelList> / <Label>               → `labels: [{ position, offset, class, … }]`, `center`
 *   shape / dot / label render props    → the same options as functions returning `svg` templates
 *   ChartConfig                         → ChartConfig (same shape; `icon` is a function returning a template)
 *
 * The series colours are custom properties in the container's `style`
 * (`--color-desktop: var(--chart-1)`, `light-dark(a, b)` for a `theme`
 * entry), so `fill: 'var(--color-desktop)'` reads exactly as in shadcn.
 * Every part carries a `ui-chart-*` class named after the `recharts-*` class
 * it replaces (`recharts-pie-label-text` → `ui-chart-pie-label-text`), so a
 * shadcn `className` such as `[&_.recharts-text]:fill-background` ports by
 * that one rename.
 *
 * Sizing: the SVG has a `viewBox` of the chart's nominal size (450 by 253 for
 * the default `aspect-video` container, 250 square for the polar charts) and
 * scales to its container. Give `width` / `height` when the container has
 * another shape (`class: 'aspect-auto h-[250px] w-full'` wants a wide box).
 *
 * The element: `<ui-chart>` adds what needs a pointer. Hovering shows the
 * tooltip, the cursor and the active dots for the nearest point; the chart
 * takes focus (Recharts' accessibilityLayer), the arrow keys step through the
 * points, Home / End jump, Escape hides. Every tooltip is resolved by the
 * server, one per point, so a `labelFormatter`, a `formatter` or an `icon`
 * runs once on the server and never ships. A point whose tooltip is all text
 * is served as data and drawn by the element; one with an icon or a custom
 * row is served as markup.
 *
 * Design tokens used: `--chart-1` to `--chart-5` through the config, plus
 * `border`, `muted`, `muted-foreground`, `background` and `foreground`.
 *
 * A11y (handled by the element, plus your part): the SVG is a `role="img"`
 * named by `title`; once the element upgrades and the chart has a tooltip it
 * becomes a focusable `role="application"` whose arrow keys move the tooltip,
 * and each step is announced through a polite live region. Your part: pass a
 * `title` that says what the chart shows, and keep the numbers available in
 * the text around it (the card's description or footer) for a reader who
 * cannot use the chart.
 *
 * @example
 * ```html
 * ${barChart({
 *   config: { desktop: { label: 'Desktop', color: 'var(--chart-1)' } },
 *   data: [{ month: 'January', desktop: 186 }, { month: 'February', desktop: 305 }],
 *   title: 'Desktop visitors by month',
 *   grid: { vertical: false },
 *   xAxis: { dataKey: 'month', tickLine: false, axisLine: false, tickMargin: 10, tickFormatter: (v) => String(v).slice(0, 3) },
 *   tooltip: { cursor: false, hideLabel: true },
 *   bars: [{ dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 8 }],
 * })}
 * ```
 */
import { html, svg, nothing } from '@webjsdev/core';
import { cn } from '../lib/utils.ts';
import {
  RADIAN, fmt, formatValue, num, percent, estimateTextWidth, niceTicks, linearTicks, linearScale, bandScale, pointScale,
  curvePath, rectanglePath, polarToCartesian, sectorPath, polygonPath, stackData, visibleTicks, barPositions,
  type CurveType, type Pt, type SectorGeometry, type Tick,
} from './chart-geometry.ts';
import {
  UiChart, chartStyle, payloadConfig, chartTooltipView, chartTooltipMarkup, chartTooltipContent, chartLegendContent, isPlainView,
  type ChartConfig, type ChartConfigItem, type ChartDatum, type Margin, type ChartPayloadItem, type ChartTooltipOptions,
  type ChartLegendOptions, type ChartBaseOptions, type ChartTooltipView, type TooltipLook,
} from './chart-element.ts';

export {
  fmt, formatValue, estimateTextWidth, niceTicks, linearTicks, linearScale, bandScale, pointScale, curvePath,
  rectanglePath, polarToCartesian, sectorPath, polygonPath, stackData, visibleTicks, barPositions,
};
export type { CurveType, SectorGeometry, Tick };
export { UiChart, chartStyle, payloadConfig, chartTooltipView, chartTooltipMarkup, chartTooltipContent, chartLegendContent };
export type {
  ChartConfig, ChartConfigItem, ChartDatum, Margin, ChartPayloadItem, ChartTooltipOptions, ChartLegendOptions, ChartBaseOptions,
  ChartTooltipView,
};

// --------------------------------------------------------------------------
// Labels (Recharts' Label / LabelList positions)
// --------------------------------------------------------------------------

export type LabelPosition = 'top' | 'bottom' | 'left' | 'right' | 'inside' | 'insideLeft' | 'insideRight' | 'insideTop' | 'insideBottom' | 'center' | 'middle' | 'outside' | 'insideStart' | 'insideEnd' | 'end';

/** A LabelList: one label per data point of a series. */
export interface ChartLabelOptions {
  /** The value to print, a key of the datum. Defaults to the series' dataKey. */
  dataKey?: string;
  position?: LabelPosition;
  offset?: number;
  class?: string;
  fill?: string;
  stroke?: string;
  fontSize?: number;
  formatter?: (value: unknown, datum: ChartDatum, index: number) => unknown;
  /** A custom label: return an `svg` template. */
  content?: (props: { x: number; y: number; width: number; height: number; value: unknown; datum: ChartDatum; index: number }) => unknown;
}

type VAnchor = 'start' | 'middle' | 'end';
const DY: Record<VAnchor, string> = { start: '0.71em', middle: '0.355em', end: '0em' };

/** A text element as Recharts' `<Text>` writes one: the position on the text, the baseline shift on a tspan. */
export function chartText(x: number, y: number, value: unknown, o: { anchor?: 'start' | 'middle' | 'end'; vAnchor?: VAnchor; class?: string; fill?: string | null; stroke?: string; fontSize?: number; baseline?: string } = {}) {
  // A size in pixels, as Recharts takes it, written in em of the chart's
  // 12px text so it keeps its size when the chart scales (see `_watchSize`).
  const size = o.fontSize != null ? `${fmt(o.fontSize / 12)}em` : nothing;
  return svg`<text x=${fmt(x)} y=${fmt(y)} text-anchor=${o.anchor ?? 'middle'} fill=${o.fill ?? nothing} stroke=${o.stroke ?? nothing} font-size=${size} alignment-baseline=${o.baseline ?? nothing} class=${cn('ui-chart-text', o.class)}><tspan x=${fmt(x)} dy=${DY[o.vAnchor ?? 'end']}>${value}</tspan></text>`;
}

function cartesianLabelAttrs(box: { x: number; y: number; width: number; height: number }, position: LabelPosition, offset: number): { x: number; y: number; anchor: 'start' | 'middle' | 'end'; vAnchor: VAnchor } {
  const { x, y, width, height } = box;
  const vs = height >= 0 ? 1 : -1;
  const hs = width >= 0 ? 1 : -1;
  switch (position) {
    case 'top': return { x: x + width / 2, y: y - vs * offset, anchor: 'middle', vAnchor: vs > 0 ? 'end' : 'start' };
    case 'bottom': return { x: x + width / 2, y: y + height + vs * offset, anchor: 'middle', vAnchor: vs > 0 ? 'start' : 'end' };
    case 'left': return { x: x - hs * offset, y: y + height / 2, anchor: hs > 0 ? 'end' : 'start', vAnchor: 'middle' };
    case 'right': return { x: x + width + hs * offset, y: y + height / 2, anchor: hs > 0 ? 'start' : 'end', vAnchor: 'middle' };
    case 'insideLeft': return { x: x + hs * offset, y: y + height / 2, anchor: hs > 0 ? 'start' : 'end', vAnchor: 'middle' };
    case 'insideRight': return { x: x + width - hs * offset, y: y + height / 2, anchor: hs > 0 ? 'end' : 'start', vAnchor: 'middle' };
    case 'insideTop': return { x: x + width / 2, y: y + vs * offset, anchor: 'middle', vAnchor: 'start' };
    case 'insideBottom': return { x: x + width / 2, y: y + height - vs * offset, anchor: 'middle', vAnchor: 'end' };
    default: return { x: x + width / 2, y: y + height / 2, anchor: 'middle', vAnchor: 'middle' };
  }
}

function labelList(labels: ChartLabelOptions[] | undefined, seriesKey: string, items: Array<{ box: { x: number; y: number; width: number; height: number }; datum: ChartDatum; index: number; fill?: string }>, fallbackPosition: LabelPosition) {
  if (!labels?.length) return '';
  return labels.map((l) => svg`<g class="ui-chart-label-list">${items.map(({ box, datum, index, fill }) => {
    const raw = datum[l.dataKey ?? seriesKey];
    const value = l.formatter ? l.formatter(raw, datum, index) : raw;
    if (l.content) return l.content({ ...box, value, datum, index });
    const a = cartesianLabelAttrs(box, l.position ?? fallbackPosition, l.offset ?? 5);
    // A label takes its mark's colour unless it names one, as Recharts' does.
    return chartText(a.x, a.y, value, { anchor: a.anchor, vAnchor: a.vAnchor, class: cn('ui-chart-label', l.class), fill: l.fill ?? fill, stroke: l.stroke, fontSize: l.fontSize });
  })}</g>`);
}

// --------------------------------------------------------------------------
// The container (shadcn's ChartContainer) and the tooltip layer
// --------------------------------------------------------------------------

/**
 * shadcn's ChartContainer classes, its `[&_.recharts-*]` rules renamed to the
 * `ui-chart-*` parts, plus one of the kit's own: strokes keep their width in
 * pixels when the chart scales, as Recharts draws them at the real size.
 */
export function chartContainerClass(): string {
  return "flex aspect-video justify-center text-xs [&_.ui-chart-cartesian-axis-tick_text]:fill-muted-foreground [&_.ui-chart-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.ui-chart-curve.ui-chart-tooltip-cursor]:stroke-border [&_.ui-chart-dot[stroke='#fff']]:stroke-transparent [&_.ui-chart-layer]:outline-hidden [&_.ui-chart-polar-grid_[stroke='#ccc']]:stroke-border [&_.ui-chart-radial-bar-background-sector]:fill-muted [&_.ui-chart-rectangle.ui-chart-tooltip-cursor]:fill-muted [&_.ui-chart-reference-line_[stroke='#ccc']]:stroke-border [&_.ui-chart-sector]:outline-hidden [&_.ui-chart-sector[stroke='#fff']]:stroke-transparent [&_.ui-chart-surface]:outline-hidden [&_.ui-chart-surface_*]:[vector-effect:non-scaling-stroke]";
}

/** One tooltip point: its category, its series, and where the tooltip anchors (viewBox units). */
export interface ChartPoint {
  label: unknown;
  payload: ChartPayloadItem[];
  x: number;
  y: number;
}

interface Frame {
  width: number;
  height: number;
  /** How the element maps a pointer to a point: along x, along y, or by the hovered shape. */
  hit: 'x' | 'y' | 'target';
  body: unknown;
  points: ChartPoint[];
  legend: ChartPayloadItem[];
  margin: Margin;
  /** The plot area, the box Recharts keeps a tooltip inside. */
  plot: { x: number; y: number; w: number; h: number };
  /** The element may widen the plot to fill its box (a cartesian chart). */
  fit?: boolean;
}

// Recharts sorts a legend by each item's value (its `itemSorter` default),
// which for a series is its name: a stable sort, so equal names keep order.
function sortLegend(items: ChartPayloadItem[]): ChartPayloadItem[] {
  return [...items].sort((a, b) => {
    const x = String(a.value);
    const y = String(b.value);
    return x < y ? -1 : x > y ? 1 : 0;
  });
}

function legendLayer(o: ChartBaseOptions, f: Frame) {
  if (!o.legend) return '';
  // An HTML row over the chart rather than a foreignObject inside it, as
  // Recharts' legend wrapper is: anchored at the margin, as wide as the area
  // between the side margins, as tall as its content (a wrapping legend grows
  // away from the edge), and in real pixels, since WebKit misplaces the
  // content of a scaled foreignObject and Firefox does not scale its font.
  const pct = (v: number, of: number) => `${fmt((v / of) * 100)}%`;
  const edge = o.legend.verticalAlign === 'top' ? `top: ${pct(f.margin.top, f.height)}` : `bottom: ${pct(f.margin.bottom, f.height)}`;
  return html`<div class="ui-chart-legend-wrapper absolute" style=${`left: ${pct(f.margin.left, f.width)}; right: ${pct(f.margin.right, f.width)}; ${edge}`}>${chartLegendContent(o.config, sortLegend(f.legend), o.legend)}</div>`;
}

function frame(o: ChartBaseOptions, f: Frame) {
  const t = o.tooltip || null;
  const def = t && t.defaultIndex != null ? f.points[t.defaultIndex] : undefined;
  const a11y = o.accessibilityLayer !== false;
  // Each point's tooltip is resolved here, on the server, so a formatter never
  // ships. One that is all strings is served as data (a 90 point chart would
  // otherwise carry 90 copies of the markup); one with an icon or a custom
  // row is served as markup.
  const look: TooltipLook = t ? { indicator: t.indicator, hideIndicator: t.hideIndicator, class: t.class, labelClass: t.labelClass } : {};
  const views = t ? f.points.map((p) => chartTooltipView(o.config, p.label, p.payload, t)) : [];
  // cn() keeps both aspect utilities, so an authored one replaces the default here.
  const base = /(^|\s)aspect-/.test(o.class ?? '') ? chartContainerClass().replace(' aspect-video', '') : chartContainerClass();
  return html`<ui-chart data-slot="chart" data-chart=${o.id ?? nothing} class=${cn(base, o.class)} style=${chartStyle(o.config) || nothing}><div class="ui-chart-wrapper relative h-full w-full min-w-0"><svg class="ui-chart-surface block h-full w-full overflow-visible" xmlns="http://www.w3.org/2000/svg" viewBox=${`0 0 ${fmt(f.width)} ${fmt(f.height)}`} role="img" aria-label=${o.title ?? nothing} data-hit=${t ? f.hit : nothing} data-keyboard=${t && a11y ? 'true' : nothing} data-default-index=${def ? String(t?.defaultIndex) : nothing} data-fit=${f.fit ? 'x' : nothing} data-plot=${t || f.fit ? [f.plot.x, f.plot.y, f.plot.w, f.plot.h].map((v) => fmt(v)).join(' ') : nothing}>${o.defs ? svg`<defs>${o.defs}</defs>` : ''}${f.body}</svg>${legendLayer(o, f)}${t ? html`<div data-slot="chart-tooltip" class="ui-chart-tooltip-wrapper pointer-events-none absolute top-0 left-0 z-10 [transition:transform_400ms]" ?hidden=${!def} style=${def ? `transform: translate(${fmt(def.x + 10)}px, ${fmt(def.y + 10)}px)` : nothing}>${def && t && t.defaultIndex != null ? chartTooltipMarkup(views[t.defaultIndex], look) : ''}</div><div data-slot="chart-tooltips" hidden data-look=${JSON.stringify(look)}>${views.map((v, i) => (isPlainView(v)
      ? html`<div data-index=${String(i)} data-x=${fmt(f.points[i].x)} data-y=${fmt(f.points[i].y)} data-tip=${JSON.stringify(v)}></div>`
      : html`<div data-index=${String(i)} data-x=${fmt(f.points[i].x)} data-y=${fmt(f.points[i].y)}>${chartTooltipMarkup(v, look)}</div>`))}</div><span data-slot="chart-live" class="sr-only" aria-live="polite"></span>` : ''}</div></ui-chart>`;
}

/** The per-point overlay groups: hidden until their point is active (or it is the default). */
function overlay(slot: 'chart-cursor' | 'chart-active', parts: unknown[], defaultIndex: number | undefined) {
  return svg`<g data-slot=${slot}>${parts.map((p, i) => svg`<g data-index=${String(i)} visibility=${i === defaultIndex ? 'visible' : 'hidden'}>${p}</g>`)}</g>`;
}

function resolveMargin(m: Partial<Margin> | undefined): Margin {
  if (!m) return { top: 5, right: 5, bottom: 5, left: 5 };
  return { top: m.top ?? 0, right: m.right ?? 0, bottom: m.bottom ?? 0, left: m.left ?? 0 };
}

// --------------------------------------------------------------------------
// Cartesian charts: bar, line, area
// --------------------------------------------------------------------------

export interface ChartAxisOptions {
  dataKey?: string;
  type?: 'category' | 'number';
  hide?: boolean;
  tick?: boolean;
  tickLine?: boolean;
  axisLine?: boolean;
  tickMargin?: number;
  tickSize?: number;
  tickFormatter?: (value: unknown, index: number) => unknown;
  minTickGap?: number;
  tickCount?: number;
  interval?: number | 'preserveEnd' | 'preserveStart' | 'preserveStartEnd';
  /** The x axis's height, default 30. */
  height?: number;
  /** The y axis's width, default 60. */
  width?: number;
  domain?: [number | 'auto' | 'dataMin' | 'dataMax', number | 'auto' | 'dataMin' | 'dataMax'];
  allowDecimals?: boolean;
  padding?: { left?: number; right?: number; top?: number; bottom?: number };
  /** Run the axis the other way, Recharts' `reversed` (a right-to-left chart's x axis). */
  reversed?: boolean;
  class?: string;
}

export interface ChartDotOptions { r?: number; fill?: string; stroke?: string; strokeWidth?: number; fillOpacity?: number; class?: string }
export type ChartDotRender = (props: { cx: number; cy: number; r: number; fill: string; stroke: string; datum: ChartDatum; index: number; dataKey: string }) => unknown;

export interface ChartBarShapeProps {
  x: number; y: number; width: number; height: number;
  radius: number | number[]; fill: string; datum: ChartDatum; index: number; dataKey: string;
  stroke?: string; strokeWidth?: number; fillOpacity?: number;
}

/** A bar as the kit draws one (Recharts' `<Rectangle>`), for a custom `shape` to reuse. */
export function chartRectangle(p: Omit<ChartBarShapeProps, 'datum' | 'index' | 'dataKey'> & { strokeDasharray?: number | string; strokeDashoffset?: number; class?: string }) {
  return svg`<path class=${cn('ui-chart-rectangle', p.class)} fill=${p.fill} fill-opacity=${p.fillOpacity ?? nothing} stroke=${p.stroke ?? nothing} stroke-width=${p.strokeWidth ?? nothing} stroke-dasharray=${p.strokeDasharray ?? nothing} stroke-dashoffset=${p.strokeDashoffset ?? nothing} d=${rectanglePath(p.x, p.y, p.width, p.height, p.radius)}></path>`;
}

export interface ChartSeriesOptions {
  dataKey: string;
  name?: string;
  fill?: string;
  stroke?: string;
  strokeWidth?: number;
  fillOpacity?: number;
  strokeDasharray?: string;
  stackId?: string;
  /** Line and area curve, Recharts' `type`. */
  type?: CurveType;
  /** Bar corner radius, one number or `[tl, tr, br, bl]`. */
  radius?: number | number[];
  /** Line dots (default on for lines, off for areas), options or a render function. */
  dot?: boolean | ChartDotOptions | ChartDotRender;
  /** The hover dot (lines and areas), default on. */
  activeDot?: boolean | ChartDotOptions;
  labels?: ChartLabelOptions[];
  /** A bar drawn active from the first paint, and how (Recharts' `activeIndex` + `activeBar`). */
  activeIndex?: number;
  activeBar?: { fill?: string; fillOpacity?: number; stroke?: string; strokeWidth?: number; strokeDasharray?: string; strokeDashoffset?: number };
  /** A custom bar, Recharts' `shape`. */
  shape?: (props: ChartBarShapeProps) => unknown;
  barSize?: number;
  class?: string;
  hide?: boolean;
}

export interface CartesianChartOptions extends ChartBaseOptions {
  layout?: 'horizontal' | 'vertical';
  barCategoryGap?: number | string;
  barGap?: number | string;
  maxBarSize?: number;
  stackOffset?: 'none' | 'expand' | 'sign';
  grid?: false | { horizontal?: boolean; vertical?: boolean; strokeDasharray?: string; class?: string };
  xAxis?: ChartAxisOptions | false;
  yAxis?: ChartAxisOptions | false;
}

type Family = 'bar' | 'line' | 'area';

function valueDomain(spec: ChartAxisOptions | undefined, dataMin: number, dataMax: number, expand: boolean): { domain: [number, number]; ticks: number[] } {
  if (expand) return { domain: [0, 1], ticks: niceTicks(0, 1, spec?.tickCount ?? 5) };
  const d = spec?.domain;
  const pick = (v: unknown, auto: number, data: number): number => (typeof v === 'number' ? v : v === 'dataMin' || v === 'dataMax' ? data : auto);
  const lo = pick(d?.[0], Math.min(0, dataMin), dataMin);
  const hi = pick(d?.[1], dataMax, dataMax);
  const ticks = niceTicks(lo, hi, spec?.tickCount ?? 5, spec?.allowDecimals ?? true);
  const [d0, d1] = d ?? [];
  if (typeof d0 === 'number' && typeof d1 === 'number') return { domain: [d0, d1], ticks: ticks.filter((t) => t >= d0 && t <= d1) };
  return { domain: [Math.min(lo, ticks[0]), Math.max(hi, ticks[ticks.length - 1])], ticks };
}

function dotProps(spec: boolean | ChartDotOptions | ChartDotRender | undefined, fallback: boolean): ChartDotOptions | ChartDotRender | null {
  if (spec === undefined) return fallback ? {} : null;
  if (spec === false) return null;
  if (spec === true) return {};
  return spec;
}

function drawDot(spec: ChartDotOptions | ChartDotRender, base: { cx: number; cy: number; r: number; fill: string; stroke: string; strokeWidth: number }, datum: ChartDatum, index: number, dataKey: string, cls: string) {
  if (typeof spec === 'function') return spec({ cx: base.cx, cy: base.cy, r: base.r, fill: base.fill, stroke: base.stroke, datum, index, dataKey });
  return svg`<circle cx=${fmt(base.cx)} cy=${fmt(base.cy)} r=${fmt(spec.r ?? base.r)} fill=${spec.fill ?? base.fill} fill-opacity=${spec.fillOpacity ?? nothing} stroke=${spec.stroke ?? base.stroke} stroke-width=${spec.strokeWidth ?? base.strokeWidth} class=${cn('ui-chart-dot', cls, spec.class)}></circle>`;
}

function cartesian(o: CartesianChartOptions, family: Family, all: ChartSeriesOptions[]) {
  const W = o.width ?? 450;
  const H = o.height ?? Math.round((W * 9) / 16);
  const margin = resolveMargin(o.margin);
  const vertical = o.layout === 'vertical';
  const xSpec = o.xAxis || undefined;
  const ySpec = o.yAxis || undefined;
  const catSpec = vertical ? ySpec : xSpec;
  const valSpec = vertical ? xSpec : ySpec;
  const xShown = !!xSpec && !xSpec.hide;
  const yShown = !!ySpec && !ySpec.hide;
  const xH = xShown ? xSpec.height ?? 30 : 0;
  const yW = yShown ? ySpec.width ?? 60 : 0;
  const legendH = o.legend ? o.legend.height ?? 28 : 0;
  const legendTop = !!o.legend && o.legend.verticalAlign === 'top';
  const plot = {
    x: margin.left + yW,
    y: margin.top + (legendTop ? legendH : 0),
    w: W - margin.left - margin.right - yW,
    h: H - margin.top - margin.bottom - xH - legendH,
  };
  const data = o.data;
  const series = all.filter((s) => !s.hide);
  const catKey = catSpec?.dataKey;
  const categories = data.map((d, i) => (catKey ? d[catKey] : i));

  // Values: each series' [low, high] per row, stacked by stackId.
  const offsetMode = o.stackOffset ?? (family === 'bar' ? 'sign' : 'none');
  const bands: Record<string, Array<[number, number]>> = {};
  const stacks = new Map<string, string[]>();
  for (const s of series) if (s.stackId != null) stacks.set(s.stackId, [...(stacks.get(s.stackId) ?? []), s.dataKey]);
  for (const keys of stacks.values()) Object.assign(bands, stackData(data, keys, offsetMode === 'expand' ? 'expand' : offsetMode === 'sign' ? 'sign' : 'none'));
  for (const s of series) if (s.stackId == null) bands[s.dataKey] = data.map((d) => [0, num(d[s.dataKey])]);
  const flat = series.flatMap((s) => bands[s.dataKey].flat());
  const { domain, ticks: valueTicks } = valueDomain(valSpec, flat.length ? Math.min(...flat) : 0, flat.length ? Math.max(...flat) : 0, offsetMode === 'expand');
  const vRange: [number, number] = vertical ? [plot.x, plot.x + plot.w] : [plot.y + plot.h, plot.y];
  const vScale = linearScale(domain, valSpec?.reversed ? [vRange[1], vRange[0]] : vRange);

  // Categories: bands under bars, points under lines and areas.
  const pad = catSpec?.padding ?? {};
  const c0 = vertical ? plot.y + (pad.top ?? 0) : plot.x + (pad.left ?? 0);
  const c1 = vertical ? plot.y + plot.h - (pad.bottom ?? 0) : plot.x + plot.w - (pad.right ?? 0);
  // A reversed category axis lays the rows out from the far end.
  const slot = (i: number) => (catSpec?.reversed ? data.length - 1 - i : i);
  const band = bandScale(data.length, c0, c1);
  const point = pointScale(data.length, c0, c1);
  const catAt = (i: number) => (family === 'bar' ? band.at(slot(i)) + band.bandwidth / 2 : point(slot(i)));
  const color = (s: ChartSeriesOptions) => (family === 'bar' ? s.fill : s.stroke ?? s.fill) ?? '#808080';
  const defaultIndex = o.tooltip ? o.tooltip.defaultIndex : undefined;

  // Grid lines at the value ticks and the category ticks.
  const g = o.grid;
  const gridLine = (x1: number, y1: number, x2: number, y2: number) => svg`<line stroke="#ccc" fill="none" stroke-dasharray=${(g && g.strokeDasharray) || nothing} x1=${fmt(x1)} y1=${fmt(y1)} x2=${fmt(x2)} y2=${fmt(y2)}></line>`;
  const valueCoords = valueTicks.map((t) => vScale(t));
  const catCoords = data.map((_, i) => catAt(i));
  const hLines = vertical ? catCoords : valueCoords;
  const vLines = vertical ? valueCoords : catCoords;
  const grid = g === undefined || g === false ? '' : svg`<g class=${cn('ui-chart-cartesian-grid', g.class)}>${g.horizontal === false ? '' : svg`<g class="ui-chart-cartesian-grid-horizontal">${hLines.map((y) => gridLine(plot.x, y, plot.x + plot.w, y))}</g>`}${g.vertical === false ? '' : svg`<g class="ui-chart-cartesian-grid-vertical">${vLines.map((x) => gridLine(x, plot.y, x, plot.y + plot.h))}</g>`}</g>`;

  // The hover cursor per point.
  const cursorOn = !!o.tooltip && o.tooltip.cursor !== false;
  const cursors = cursorOn
    ? data.map((_, i) => {
      if (family === 'bar') {
        const a = band.at(slot(i));
        return vertical
          ? svg`<path class="ui-chart-rectangle ui-chart-tooltip-cursor" fill="#ccc" d=${rectanglePath(plot.x, a, plot.w, band.bandwidth)}></path>`
          : svg`<path class="ui-chart-rectangle ui-chart-tooltip-cursor" fill="#ccc" d=${rectanglePath(a, plot.y, band.bandwidth, plot.h)}></path>`;
      }
      const c = catAt(i);
      return vertical
        ? svg`<path class="ui-chart-curve ui-chart-tooltip-cursor" stroke="#ccc" fill="none" d=${`M${fmt(plot.x)},${fmt(c)}L${fmt(plot.x + plot.w)},${fmt(c)}`}></path>`
        : svg`<path class="ui-chart-curve ui-chart-tooltip-cursor" stroke="#ccc" fill="none" d=${`M${fmt(c)},${fmt(plot.y)}L${fmt(c)},${fmt(plot.y + plot.h)}`}></path>`;
    })
    : [];

  // Marks.
  const slotIds: string[] = [];
  for (const s of series) { const id = s.stackId != null ? `stack:${s.stackId}` : `bar:${s.dataKey}`; if (!slotIds.includes(id)) slotIds.push(id); }
  const slotSpecs = slotIds.map((id) => ({ barSize: series.find((s) => (s.stackId != null ? `stack:${s.stackId}` : `bar:${s.dataKey}`) === id)?.barSize }));
  const positions = family === 'bar' ? barPositions(band.bandwidth, slotSpecs, o.barGap, o.barCategoryGap, o.maxBarSize) : [];

  const marks = series.map((s) => {
    const sb = bands[s.dataKey];
    if (family === 'bar') {
      const pos = positions[slotIds.indexOf(s.stackId != null ? `stack:${s.stackId}` : `bar:${s.dataKey}`)];
      const boxes = data.map((d, i) => {
        const [lo, hi] = sb[i];
        const a = band.at(slot(i)) + pos.offset;
        const box = vertical
          ? { x: vScale(lo), y: a, width: vScale(hi) - vScale(lo), height: pos.size }
          : { x: a, y: vScale(hi), width: pos.size, height: vScale(lo) - vScale(hi) };
        return { box, datum: d, index: i, fill: typeof d.fill === 'string' ? d.fill : s.fill };
      });
      return svg`<g class=${cn('ui-chart-layer ui-chart-bar', s.class)}><g class="ui-chart-layer ui-chart-bar-rectangles">${boxes.map(({ box, datum, index }) => {
        const fill = typeof datum.fill === 'string' ? datum.fill : s.fill ?? '#808080';
        const active = s.activeIndex === index ? s.activeBar ?? {} : null;
        const shape = s.shape
          ? s.shape({ ...box, radius: s.radius ?? 0, fill, datum, index, dataKey: s.dataKey, stroke: s.stroke, strokeWidth: s.strokeWidth, fillOpacity: s.fillOpacity })
          : svg`<path class="ui-chart-rectangle" fill=${active?.fill ?? fill} fill-opacity=${active?.fillOpacity ?? s.fillOpacity ?? nothing} stroke=${active?.stroke ?? s.stroke ?? nothing} stroke-width=${active?.strokeWidth ?? s.strokeWidth ?? nothing} stroke-dasharray=${active?.strokeDasharray ?? nothing} stroke-dashoffset=${active?.strokeDashoffset ?? nothing} d=${rectanglePath(box.x, box.y, box.width, box.height, s.radius ?? 0)}></path>`;
        return svg`<g class="ui-chart-layer ui-chart-bar-rectangle" data-index=${String(index)}>${shape}</g>`;
      })}</g>${labelList(s.labels, s.dataKey, boxes, 'center')}</g>`;
    }
    const top = data.map((_, i): Pt => (vertical ? [vScale(sb[i][1]), catAt(i)] : [catAt(i), vScale(sb[i][1])]));
    const curve = s.type ?? 'linear';
    const stroke = s.stroke ?? '#3182bd';
    const pts = top.map((p, i) => ({ box: { x: p[0], y: p[1], width: 0, height: 0 }, datum: data[i], index: i }));
    const dot = dotProps(s.dot, family === 'line');
    const dots = dot
      ? svg`<g class="ui-chart-layer ui-chart-dots">${top.map((p, i) => drawDot(dot, { cx: p[0], cy: p[1], r: 3, fill: family === 'line' ? '#fff' : s.fill ?? stroke, stroke, strokeWidth: s.strokeWidth ?? 1 }, data[i], i, s.dataKey, family === 'line' ? 'ui-chart-line-dot' : 'ui-chart-area-dot'))}</g>`
      : '';
    if (family === 'line') {
      return svg`<g class=${cn('ui-chart-layer ui-chart-line', s.class)}><path class="ui-chart-curve ui-chart-line-curve" fill="none" stroke=${stroke} stroke-width=${s.strokeWidth ?? 1} stroke-dasharray=${s.strokeDasharray ?? nothing} d=${curvePath(top, curve)}></path>${dots}${labelList(s.labels, s.dataKey, pts, 'top')}</g>`;
    }
    const bottom = data.map((_, i): Pt => {
      const lo = s.stackId != null ? sb[i][0] : Math.max(domain[0], Math.min(0, domain[1]));
      return vertical ? [vScale(lo), catAt(i)] : [catAt(i), vScale(lo)];
    }).reverse();
    const area = `${curvePath(top, curve)}${curvePath(bottom, curve, 'L')}Z`;
    return svg`<g class=${cn('ui-chart-layer ui-chart-area', s.class)}><path class="ui-chart-curve ui-chart-area-area" fill=${s.fill ?? '#3182bd'} fill-opacity=${s.fillOpacity ?? 0.6} stroke="none" d=${area}></path><path class="ui-chart-curve ui-chart-area-curve" fill="none" stroke=${stroke} stroke-width=${s.strokeWidth ?? 1} stroke-dasharray=${s.strokeDasharray ?? nothing} d=${curvePath(top, curve)}></path>${dots}${labelList(s.labels, s.dataKey, pts, 'top')}</g>`;
  });

  // Active dots per point (lines and areas).
  const actives = family === 'bar' || !o.tooltip
    ? []
    : data.map((_, i) => series.map((s) => {
      if (s.activeDot === false) return '';
      const sb = bands[s.dataKey];
      const [cx, cy] = vertical ? [vScale(sb[i][1]), catAt(i)] : [catAt(i), vScale(sb[i][1])];
      const spec = typeof s.activeDot === 'object' ? s.activeDot : {};
      return drawDot(spec, { cx, cy, r: 4, fill: s.stroke ?? s.fill ?? '#3182bd', stroke: '#fff', strokeWidth: 2 }, data[i], i, s.dataKey, 'ui-chart-active-dot');
    }));

  // Axes.
  const axis = (which: 'x' | 'y') => {
    const spec = which === 'x' ? xSpec : ySpec;
    if (!spec || spec.hide) return '';
    const isCat = (which === 'x') !== vertical;
    const fmtTick = (v: unknown, i: number) => (spec.tickFormatter ? spec.tickFormatter(v, i) : v);
    const ticks: Tick[] = isCat
      ? categories.map((v, i) => ({ value: v, label: fmtTick(v, i), coord: catAt(i) }))
      : valueTicks.map((v, i) => ({ value: v, label: fmtTick(v, i), coord: vScale(v) }));
    const size = (t: Tick) => (which === 'x' ? estimateTextWidth(String(t.label ?? '')) : 14);
    const interval = spec.interval ?? 'preserveEnd';
    const minTickGap = spec.minTickGap ?? 5;
    // Every tick is served; the ones that do not fit are hidden. The server
    // can only estimate a label's width, so the element measures the real
    // text and thins the ticks again (see `_fitTicks`).
    const shown = new Map(visibleTicks(ticks, size, 0, which === 'x' ? W : H, minTickGap, interval).map((t) => [t.coord, t.at ?? t.coord]));
    const all = spec.tick === false ? [] : ticks;
    const tickSize = spec.tickSize ?? 6;
    const margin2 = spec.tickMargin ?? 2;
    const edge = which === 'x' ? plot.y + plot.h : plot.x;
    const line = spec.axisLine === false ? '' : which === 'x'
      ? svg`<line class="ui-chart-cartesian-axis-line" stroke="#666" fill="none" x1=${fmt(plot.x)} y1=${fmt(edge)} x2=${fmt(plot.x + plot.w)} y2=${fmt(edge)}></line>`
      : svg`<line class="ui-chart-cartesian-axis-line" stroke="#666" fill="none" x1=${fmt(edge)} y1=${fmt(plot.y)} x2=${fmt(edge)} y2=${fmt(plot.y + plot.h)}></line>`;
    return svg`<g class=${cn('ui-chart-layer ui-chart-cartesian-axis', which === 'x' ? 'ui-chart-xAxis' : 'ui-chart-yAxis', spec.class)} data-axis=${which} data-gap=${String(minTickGap)} data-interval=${String(interval)} data-extent=${fmt(which === 'x' ? W : H)}>${line}<g class="ui-chart-cartesian-axis-ticks">${all.map((t) => {
      const at = shown.get(t.coord) ?? t.coord;
      const tl = spec.tickLine === false ? '' : which === 'x'
        ? svg`<line class="ui-chart-cartesian-axis-tick-line" stroke="#666" fill="none" x1=${fmt(at)} y1=${fmt(edge + tickSize)} x2=${fmt(at)} y2=${fmt(edge)}></line>`
        : svg`<line class="ui-chart-cartesian-axis-tick-line" stroke="#666" fill="none" x1=${fmt(edge - tickSize)} y1=${fmt(at)} x2=${fmt(edge)} y2=${fmt(at)}></line>`;
      const text = which === 'x'
        ? chartText(at, edge + tickSize + margin2, t.label, { anchor: 'middle', vAnchor: 'start', fill: '#666', class: 'ui-chart-cartesian-axis-tick-value' })
        : chartText(edge - tickSize - margin2, at, t.label, { anchor: 'end', vAnchor: 'middle', fill: '#666', class: 'ui-chart-cartesian-axis-tick-value' });
      return svg`<g class="ui-chart-layer ui-chart-cartesian-axis-tick" data-coord=${fmt(t.coord)} visibility=${shown.has(t.coord) ? nothing : 'hidden'}>${tl}${text}</g>`;
    })}</g></g>`;
  };

  // Tooltip points: the series at each row, anchored where Recharts puts a
  // tooltip it opens without a pointer (combineCoordinateForDefaultIndex):
  // on the category, halfway between the plot's near edge and the chart's far one.
  const points: ChartPoint[] = data.map((d, i) => ({
    label: categories[i],
    payload: series.map((s) => ({ dataKey: s.dataKey, name: s.name ?? s.dataKey, value: d[s.dataKey], color: color(s), payload: d })),
    x: vertical ? (plot.x + W) / 2 : catAt(i),
    y: vertical ? catAt(i) : (plot.y + H) / 2,
  }));

  const body = svg`${grid}${overlay('chart-cursor', cursors, defaultIndex)}${marks}${axis('x')}${axis('y')}${actives.length ? overlay('chart-active', actives, defaultIndex) : ''}`;
  return frame(o, {
    width: W, height: H, hit: vertical ? 'y' : 'x', body, points, margin, plot, fit: true,
    legend: series.map((s) => ({ dataKey: s.dataKey, name: s.name ?? s.dataKey, value: s.name ?? s.dataKey, color: color(s), payload: {} })),
  });
}

/** A bar chart: Recharts' `<BarChart>` with its `<Bar>`s. */
export function barChart(o: CartesianChartOptions & { bars: ChartSeriesOptions[] }) {
  return cartesian(o, 'bar', o.bars);
}

/** A line chart: Recharts' `<LineChart>` with its `<Line>`s. */
export function lineChart(o: CartesianChartOptions & { lines: ChartSeriesOptions[] }) {
  return cartesian(o, 'line', o.lines);
}

/** An area chart: Recharts' `<AreaChart>` with its `<Area>`s. */
export function areaChart(o: CartesianChartOptions & { areas: ChartSeriesOptions[] }) {
  return cartesian(o, 'area', o.areas);
}

// --------------------------------------------------------------------------
// Polar charts: pie, radar, radial bar
// --------------------------------------------------------------------------

/** Where a polar chart sits: its centre and radii, what a `center` label receives. */
export interface ChartPolarBox { cx: number; cy: number; innerRadius: number; outerRadius: number }

export interface ChartSectorProps extends SectorGeometry {
  fill: string;
  stroke: string;
  strokeWidth: number;
  datum: ChartDatum;
  index: number;
  value: number;
  midAngle: number;
}

/** A sector as the kit draws one, for a custom `shape` / `activeShape` to reuse. */
export function chartSector(p: Partial<ChartSectorProps> & SectorGeometry, cls = '') {
  return svg`<path class=${cn('ui-chart-sector', cls)} fill=${p.fill ?? nothing} stroke=${p.stroke ?? nothing} stroke-width=${p.strokeWidth ?? nothing} d=${sectorPath(p)}></path>`;
}

export interface ChartPieOptions {
  dataKey: string;
  nameKey?: string;
  /** This ring's own rows (two rings of a stacked pie), else the chart's `data`. */
  data?: ChartDatum[];
  innerRadius?: number | string;
  outerRadius?: number | string;
  cx?: number | string;
  cy?: number | string;
  startAngle?: number;
  endAngle?: number;
  paddingAngle?: number;
  cornerRadius?: number;
  fill?: string;
  stroke?: string;
  strokeWidth?: number;
  /** Slice labels outside the pie: true, options, or a render function. */
  label?: boolean | { offsetRadius?: number; class?: string; fill?: string; fontSize?: number }
    | ((props: { x: number; y: number; cx: number; cy: number; midAngle: number; innerRadius: number; outerRadius: number; value: unknown; datum: ChartDatum; index: number; fill: string; textAnchor: 'start' | 'middle' | 'end' }) => unknown);
  labelLine?: boolean;
  /** LabelLists on the slices (`position` `inside` by default, or `outside`). */
  labels?: ChartLabelOptions[];
  activeIndex?: number;
  /** How the active slice draws: a render function, or a larger outer radius. */
  activeShape?: ((props: ChartSectorProps) => unknown) | { outerRadius?: number };
  shape?: (props: ChartSectorProps) => unknown;
  /** Content at the centre (a donut's total), shadcn's `<Label content>`. */
  center?: (box: ChartPolarBox) => unknown;
  class?: string;
}

function polarPlot(o: ChartBaseOptions, W: number, H: number) {
  const m = resolveMargin(o.margin);
  const legendH = o.legend ? o.legend.height ?? 28 : 0;
  const top = m.top + (o.legend && o.legend.verticalAlign === 'top' ? legendH : 0);
  return { m, x: m.left, y: top, w: W - m.left - m.right, h: H - m.top - m.bottom - legendH };
}

function anchorOf(x: number, cx: number): 'start' | 'middle' | 'end' {
  return x > cx ? 'start' : x < cx ? 'end' : 'middle';
}

/** A pie or donut chart: Recharts' `<PieChart>` with its `<Pie>`s. */
export function pieChart(o: ChartBaseOptions & { pies: ChartPieOptions[] }) {
  const W = o.width ?? 250;
  const H = o.height ?? W;
  const plot = polarPlot(o, W, H);
  const maxR = Math.min(plot.w, plot.h) / 2;
  const points: ChartPoint[] = [];
  const legend: ChartPayloadItem[] = [];
  const rings = o.pies.map((p) => {
    const rows = p.data ?? o.data;
    const cx = plot.x + percent(p.cx, plot.w, plot.w / 2);
    const cy = plot.y + percent(p.cy, plot.h, plot.h / 2);
    const innerRadius = percent(p.innerRadius, maxR, 0);
    const outerRadius = percent(p.outerRadius, maxR, maxR * 0.8);
    const start = p.startAngle ?? 0;
    const end = p.endAngle ?? 360;
    const delta = Math.sign(end - start) * Math.min(Math.abs(end - start), 360);
    const values = rows.map((d) => num(d[p.dataKey]));
    const nonZero = values.filter((v) => v !== 0).length;
    const padding = rows.length <= 1 ? 0 : p.paddingAngle ?? 0;
    const real = Math.abs(delta) - (Math.abs(delta) >= 360 ? nonZero : nonZero - 1) * padding;
    const sum = values.reduce((s, v) => s + v, 0);
    let prevEnd = start;
    const sectors = rows.map((d, i) => {
      const v = values[i];
      const s0 = i ? prevEnd + Math.sign(delta) * padding * (v !== 0 ? 1 : 0) : start;
      const s1 = s0 + Math.sign(delta) * (sum > 0 ? (v / sum) * real : 0);
      prevEnd = s1;
      const fill = typeof d.fill === 'string' ? d.fill : p.fill ?? '#808080';
      return { cx, cy, innerRadius, outerRadius, startAngle: s0, endAngle: s1, cornerRadius: p.cornerRadius, fill, stroke: p.stroke ?? '#fff', strokeWidth: p.strokeWidth ?? 1, datum: d, index: i, value: v, midAngle: (s0 + s1) / 2 };
    });
    const base = points.length;
    sectors.forEach((s) => {
      const name = String(p.nameKey ? s.datum[p.nameKey] ?? s.index : s.index);
      const item = { dataKey: p.dataKey, name, value: s.datum[p.dataKey], color: s.fill, payload: s.datum };
      const at = polarToCartesian(s.cx, s.cy, (s.innerRadius + s.outerRadius) / 2, s.midAngle);
      points.push({ label: name, payload: [item], x: at.x, y: at.y });
      if (p === o.pies[0]) legend.push({ ...item, value: name });
    });
    const drawn = sectors.map((s) => {
      const isActive = p.activeIndex === s.index && p.activeShape;
      let shape: unknown;
      if (isActive && typeof p.activeShape === 'function') shape = p.activeShape(s);
      else if (isActive && typeof p.activeShape === 'object') shape = chartSector({ ...s, outerRadius: p.activeShape.outerRadius ?? s.outerRadius });
      else shape = p.shape ? p.shape(s) : chartSector(s);
      return svg`<g class="ui-chart-layer ui-chart-pie-sector" data-index=${String(base + s.index)}>${shape}</g>`;
    });
    let labels: unknown = '';
    if (p.label) {
      const lo = typeof p.label === 'object' ? p.label : {};
      const offsetR = lo.offsetRadius ?? 20;
      labels = svg`<g class="ui-chart-layer ui-chart-pie-labels">${sectors.map((s) => {
        const e = polarToCartesian(s.cx, s.cy, s.outerRadius + offsetR, s.midAngle);
        const a = polarToCartesian(s.cx, s.cy, s.outerRadius, s.midAngle);
        const anchor = anchorOf(e.x, s.cx);
        const line = p.labelLine === false ? '' : svg`<path class="ui-chart-curve ui-chart-pie-label-line" fill="none" stroke=${s.fill} d=${`M${fmt(a.x, 3)},${fmt(a.y, 3)}L${fmt(e.x, 3)},${fmt(e.y, 3)}`}></path>`;
        const text = typeof p.label === 'function'
          ? p.label({ x: e.x, y: e.y, cx: s.cx, cy: s.cy, midAngle: s.midAngle, innerRadius: s.innerRadius, outerRadius: s.outerRadius, value: s.datum[p.dataKey], datum: s.datum, index: s.index, fill: s.fill, textAnchor: anchor })
          : chartText(e.x, e.y, s.datum[p.dataKey], { anchor, fill: lo.fill ?? s.fill, stroke: 'none', fontSize: lo.fontSize, baseline: 'middle', class: cn('ui-chart-pie-label-text', lo.class) });
        return svg`<g class="ui-chart-layer">${line}${text}</g>`;
      })}</g>`;
    }
    const lists = (p.labels ?? []).map((l) => svg`<g class="ui-chart-label-list">${sectors.map((s) => {
      const raw = s.datum[l.dataKey ?? p.dataKey];
      const value = l.formatter ? l.formatter(raw, s.datum, s.index) : raw;
      const outside = l.position === 'outside';
      const at = polarToCartesian(s.cx, s.cy, outside ? s.outerRadius + (l.offset ?? 5) : (s.innerRadius + s.outerRadius) / 2, s.midAngle);
      if (l.content) return l.content({ x: at.x, y: at.y, width: 0, height: 0, value, datum: s.datum, index: s.index });
      return chartText(at.x, at.y, value, { anchor: outside ? (at.x >= s.cx ? 'start' : 'end') : 'middle', vAnchor: 'middle', class: cn('ui-chart-label', l.class), fill: l.fill, stroke: l.stroke, fontSize: l.fontSize });
    })}</g>`);
    const center = p.center ? p.center({ cx, cy, innerRadius, outerRadius }) : '';
    return svg`<g class=${cn('ui-chart-layer ui-chart-pie', p.class)}><g class="ui-chart-layer">${drawn}</g>${labels}${lists}${center}</g>`;
  });
  return frame(o, { width: W, height: H, hit: 'target', body: rings, points, legend, margin: plot.m, plot });
}

export interface ChartRadarOptions {
  dataKey: string;
  name?: string;
  fill?: string;
  fillOpacity?: number;
  stroke?: string;
  strokeWidth?: number;
  dot?: boolean | ChartDotOptions | ChartDotRender;
  activeDot?: boolean | ChartDotOptions;
  labels?: ChartLabelOptions[];
  class?: string;
}

export interface ChartPolarGridOptions {
  gridType?: 'polygon' | 'circle';
  radialLines?: boolean;
  /** The ring radii, else the radius axis ticks. */
  polarRadius?: number[];
  class?: string;
  fill?: string;
  stroke?: string;
  strokeWidth?: number;
}

export interface ChartPolarAngleAxisOptions {
  dataKey?: string;
  tickFormatter?: (value: unknown, index: number) => unknown;
  /** false hides the labels; a function draws each one. */
  tick?: boolean | ((props: { x: number; y: number; textAnchor: 'start' | 'middle' | 'end'; value: unknown; label: unknown; index: number; datum: ChartDatum }) => unknown);
  class?: string;
}

export interface ChartPolarRadiusAxisOptions {
  angle?: number;
  orientation?: 'left' | 'right' | 'middle';
  tickCount?: number;
  domain?: [number, number];
  tick?: boolean;
  tickFormatter?: (value: unknown, index: number) => unknown;
  class?: string;
  stroke?: string;
}

function polarGrid(g: ChartPolarGridOptions | false | undefined, cx: number, cy: number, radii: number[], angles: number[], outer: number, inner = 0) {
  if (!g) return '';
  const ring = (r: number) => (g.gridType === 'circle'
    ? svg`<circle class=${cn('ui-chart-polar-grid-concentric-circle', g.class)} stroke=${g.stroke ?? '#ccc'} stroke-width=${g.strokeWidth ?? nothing} fill=${g.fill ?? 'none'} cx=${fmt(cx)} cy=${fmt(cy)} r=${fmt(r)}></circle>`
    : svg`<path class=${cn('ui-chart-polar-grid-concentric-polygon', g.class)} stroke=${g.stroke ?? '#ccc'} stroke-width=${g.strokeWidth ?? nothing} fill=${g.fill ?? 'none'} d=${polygonPath(angles.map((a) => polarToCartesian(cx, cy, r, a)))}></path>`);
  return svg`<g class="ui-chart-polar-grid"><g class="ui-chart-polar-grid-concentric">${radii.map(ring)}</g>${g.radialLines === false ? '' : svg`<g class="ui-chart-polar-grid-angle">${angles.map((a) => {
    const b = polarToCartesian(cx, cy, inner, a);
    const e = polarToCartesian(cx, cy, outer, a);
    return svg`<line class=${cn('ui-chart-polar-grid-angle-line', g.class)} stroke=${g.stroke ?? '#ccc'} x1=${fmt(b.x)} y1=${fmt(b.y)} x2=${fmt(e.x)} y2=${fmt(e.y)}></line>`;
  })}</g>`}</g>`;
}

/** A radar chart: Recharts' `<RadarChart>` with its `<Radar>`s, grid and axes. */
export function radarChart(o: ChartBaseOptions & {
  radars: ChartRadarOptions[];
  cx?: number | string;
  cy?: number | string;
  innerRadius?: number | string;
  outerRadius?: number | string;
  startAngle?: number;
  endAngle?: number;
  grid?: ChartPolarGridOptions | false;
  angleAxis?: ChartPolarAngleAxisOptions | false;
  radiusAxis?: ChartPolarRadiusAxisOptions | false;
}) {
  const W = o.width ?? 250;
  const H = o.height ?? W;
  const plot = polarPlot(o, W, H);
  const maxR = Math.min(plot.w, plot.h) / 2;
  // The centre is a share of the whole chart (Recharts' selectPolarViewBox),
  // while the radius comes from the plot inside the margins.
  const cx = percent(o.cx, W, W / 2);
  const cy = percent(o.cy, H, H / 2);
  const inner = percent(o.innerRadius, maxR, 0);
  const outer = percent(o.outerRadius, maxR, maxR * 0.8);
  const data = o.data;
  const n = data.length;
  const start = o.startAngle ?? 90;
  const end = o.endAngle ?? -270;
  const angles = data.map((_, i) => start + (i * (end - start)) / (n || 1));
  const aSpec = o.angleAxis || undefined;
  const rSpec = o.radiusAxis || undefined;
  const all = o.radars.flatMap((r) => data.map((d) => num(d[r.dataKey])));
  const ticks = rSpec?.domain ? niceTicks(rSpec.domain[0], rSpec.domain[1], rSpec.tickCount ?? 5).filter((t) => t >= rSpec.domain![0] && t <= rSpec.domain![1]) : niceTicks(Math.min(0, ...all), Math.max(...all, 0), rSpec?.tickCount ?? 5);
  const domain: [number, number] = rSpec?.domain ?? [ticks[0], ticks[ticks.length - 1]];
  const rScale = linearScale(domain, [inner, outer]);
  const defaultIndex = o.tooltip ? o.tooltip.defaultIndex : undefined;
  const at = (r: ChartRadarOptions, i: number) => polarToCartesian(cx, cy, rScale(num(data[i][r.dataKey])), angles[i]);
  const colorOf = (r: ChartRadarOptions) => r.stroke ?? r.fill ?? '#808080';
  const grid = polarGrid(o.grid, cx, cy, o.grid && o.grid.polarRadius ? o.grid.polarRadius : ticks.map(rScale), angles, outer);
  const radars = o.radars.map((r) => {
    const pts = data.map((_, i) => at(r, i));
    const dot = dotProps(r.dot, false);
    return svg`<g class=${cn('ui-chart-layer ui-chart-radar', r.class)}><g class="ui-chart-layer ui-chart-radar-polygon"><path class="ui-chart-polygon" fill=${r.fill ?? nothing} fill-opacity=${r.fillOpacity ?? nothing} stroke=${r.stroke ?? nothing} stroke-width=${r.strokeWidth ?? nothing} d=${polygonPath(pts)}></path></g>${dot ? svg`<g class="ui-chart-layer ui-chart-radar-dots">${pts.map((q, i) => drawDot(dot, { cx: q.x, cy: q.y, r: 3, fill: r.fill ?? '#808080', stroke: r.stroke ?? 'none', strokeWidth: r.strokeWidth ?? 1 }, data[i], i, r.dataKey, 'ui-chart-radar-dot'))}</g>` : ''}${labelList(r.labels, r.dataKey, pts.map((q, i) => ({ box: { x: q.x, y: q.y, width: 0, height: 0 }, datum: data[i], index: i })), 'top')}</g>`;
  });
  const angleAxis = aSpec ? svg`<g class=${cn('ui-chart-layer ui-chart-polar-angle-axis', aSpec.class)}>${aSpec.tick === false ? '' : data.map((d, i) => {
    const value = aSpec.dataKey ? d[aSpec.dataKey] : i;
    const label = aSpec.tickFormatter ? aSpec.tickFormatter(value, i) : value;
    const p = polarToCartesian(cx, cy, outer + 8, angles[i]);
    const cos = Math.cos(-RADIAN * angles[i]);
    const anchor = cos > 1e-5 ? 'start' : cos < -1e-5 ? 'end' : 'middle';
    if (typeof aSpec.tick === 'function') return aSpec.tick({ x: p.x, y: p.y, textAnchor: anchor, value, label, index: i, datum: d });
    const sin = Math.sin(-RADIAN * angles[i]);
    const vAnchor: VAnchor = anchor !== 'middle' ? 'middle' : sin < 0 ? 'end' : 'start';
    return svg`<g class="ui-chart-layer ui-chart-polar-angle-axis-tick">${chartText(p.x, p.y, label, { anchor, vAnchor, fill: '#808080', class: 'ui-chart-polar-angle-axis-tick-value' })}</g>`;
  })}</g>` : '';
  const radiusAxis = rSpec && rSpec.tick !== false ? svg`<g class=${cn('ui-chart-layer ui-chart-polar-radius-axis', rSpec.class)}>${ticks.map((t, i) => {
    const p = polarToCartesian(cx, cy, rScale(t), rSpec.angle ?? 0);
    const anchor = rSpec.orientation === 'left' ? 'end' : rSpec.orientation === 'middle' ? 'middle' : 'start';
    return chartText(p.x, p.y, rSpec.tickFormatter ? rSpec.tickFormatter(t, i) : t, { anchor, vAnchor: 'middle', fill: rSpec.stroke ?? '#808080', class: 'ui-chart-polar-radius-axis-tick-value' });
  })}</g>` : '';
  const cursors = o.tooltip && o.tooltip.cursor !== false
    ? angles.map((a) => { const e = polarToCartesian(cx, cy, outer, a); return svg`<path class="ui-chart-curve ui-chart-tooltip-cursor" stroke="#ccc" fill="none" d=${`M${fmt(cx)},${fmt(cy)}L${fmt(e.x)},${fmt(e.y)}`}></path>`; })
    : [];
  const actives = o.tooltip
    ? data.map((_, i) => o.radars.map((r) => {
      if (r.activeDot === false) return '';
      const q = at(r, i);
      return drawDot(typeof r.activeDot === 'object' ? r.activeDot : {}, { cx: q.x, cy: q.y, r: 4, fill: colorOf(r), stroke: '#fff', strokeWidth: 2 }, data[i], i, r.dataKey, 'ui-chart-active-dot');
    }))
    : [];
  // Hit wedges: each point owns the angles nearer to it than to its neighbours.
  const step = n ? (end - start) / n : 0;
  const hits = o.tooltip ? svg`<g data-slot="chart-hit">${angles.map((a, i) => svg`<path data-index=${String(i)} fill="transparent" d=${sectorPath({ cx, cy, innerRadius: 0, outerRadius: outer + 8, startAngle: a - step / 2, endAngle: a + step / 2 })}></path>`)}</g>` : '';
  const points: ChartPoint[] = data.map((d, i) => {
    const q = o.radars.length ? at(o.radars[0], i) : { x: cx, y: cy };
    return { label: aSpec && aSpec.dataKey ? d[aSpec.dataKey] : i, payload: o.radars.map((r) => ({ dataKey: r.dataKey, name: r.name ?? r.dataKey, value: d[r.dataKey], color: colorOf(r), payload: d })), x: q.x, y: q.y };
  });
  const body = svg`${grid}${overlay('chart-cursor', cursors, defaultIndex)}${radars}${angleAxis}${radiusAxis}${actives.length ? overlay('chart-active', actives, defaultIndex) : ''}${hits}`;
  return frame(o, { width: W, height: H, hit: 'target', body, points, margin: plot.m, plot, legend: o.radars.map((r) => ({ dataKey: r.dataKey, name: r.name ?? r.dataKey, value: r.name ?? r.dataKey, color: colorOf(r), payload: {} })) });
}

export interface ChartRadialBarOptions {
  dataKey: string;
  name?: string;
  fill?: string;
  stackId?: string;
  cornerRadius?: number;
  /** The track behind each bar: true, or its fill and classes. */
  background?: boolean | { fill?: string; class?: string };
  /** LabelLists along the bars (`insideStart`, `insideEnd`, `end`, or a cartesian position at the bar's middle). */
  labels?: ChartLabelOptions[];
  class?: string;
}

let radialLabelSeq = 0;

/** A radial bar chart: Recharts' `<RadialBarChart>` with its `<RadialBar>`s. */
export function radialBarChart(o: ChartBaseOptions & {
  bars: ChartRadialBarOptions[];
  cx?: number | string;
  cy?: number | string;
  innerRadius?: number | string;
  outerRadius?: number | string;
  startAngle?: number;
  endAngle?: number;
  barSize?: number;
  barGap?: number | string;
  barCategoryGap?: number | string;
  /** The value axis's extent, default `[0, largest value]`. */
  domain?: [number, number];
  grid?: ChartPolarGridOptions | false;
  center?: (box: ChartPolarBox) => unknown;
}) {
  const W = o.width ?? 250;
  const H = o.height ?? W;
  const plot = polarPlot(o, W, H);
  const maxR = Math.min(plot.w, plot.h) / 2;
  // The centre is a share of the whole chart (Recharts' selectPolarViewBox),
  // while the radius comes from the plot inside the margins.
  const cx = percent(o.cx, W, W / 2);
  const cy = percent(o.cy, H, H / 2);
  const inner = percent(o.innerRadius, maxR, 0);
  const outer = percent(o.outerRadius, maxR, maxR * 0.8);
  const start = o.startAngle ?? 0;
  const end = o.endAngle ?? 360;
  const data = o.data;
  const stacks = new Map<string, string[]>();
  for (const s of o.bars) if (s.stackId != null) stacks.set(s.stackId, [...(stacks.get(s.stackId) ?? []), s.dataKey]);
  const bands: Record<string, Array<[number, number]>> = {};
  for (const keys of stacks.values()) Object.assign(bands, stackData(data, keys));
  for (const s of o.bars) if (s.stackId == null) bands[s.dataKey] = data.map((d) => [0, num(d[s.dataKey])]);
  const max = Math.max(0, ...o.bars.flatMap((s) => bands[s.dataKey].map((b) => b[1])));
  const aScale = linearScale(o.domain ?? [0, max], [start, end]);
  const band = bandScale(data.length, inner, outer);
  const slotIds: string[] = [];
  for (const s of o.bars) { const id = s.stackId != null ? `stack:${s.stackId}` : `bar:${s.dataKey}`; if (!slotIds.includes(id)) slotIds.push(id); }
  const positions = barPositions(band.bandwidth, slotIds.map(() => ({ barSize: o.barSize })), o.barGap, o.barCategoryGap);
  const seq = ++radialLabelSeq;
  const points: ChartPoint[] = data.map((d, i) => ({ label: i, payload: [], x: cx, y: cy }));
  const backgrounds: unknown[] = [];
  const bars = o.bars.map((s, si) => {
    const pos = positions[slotIds.indexOf(s.stackId != null ? `stack:${s.stackId}` : `bar:${s.dataKey}`)];
    const sectors = data.map((d, i) => {
      const r0 = band.at(i) + pos.offset;
      const [lo, hi] = bands[s.dataKey][i];
      const fill = typeof d.fill === 'string' ? d.fill : s.fill ?? '#808080';
      const sec = { cx, cy, innerRadius: r0, outerRadius: r0 + pos.size, startAngle: aScale(lo), endAngle: aScale(hi), cornerRadius: s.cornerRadius, fill, datum: d, index: i };
      points[i].payload.push({ dataKey: s.dataKey, name: s.name ?? s.dataKey, value: d[s.dataKey], color: fill, payload: d });
      if (si === 0) {
        const q = polarToCartesian(cx, cy, r0 + pos.size / 2, (sec.startAngle + sec.endAngle) / 2);
        points[i].x = q.x;
        points[i].y = q.y;
      }
      if (s.background) {
        const bg = typeof s.background === 'object' ? s.background : {};
        backgrounds.push(svg`<g class="ui-chart-layer" data-index=${String(i)}><path class=${cn('ui-chart-sector ui-chart-radial-bar-background-sector', bg.class)} fill=${bg.fill ?? '#eee'} d=${sectorPath({ ...sec, startAngle: start, endAngle: end })}></path></g>`);
      }
      return sec;
    });
    const labels = (s.labels ?? []).map((l, li) => svg`<g class="ui-chart-label-list">${sectors.map((sec) => {
      const raw = sec.datum[l.dataKey ?? s.dataKey];
      const value = l.formatter ? l.formatter(raw, sec.datum, sec.index) : raw;
      const pos2 = l.position ?? 'insideStart';
      const offset = l.offset ?? 5;
      const r = (sec.innerRadius + sec.outerRadius) / 2;
      if (pos2 === 'insideStart' || pos2 === 'insideEnd' || pos2 === 'end') {
        const sign = sec.endAngle - sec.startAngle >= 0 ? 1 : -1;
        const angle = pos2 === 'insideStart' ? sec.startAngle + sign * offset : pos2 === 'insideEnd' ? sec.endAngle - sign * offset : sec.endAngle + sign * offset;
        let dir = pos2 === 'insideEnd';
        dir = sign <= 0 ? dir : !dir;
        const p0 = polarToCartesian(cx, cy, r, angle);
        const p1 = polarToCartesian(cx, cy, r, angle + (dir ? 1 : -1) * 359);
        const id = `ui-chart-radial-label-${seq}-${si}-${li}-${sec.index}`;
        return svg`<text dominant-baseline="central" fill=${l.fill ?? nothing} font-size=${l.fontSize != null ? `${fmt(l.fontSize / 12)}em` : nothing} class=${cn('ui-chart-radial-bar-label', l.class)}><defs><path id=${id} d=${`M${fmt(p0.x)},${fmt(p0.y)} A${fmt(r)},${fmt(r)},0,1,${dir ? 0 : 1},${fmt(p1.x)},${fmt(p1.y)}`}></path></defs><textPath href=${`#${id}`}>${value}</textPath></text>`;
      }
      const q = polarToCartesian(cx, cy, r, (sec.startAngle + sec.endAngle) / 2);
      return chartText(q.x, q.y, value, { anchor: 'middle', vAnchor: 'middle', class: cn('ui-chart-label', l.class), fill: l.fill, fontSize: l.fontSize });
    })}</g>`);
    return svg`<g class=${cn('ui-chart-layer ui-chart-radial-bar', s.class)}><g class="ui-chart-layer ui-chart-radial-bar-sectors">${sectors.map((sec) => svg`<g class="ui-chart-layer" data-index=${String(sec.index)}>${chartSector(sec, 'ui-chart-radial-bar-sector')}</g>`)}</g>${labels}</g>`;
  });
  // The rings sit on the bands, the spokes on the value axis's d3 ticks.
  const spokes = linearTicks(...(o.domain ?? [0, max])).map((t) => aScale(t));
  const grid = polarGrid(o.grid, cx, cy, o.grid && o.grid.polarRadius ? o.grid.polarRadius : data.map((_, i) => band.at(i) + band.bandwidth / 2), spokes, outer, inner);
  const center = o.center ? o.center({ cx, cy, innerRadius: inner, outerRadius: outer }) : '';
  return frame(o, {
    width: W, height: H, hit: 'target', body: svg`${grid}<g class="ui-chart-layer ui-chart-radial-bar-background">${backgrounds}</g>${bars}${center}`, points, margin: plot.m, plot,
    legend: data.map((d, i) => ({ dataKey: o.bars[0]?.dataKey ?? 'value', name: String(i), value: String(i), color: typeof d.fill === 'string' ? d.fill : o.bars[0]?.fill ?? '#808080', payload: d })),
  });
}
````

```ts title="components/ui/chart-element.ts"
/**
 * The chart's browser half (#1666): the `<ui-chart>` element, and the
 * tooltip and legend markup it draws (shadcn's ChartTooltipContent and
 * ChartLegendContent), with the ChartConfig types they share. `chart.ts`
 * draws the charts on the server with the same markup, and imports and
 * re-exports everything here, so an app imports the chart module alone.
 *
 * A11y (handled by the element): once upgraded, a chart with a tooltip is a
 * focusable `role="application"` named by its `title`, the arrow keys and
 * Home / End step through its points, Escape hides the tooltip, and each
 * step is announced through a polite live region.
 */
import { WebComponent, html, render } from '@webjsdev/core';
import { cn } from '../lib/utils.ts';
import { formatValue, visibleTicks, type Tick } from './chart-geometry.ts';

// --------------------------------------------------------------------------
// Types
// --------------------------------------------------------------------------

/** shadcn's ChartConfig: a label, and a colour or a light and dark pair, per key. */
export interface ChartConfigItem {
  label?: string;
  /** An icon for the tooltip and legend, a function returning an `html` / `svg` template. */
  icon?: () => unknown;
  color?: string;
  theme?: { light: string; dark: string };
}
export type ChartConfig = Record<string, ChartConfigItem>;

/** One row of chart data. */
export type ChartDatum = Record<string, unknown>;

export interface Margin { top: number; right: number; bottom: number; left: number }

/** One entry of a tooltip or legend payload, Recharts' shape. */
export interface ChartPayloadItem {
  dataKey: string;
  name: string;
  value: unknown;
  color: string;
  payload: ChartDatum;
  type?: 'none';
}

export interface ChartTooltipOptions {
  /** The hover cursor (a muted band behind bars, a line on lines and areas). Default true. */
  cursor?: boolean;
  /** A point shown from the first paint, Recharts' `defaultIndex`. */
  defaultIndex?: number;
  indicator?: 'dot' | 'line' | 'dashed';
  hideLabel?: boolean;
  hideIndicator?: boolean;
  nameKey?: string;
  labelKey?: string;
  labelFormatter?: (label: unknown, payload: ChartPayloadItem[]) => unknown;
  formatter?: (value: unknown, name: string, item: ChartPayloadItem, index: number, datum: ChartDatum) => unknown;
  /** One colour for every indicator, shadcn's `color`. */
  color?: string;
  class?: string;
  labelClass?: string;
}

export interface ChartLegendOptions {
  verticalAlign?: 'top' | 'bottom';
  nameKey?: string;
  hideIcon?: boolean;
  class?: string;
  /** The height the legend takes from the plot, in viewBox units. Default 28. */
  height?: number;
}

/** What every chart function takes. */
export interface ChartBaseOptions {
  config: ChartConfig;
  data: ChartDatum[];
  /** Classes for the container, shadcn's ChartContainer `className`. */
  class?: string;
  id?: string;
  /** The accessible name of the chart. */
  title?: string;
  /** Nominal size: the SVG's viewBox. */
  width?: number;
  height?: number;
  margin?: Partial<Margin>;
  tooltip?: ChartTooltipOptions | false;
  legend?: ChartLegendOptions | false;
  /** Recharts' accessibilityLayer: focus and the arrow keys. Default true. */
  accessibilityLayer?: boolean;
  /** SVG `<defs>` content, for gradients (`svg` template). */
  defs?: unknown;
}

/** The container's colour variables: `--color-<key>` per configured colour. */
export function chartStyle(config: ChartConfig): string {
  return Object.entries(config)
    .map(([key, item]) => {
      const color = item.theme ? `light-dark(${item.theme.light}, ${item.theme.dark})` : item.color;
      return color ? `--color-${key}: ${color};` : '';
    })
    .filter(Boolean)
    .join(' ');
}

// --------------------------------------------------------------------------
// Tooltip and legend content (shadcn's ChartTooltipContent / ChartLegendContent)
// --------------------------------------------------------------------------

/** shadcn's getPayloadConfigFromPayload: the config entry a payload item names. */
export function payloadConfig(config: ChartConfig, item: ChartPayloadItem | undefined, key: string): ChartConfigItem | undefined {
  if (!item) return undefined;
  let k = key;
  const own = (item as unknown as Record<string, unknown>)[key];
  if (typeof own === 'string') k = own;
  else if (typeof item.payload?.[key] === 'string') k = item.payload[key] as string;
  return k in config ? config[k] : config[key];
}

/**
 * A tooltip resolved for one point: its label and its rows, with every
 * formatter and config lookup already applied. When every part is a string
 * it is plain data, which is how the chart serves a point (see `frame`).
 */
export interface ChartTooltipView {
  label: unknown;
  items: Array<{ name: unknown; value: string | null; color: string; icon?: unknown; custom?: unknown }>;
}

/** The view options the browser needs to draw a served point. */
export type TooltipLook = Pick<ChartTooltipOptions, 'indicator' | 'hideIndicator' | 'class' | 'labelClass'>;

/** Resolve a point's tooltip: shadcn's ChartTooltipContent logic, without the markup. */
export function chartTooltipView(config: ChartConfig, label: unknown, payload: ChartPayloadItem[], o: ChartTooltipOptions = {}): ChartTooltipView {
  let viewLabel: unknown = '';
  if (!o.hideLabel && payload.length) {
    const first = payload[0];
    const key = `${o.labelKey ?? first.dataKey ?? first.name ?? 'value'}`;
    const itemConfig = payloadConfig(config, first, key);
    const value = !o.labelKey && typeof label === 'string' ? (config[label]?.label ?? label) : itemConfig?.label;
    viewLabel = o.labelFormatter ? o.labelFormatter(value, payload) : (value ?? '');
  }
  const items = payload.filter((item) => item.type !== 'none').map((item, index) => {
    const key = `${o.nameKey ?? item.name ?? item.dataKey ?? 'value'}`;
    const itemConfig = payloadConfig(config, item, key);
    const color = o.color ?? (typeof item.payload?.fill === 'string' ? item.payload.fill : item.color);
    const custom = o.formatter && item.value !== undefined && item.name ? o.formatter(item.value, item.name, item, index, item.payload) : undefined;
    return {
      name: itemConfig?.label ?? item.name,
      value: item.value != null ? formatValue(item.value) : null,
      color,
      ...(itemConfig?.icon ? { icon: itemConfig.icon() } : {}),
      ...(custom !== undefined ? { custom } : {}),
    };
  });
  return { label: viewLabel, items };
}

/** A view that is all strings can be served as data and drawn in the browser. */
export function isPlainView(v: ChartTooltipView): boolean {
  return typeof v.label === 'string' && v.items.every((i) => i.icon === undefined && i.custom === undefined && typeof i.name === 'string');
}

/** Draw a resolved tooltip: shadcn's ChartTooltipContent markup. */
export function chartTooltipMarkup(view: ChartTooltipView, o: TooltipLook = {}) {
  if (!view.items.length) return '';
  const indicator = o.indicator ?? 'dot';
  const tooltipLabel = view.label === '' || view.label == null ? '' : html`<div class=${cn('font-medium', o.labelClass)}>${view.label}</div>`;
  const nestLabel = view.items.length === 1 && indicator !== 'dot';
  return html`<div class=${cn('border-border/50 bg-background gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl grid min-w-32 items-start', o.class)}>${nestLabel ? '' : tooltipLabel}<div class="grid gap-1.5">${view.items.map((item) => {
    const body = item.custom !== undefined
      ? item.custom
      : html`${item.icon !== undefined
        ? item.icon
        : o.hideIndicator
          ? ''
          : html`<div class=${cn('shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)', {
            'h-2.5 w-2.5': indicator === 'dot',
            'w-1': indicator === 'line',
            'w-0 border-[1.5px] border-dashed bg-transparent': indicator === 'dashed',
            'my-0.5': nestLabel && indicator === 'dashed',
          })} style=${`--color-bg: ${item.color}; --color-border: ${item.color}`}></div>`}<div class=${cn('flex flex-1 justify-between leading-none', nestLabel ? 'items-end' : 'items-center')}><div class="grid gap-1.5">${nestLabel ? tooltipLabel : ''}<span class="text-muted-foreground">${item.name}</span></div>${item.value != null ? html`<span class="font-mono font-medium text-foreground tabular-nums">${item.value}</span>` : ''}</div>`;
    return html`<div class=${cn('flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground', indicator === 'dot' && 'items-center')}>${body}</div>`;
  })}</div></div>`;
}

/**
 * The tooltip's content for one point: shadcn's ChartTooltipContent.
 * `label` is the point's category (a month, a date), `payload` its series.
 */
export function chartTooltipContent(config: ChartConfig, label: unknown, payload: ChartPayloadItem[], o: ChartTooltipOptions = {}) {
  return chartTooltipMarkup(chartTooltipView(config, label, payload, o), o);
}

/** The legend: shadcn's ChartLegendContent markup over a series payload. */
export function chartLegendContent(config: ChartConfig, payload: ChartPayloadItem[], o: ChartLegendOptions = {}) {
  if (!payload.length) return '';
  return html`<div class=${cn('flex items-center justify-center gap-4', o.verticalAlign === 'top' ? 'pb-3' : 'pt-3', o.class)}>${payload
    .filter((item) => item.type !== 'none')
    .map((item) => {
      const itemConfig = payloadConfig(config, item, `${o.nameKey ?? item.dataKey ?? 'value'}`);
      return html`<div class="flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground">${itemConfig?.icon && !o.hideIcon
        ? itemConfig.icon()
        : html`<div class="h-2 w-2 shrink-0 rounded-[2px]" style=${`background-color: ${item.color}`}></div>`}${itemConfig?.label ?? ''}</div>`;
    })}</div>`;
}

// --------------------------------------------------------------------------
// The element adds the tooltip, cursor and active marks, by pointer and keyboard
// --------------------------------------------------------------------------

export class UiChart extends WebComponent {
  /** The point showing, or -1. */
  activeIndex = -1;
  _resize: ResizeObserver | null = null;

  connectedCallback(): void {
    super.connectedCallback?.();
    this.addEventListener('pointermove', this._onMove);
    this.addEventListener('pointerleave', this._onLeave);
    this.addEventListener('focusin', this._onFocus);
    this.addEventListener('focusout', this._onBlur);
    this.addEventListener('keydown', this._onKey);
  }

  firstUpdated(): void {
    // A chart rendered on the client commits its attributes after the
    // element connects, so a first attempt can find the SVG unfinished.
    if (!this._init()) requestAnimationFrame(() => this._init());
  }

  disconnectedCallback(): void {
    this.removeEventListener('pointermove', this._onMove);
    this.removeEventListener('pointerleave', this._onLeave);
    this.removeEventListener('focusin', this._onFocus);
    this.removeEventListener('focusout', this._onBlur);
    this.removeEventListener('keydown', this._onKey);
    this._resize?.disconnect();
    this._resize = null;
    super.disconnectedCallback?.();
  }

  render() {
    return html`<slot></slot>`;
  }

  _svg(): SVGSVGElement | null {
    return typeof this.querySelector === 'function' ? this.querySelector<SVGSVGElement>('svg.ui-chart-surface') : null;
  }

  _entries(): HTMLElement[] {
    return Array.from(this.querySelectorAll<HTMLElement>('[data-slot="chart-tooltips"] > [data-index]'));
  }

  _look(): TooltipLook {
    const raw = this.querySelector<HTMLElement>('[data-slot="chart-tooltips"]')?.dataset.look;
    return raw ? (JSON.parse(raw) as TooltipLook) : {};
  }

  _init(): boolean {
    const s = this._svg();
    if (!s || !s.getAttribute('viewBox')) return false;
    this._watchSize(s);
    if (!s.dataset.hit) return true;
    if (s.dataset.keyboard === 'true') {
      s.setAttribute('tabindex', '0');
      s.setAttribute('role', 'application');
      s.setAttribute('aria-roledescription', 'chart');
    }
    const d = s.dataset.defaultIndex;
    if (d != null) this.show(Number(d));
    return true;
  }

  /** Lay the chart out again whenever its box changes size. */
  _watchSize(s: SVGSVGElement): void {
    if (this._resize || typeof ResizeObserver !== 'function') return;
    this._resize = new ResizeObserver(() => this._layout(s));
    this._resize.observe(s);
  }

  /**
   * Fit the served chart to its box, as Recharts lays out at the real size.
   *
   * The server draws at a nominal size, and the SVG scales to its box. Where
   * the box has another shape (a wide chart in a fixed height on a phone), a
   * cartesian chart (`data-fit`) is widened or narrowed to fill it: the
   * viewBox takes the box's aspect, and the plot is stretched along x around
   * its left edge while the margins and the y axis keep their size. That is
   * exact for the marks Recharts would redraw (its scales and the d3 curves
   * are linear in x), so only what has a size of its own is put back: each
   * label and dot is drawn unstretched, and the x axis ticks move to their
   * new places and are thinned again. Without JavaScript the served layout
   * shows, letterboxed in a box of another shape.
   *
   * Then the labels and dots keep their size in pixels. A 12px label in a
   * chart drawn 340px wide on a 450 unit viewBox would read as 9px, so the
   * SVG's font size, in em of its container's, undoes the scale, and each
   * dot is scaled by it around its centre (Recharts' `r` is in pixels).
   */
  _layout(s: SVGSVGElement): void {
    const shown = s.getBoundingClientRect();
    if (!shown.width || !shown.height) return;
    const [, , w0, h] = (s.dataset.viewBox ??= s.getAttribute('viewBox') ?? '').split(/\s+/).map(Number);
    if (!(w0 > 0 && h > 0)) return;
    const round = (v: number) => Math.round(v * 1e4) / 1e4;
    let w = w0;
    let sx = 1;
    const fit = s.dataset.fit === 'x' && s.dataset.plot != null;
    if (fit) {
      const [px, py, pw, ph] = (s.dataset.plot0 ??= s.dataset.plot ?? '').split(' ').map(Number);
      const wide = (h * shown.width) / shown.height;
      const stretch = (pw + wide - w0) / pw;
      if (pw > 0 && stretch > 0.05) {
        w = wide;
        sx = Math.abs(stretch - 1) < 1e-3 ? 1 : stretch;
      }
      const map = (x: number) => (x <= px ? x : x >= px + pw ? x + (sx - 1) * pw : px + (x - px) * sx);
      s.setAttribute('viewBox', `0 0 ${round(sx === 1 ? w0 : w)} ${h}`);
      s.dataset.plot = [px, py, pw * sx, ph].map(round).join(' ');
      const matrix = sx === 1 ? null : `matrix(${round(sx)} 0 0 1 ${round(px * (1 - sx))} 0)`;
      for (const g of Array.from(s.children)) {
        if (g.tagName.toLowerCase() === 'defs' || g.hasAttribute('data-axis')) continue;
        if (matrix) g.setAttribute('transform', matrix);
        else g.removeAttribute('transform');
        for (const t of Array.from(g.querySelectorAll('text'))) {
          const x = Number(t.getAttribute('x'));
          if (matrix && Number.isFinite(x)) t.setAttribute('transform', `matrix(${round(1 / sx)} 0 0 1 ${round(x * (1 - 1 / sx))} 0)`);
          else t.removeAttribute('transform');
        }
      }
      const axis = s.querySelector<SVGGElement>('[data-axis="x"]');
      if (axis) {
        axis.dataset.extent = String(round(sx === 1 ? w0 : w));
        for (const line of Array.from(axis.querySelectorAll('.ui-chart-cartesian-axis-line'))) {
          for (const a of ['x1', 'x2']) {
            const key = `data-${a}0`;
            if (!line.hasAttribute(key)) line.setAttribute(key, line.getAttribute(a) ?? '0');
            line.setAttribute(a, String(round(map(Number(line.getAttribute(key))))));
          }
        }
        for (const t of Array.from(axis.querySelectorAll<SVGGElement>('[data-coord]'))) {
          t.dataset.coord = String(round(map(Number((t.dataset.coord0 ??= t.dataset.coord)))));
        }
      }
      for (const e of this._entries()) {
        if (e.dataset.x != null) e.dataset.x = String(round(map(Number((e.dataset.x0 ??= e.dataset.x)))));
      }
    }
    const k = Math.max((sx === 1 ? w0 : w) / shown.width, h / shown.height);
    if (!(Number.isFinite(k) && k > 0)) return;
    s.style.fontSize = `${round(k)}em`;
    for (const c of Array.from(s.querySelectorAll('circle.ui-chart-dot'))) {
      const cx = Number(c.getAttribute('cx'));
      const cy = Number(c.getAttribute('cy'));
      const a = k / (fit ? sx : 1);
      c.setAttribute('transform', `matrix(${round(a)} 0 0 ${round(k)} ${round(cx * (1 - a))} ${round(cy * (1 - k))})`);
    }
    this._fitTicks(s, k);
    const tip = this.querySelector<HTMLElement>('[data-slot="chart-tooltip"]');
    if (this.activeIndex >= 0 && tip && !tip.hidden) this.show(this.activeIndex);
  }

  /**
   * Thin each axis's labels again with their real widths, the way Recharts'
   * getTicks does at render: the server could only estimate them, and the
   * labels keep their font size while the chart scales.
   */
  _fitTicks(s: SVGSVGElement, k: number): void {
    for (const axis of Array.from(s.querySelectorAll<SVGGElement>('[data-axis][data-interval]'))) {
      const interval = axis.dataset.interval ?? 'preserveEnd';
      const groups = Array.from(axis.querySelectorAll<SVGGElement>('[data-coord]'));
      const isX = axis.dataset.axis === 'x';
      const ticks: Tick[] = groups.map((g, i) => ({ value: i, label: '', coord: Number(g.dataset.coord) }));
      const size = (t: Tick) => {
        const text = groups[Number(t.value)].querySelector('text');
        if (!text) return 0;
        return isX ? text.getComputedTextLength() : text.getBBox().height;
      };
      // Recharts' edges are the chart's box, with its margins in pixels. Here
      // the margins scale with the chart while the labels do not, so the room
      // between the box and the outer ticks is widened back to its pixels.
      const extent = Number(axis.dataset.extent);
      const coords = ticks.map((t) => t.coord);
      const before = coords.length ? Math.min(...coords) : 0;
      const after = coords.length ? extent - Math.max(...coords) : 0;
      const kept = visibleTicks(ticks, size, -before * (k - 1), extent + after * (k - 1), Number(axis.dataset.gap), /^\d+$/.test(interval) ? Number(interval) : (interval as 'preserveEnd'));
      const at = new Map(kept.map((t) => [Number(t.value), t.at ?? t.coord]));
      groups.forEach((g, i) => {
        const pos = at.get(i);
        if (pos == null) {
          g.setAttribute('visibility', 'hidden');
          return;
        }
        g.removeAttribute('visibility');
        const v = String(Math.round(pos * 1e4) / 1e4);
        for (const el of Array.from(g.querySelectorAll('text, tspan'))) {
          if (isX) el.setAttribute('x', v);
          else if (el.tagName.toLowerCase() === 'text') el.setAttribute('y', v);
        }
        for (const line of Array.from(g.querySelectorAll('line'))) {
          if (isX) { line.setAttribute('x1', v); line.setAttribute('x2', v); } else { line.setAttribute('y1', v); line.setAttribute('y2', v); }
        }
      });
    }
  }

  /** Where a point's tooltip anchors, in pixels from the chart's wrapper. */
  _anchor(i: number): { x: number; y: number } | null {
    const s = this._svg();
    const e = this._entries()[i];
    const m = s?.getScreenCTM?.();
    const wrap = s?.parentElement;
    if (!s || !e || !m || !wrap) return null;
    const r = wrap.getBoundingClientRect();
    const x = Number(e.dataset.x);
    const y = Number(e.dataset.y);
    return { x: m.a * x + m.c * y + m.e - r.left, y: m.b * x + m.d * y + m.f - r.top };
  }

  /** Show point `i`, its tooltip at `at` (pixels from the wrapper) or at its anchor. */
  show(i: number, at?: { x: number; y: number }): void {
    const entry = this._entries()[i];
    const wrapper = this.querySelector<HTMLElement>('[data-slot="chart-tooltip"]');
    if (!entry || !wrapper) return;
    for (const g of this.querySelectorAll('[data-slot="chart-cursor"] > [data-index], [data-slot="chart-active"] > [data-index]')) {
      g.setAttribute('visibility', g.getAttribute('data-index') === String(i) ? 'visible' : 'hidden');
    }
    if (i !== this.activeIndex || wrapper.hidden || !wrapper.firstChild) {
      const tip = entry.dataset.tip;
      if (tip) {
        // A served point is data: draw it with the same markup the server uses.
        const box = document.createElement('div');
        render(chartTooltipMarkup(JSON.parse(tip) as ChartTooltipView, this._look()), box);
        wrapper.replaceChildren(...Array.from(box.childNodes));
      } else {
        wrapper.replaceChildren(...Array.from(entry.cloneNode(true).childNodes));
      }
    }
    this.activeIndex = i;
    wrapper.hidden = false;
    const p = at ?? this._anchor(i);
    if (!p) return;
    // Recharts' getTooltipTranslate: 10px right of and below the point, or
    // above and to its left when that would leave the plot area.
    const area = this._plot();
    const x = p.x + 10 + wrapper.offsetWidth > area.right ? Math.max(p.x - wrapper.offsetWidth - 10, area.left) : Math.max(p.x + 10, area.left);
    const y = p.y + 10 + wrapper.offsetHeight > area.bottom ? Math.max(p.y - wrapper.offsetHeight - 10, area.top) : Math.max(p.y + 10, area.top);
    wrapper.style.transform = `translate(${x}px, ${y}px)`;
  }

  /** The plot area in pixels from the chart's wrapper. */
  _plot(): { left: number; top: number; right: number; bottom: number } {
    const s = this._svg();
    const wrap = s?.parentElement;
    const m = s?.getScreenCTM?.();
    const [x, y, w, h] = (s?.dataset.plot ?? '').split(' ').map(Number);
    if (!s || !wrap || !m || !Number.isFinite(h)) {
      return { left: 0, top: 0, right: wrap?.clientWidth ?? 0, bottom: wrap?.clientHeight ?? 0 };
    }
    const r = wrap.getBoundingClientRect();
    return {
      left: m.a * x + m.e - r.left,
      top: m.d * y + m.f - r.top,
      right: m.a * (x + w) + m.e - r.left,
      bottom: m.d * (y + h) + m.f - r.top,
    };
  }

  /** Hide the tooltip and the marks. */
  hide(): void {
    const wrapper = this.querySelector<HTMLElement>('[data-slot="chart-tooltip"]');
    if (wrapper) wrapper.hidden = true;
    for (const g of this.querySelectorAll('[data-slot="chart-cursor"] > [data-index], [data-slot="chart-active"] > [data-index]')) g.setAttribute('visibility', 'hidden');
    this.activeIndex = -1;
  }

  _announce(i: number): void {
    const live = this.querySelector<HTMLElement>('[data-slot="chart-live"]');
    const entry = this._entries()[i];
    if (!live || !entry) return;
    const tip = entry.dataset.tip ? (JSON.parse(entry.dataset.tip) as ChartTooltipView) : null;
    const text = tip
      ? [tip.label, ...tip.items.map((it) => `${it.name} ${it.value ?? ''}`)].join(' ')
      : entry.textContent ?? '';
    live.textContent = text.replace(/\s+/g, ' ').trim();
  }

  _onMove = (e: PointerEvent): void => {
    const s = this._svg();
    if (!s || !s.dataset.hit || !s.parentElement) return;
    const wrap = s.parentElement.getBoundingClientRect();
    const at = { x: e.clientX - wrap.left, y: e.clientY - wrap.top };
    let index = -1;
    if (s.dataset.hit === 'target') {
      const t = (e.target as Element | null)?.closest?.('[data-index]');
      if (t && s.contains(t)) index = Number(t.getAttribute('data-index'));
    } else {
      const m = s.getScreenCTM?.();
      if (!m) return;
      const inv = m.inverse();
      const v = s.dataset.hit === 'y'
        ? inv.b * e.clientX + inv.d * e.clientY + inv.f
        : inv.a * e.clientX + inv.c * e.clientY + inv.e;
      const axis = s.dataset.hit === 'y' ? 'y' : 'x';
      let best = Infinity;
      this._entries().forEach((en, i) => {
        const d = Math.abs(Number(en.dataset[axis]) - v);
        if (d < best) { best = d; index = i; }
      });
    }
    if (index < 0) this.hide();
    else this.show(index, at);
  };

  _onLeave = (): void => {
    if (!this.contains(document.activeElement)) this.hide();
  };

  _onFocus = (e: FocusEvent): void => {
    if (e.target !== this._svg()) return;
    const i = this.activeIndex >= 0 ? this.activeIndex : 0;
    this.show(i);
    this._announce(i);
  };

  _onBlur = (e: FocusEvent): void => {
    if (e.target === this._svg()) this.hide();
  };

  _onKey = (e: KeyboardEvent): void => {
    if (e.target !== this._svg()) return;
    const n = this._entries().length;
    if (!n) return;
    const cur = this.activeIndex;
    let next = cur;
    if (e.key === 'ArrowRight' || e.key === 'ArrowDown') next = Math.min(n - 1, cur + 1);
    else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') next = Math.max(0, cur - 1);
    else if (e.key === 'Home') next = 0;
    else if (e.key === 'End') next = n - 1;
    else if (e.key === 'Escape') { this.hide(); return; }
    else return;
    e.preventDefault();
    this.show(next);
    this._announce(next);
  };
}
UiChart.register('ui-chart');
```

```ts title="components/ui/chart-geometry.ts"
/**
 * The chart's geometry: Recharts' maths, ported with no dependency (#1666,
 * D10). Pure functions over numbers and strings, imported by `chart.ts`,
 * which draws with them and re-exports them, so an app reaches them through
 * the chart module.
 *
 * What is here, each matching what Recharts 3 draws for the same input:
 * the nice ticks of a numeric axis (getNiceTickValues), linear, band and
 * point scales, the d3-shape curves (linear, natural, monotone, step), the
 * bar rectangle and pie or radial sector paths with their rounded corners,
 * polar coordinates, stacking (none, sign, expand), the bar slot layout
 * (getBarPositions), and which axis labels fit (getTicks).
 *
 * A11y: none to supply. This module draws nothing; the chart that uses it
 * carries the accessible name and the keyboard access.
 */

/** A curve type, Recharts' `type` on a Line or an Area. */
export type CurveType = 'linear' | 'natural' | 'monotone' | 'monotoneX' | 'step' | 'stepBefore' | 'stepAfter';

// --------------------------------------------------------------------------
// Numbers
// --------------------------------------------------------------------------

export const RADIAN = Math.PI / 180;

// Floating point noise off: 0.1 + 0.2 stays 0.3 for tick values.
function snap(n: number): number {
  return Number(n.toPrecision(12));
}

/** A coordinate as Recharts writes one: at most four decimals, no `-0`. */
export function fmt(n: number, digits = 4): string {
  const k = 10 ** digits;
  const r = Math.round(n * k) / k;
  return String(r === 0 ? 0 : r);
}

/** A number as a tooltip shows one (`toLocaleString`, fixed to en-US so server and client agree). */
export function formatValue(v: unknown): string {
  return typeof v === 'number' ? v.toLocaleString('en-US') : String(v ?? '');
}

export function num(v: unknown): number {
  return typeof v === 'number' ? v : Number(v) || 0;
}

/** A Recharts size: a number, or a percentage of `whole`. */
export function percent(v: number | string | undefined, whole: number, fallback: number): number {
  if (v == null) return fallback;
  if (typeof v === 'number') return v;
  const s = v.trim();
  if (s.endsWith('%')) return (parseFloat(s) / 100) * whole;
  const n = parseFloat(s);
  return Number.isFinite(n) ? n : fallback;
}

/**
 * The width of a label in the chart's 12px font, estimated, since the server
 * cannot measure text. Used only to thin crowded axis labels.
 */
export function estimateTextWidth(text: string, fontSize = 12): number {
  let em = 0;
  for (const ch of text) {
    if (/[ilj.,:;'|!]/.test(ch)) em += 0.26;
    else if (/[mwMW]/.test(ch)) em += 0.82;
    else if (ch === ' ') em += 0.28;
    else if (/[0-9]/.test(ch)) em += 0.56;
    else if (/[A-Z]/.test(ch)) em += 0.66;
    else em += 0.52;
  }
  return em * fontSize;
}

// --------------------------------------------------------------------------
// Ticks and scales (Recharts' getNiceTickValues, ported)
// --------------------------------------------------------------------------

function digitCount(v: number): number {
  return v === 0 ? 1 : Math.floor(snap(Math.log10(Math.abs(v)))) + 1;
}

function adaptiveStep(rough: number, allowDecimals: boolean, correction: number): number {
  if (rough <= 0) return 0;
  const dc = digitCount(rough);
  const pow = 10 ** dc;
  const ratio = rough / pow;
  const scale = dc !== 1 ? 0.05 : 0.1;
  const step = snap(snap((Math.ceil(snap(ratio / scale)) + correction) * scale) * pow);
  return allowDecimals ? step : Math.ceil(step);
}

function calculateStep(min: number, max: number, count: number, allowDecimals: boolean, correction = 0): { step: number; tickMin: number; tickMax: number } {
  if (!Number.isFinite((max - min) / (count - 1))) return { step: 0, tickMin: 0, tickMax: 0 };
  const step = adaptiveStep((max - min) / (count - 1), allowDecimals, correction);
  let middle: number;
  if (min <= 0 && max >= 0) middle = 0;
  else {
    middle = (min + max) / 2;
    middle = snap(middle - (middle % step));
  }
  let below = Math.ceil(snap((middle - min) / step));
  let up = Math.ceil(snap((max - middle) / step));
  const scaleCount = below + up + 1;
  if (scaleCount > count) return calculateStep(min, max, count, allowDecimals, correction + 1);
  if (scaleCount < count) {
    if (max > 0) up += count - scaleCount;
    else below += count - scaleCount;
  }
  return { step, tickMin: snap(middle - below * step), tickMax: snap(middle + up * step) };
}

/**
 * Recharts' nice ticks for a numeric axis: `count` round values covering
 * `[min, max]`, extended past the data where that makes them rounder
 * (`[0, 305]` gives `0, 80, 160, 240, 320`).
 */
export function niceTicks(min: number, max: number, count = 5, allowDecimals = true): number[] {
  const n = Math.max(count, 2);
  const [lo, hi] = min > max ? [max, min] : [min, max];
  if (lo === hi) {
    const middleIndex = Math.floor((n - 1) / 2);
    let middle = lo;
    if (lo === 0) middle = middleIndex;
    else if (!allowDecimals || Math.abs(lo) > 1) middle = Math.floor(lo);
    return Array.from({ length: n }, (_, i) => snap(middle + (i - middleIndex)));
  }
  const { step, tickMin, tickMax } = calculateStep(lo, hi, n, allowDecimals);
  const out: number[] = [];
  if (step <= 0) return [tickMin];
  for (let v = tickMin, i = 0; v < tickMax + step * 0.1 && i < 1000; i++, v = snap(tickMin + i * step)) out.push(v);
  return min > max ? out.reverse() : out;
}

/**
 * d3's linear ticks: about `count` round values inside `[start, stop]`,
 * stepping by 1, 2 or 5 times a power of ten. Recharts uses them for an axis
 * with no tick count of its own, a radial bar chart's angle axis.
 */
export function linearTicks(start: number, stop: number, count = 10): number[] {
  const raw = Math.abs(stop - start) / count;
  if (!(raw > 0) || !Number.isFinite(raw)) return [start];
  const power = Math.floor(Math.log10(raw));
  const error = raw / 10 ** power;
  const step = (error >= Math.sqrt(50) ? 10 : error >= Math.sqrt(10) ? 5 : error >= Math.sqrt(2) ? 2 : 1) * 10 ** power;
  const out: number[] = [];
  for (let v = Math.ceil(start / step) * step; v <= stop + step * 1e-9; v = snap(v + step)) out.push(snap(v));
  return out;
}

/** A linear scale from a domain onto a range. */
export function linearScale(domain: [number, number], range: [number, number]): (v: number) => number {
  const [d0, d1] = domain;
  const [r0, r1] = range;
  return (v) => (d1 === d0 ? (r0 + r1) / 2 : r0 + ((v - d0) / (d1 - d0)) * (r1 - r0));
}

/** A band scale with no padding, Recharts' category axis under bars. */
export function bandScale(count: number, start: number, end: number): { bandwidth: number; at: (i: number) => number } {
  const bandwidth = count ? (end - start) / count : 0;
  return { bandwidth, at: (i) => start + i * bandwidth };
}

/** A point scale with no padding, Recharts' category axis under lines and areas. */
export function pointScale(count: number, start: number, end: number): (i: number) => number {
  return (i) => (count <= 1 ? (start + end) / 2 : start + (i * (end - start)) / (count - 1));
}

// --------------------------------------------------------------------------
// Curves (d3-shape's curves, which Recharts draws with)
// --------------------------------------------------------------------------

export type Pt = [number, number];

function naturalControls(x: number[]): [number[], number[]] {
  const n = x.length - 1;
  const a = new Array<number>(n);
  const b = new Array<number>(n);
  const r = new Array<number>(n);
  a[0] = 0; b[0] = 2; r[0] = x[0] + 2 * x[1];
  for (let i = 1; i < n - 1; ++i) { a[i] = 1; b[i] = 4; r[i] = 4 * x[i] + 2 * x[i + 1]; }
  a[n - 1] = 2; b[n - 1] = 7; r[n - 1] = 8 * x[n - 1] + x[n];
  for (let i = 1; i < n; ++i) { const m = a[i] / b[i - 1]; b[i] -= m; r[i] -= m * r[i - 1]; }
  a[n - 1] = r[n - 1] / b[n - 1];
  for (let i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];
  b[n - 1] = (x[n] + a[n - 1]) / 2;
  for (let i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];
  return [a, b];
}

function sgn(x: number): number {
  return x < 0 ? -1 : 1;
}

/**
 * The SVG path of a curve through `points`, as d3-shape draws it (three
 * decimals). `start` is the first command: `M` for a new path, `L` to
 * continue one (an area's baseline).
 */
export function curvePath(points: Pt[], type: CurveType = 'linear', start: 'M' | 'L' = 'M'): string {
  const p = (x: number, y: number) => `${fmt(x, 3)},${fmt(y, 3)}`;
  if (!points.length) return '';
  const [x0, y0] = points[0];
  let d = `${start}${p(x0, y0)}`;
  const n = points.length;
  if (n === 1) return d;
  if (type === 'natural') {
    if (n === 2) return `${d}L${p(points[1][0], points[1][1])}`;
    const [ax, bx] = naturalControls(points.map((q) => q[0]));
    const [ay, by] = naturalControls(points.map((q) => q[1]));
    for (let i = 0; i < n - 1; i++) d += `C${p(ax[i], ay[i])},${p(bx[i], by[i])},${p(points[i + 1][0], points[i + 1][1])}`;
    return d;
  }
  if (type === 'monotone' || type === 'monotoneX') {
    // d3's curveMonotoneX: slopes from the neighbours, never overshooting.
    const xs = points.map((q) => q[0]);
    const ys = points.map((q) => q[1]);
    if (n === 2) return `${d}L${p(xs[1], ys[1])}`;
    const slope3 = (i: number): number => {
      const h0 = xs[i] - xs[i - 1];
      const h1 = xs[i + 1] - xs[i];
      const s0 = (ys[i] - ys[i - 1]) / (h0 || (h1 < 0 ? -0 : 0));
      const s1 = (ys[i + 1] - ys[i]) / (h1 || (h0 < 0 ? -0 : 0));
      const q = (s0 * h1 + s1 * h0) / (h0 + h1);
      return (sgn(s0) + sgn(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(q)) || 0;
    };
    const slope2 = (i: number, t: number): number => {
      const h = xs[i] - xs[i - 1];
      return h ? (3 * (ys[i] - ys[i - 1]) / h - t) / 2 : t;
    };
    const t = new Array<number>(n);
    for (let i = 1; i < n - 1; i++) t[i] = slope3(i);
    t[0] = slope2(1, t[1]);
    t[n - 1] = slope2(n - 1, t[n - 2]);
    for (let i = 0; i < n - 1; i++) {
      const dx = (xs[i + 1] - xs[i]) / 3;
      d += `C${p(xs[i] + dx, ys[i] + dx * t[i])},${p(xs[i + 1] - dx, ys[i + 1] - dx * t[i + 1])},${p(xs[i + 1], ys[i + 1])}`;
    }
    return d;
  }
  if (type === 'step' || type === 'stepBefore' || type === 'stepAfter') {
    const k = type === 'step' ? 0.5 : type === 'stepBefore' ? 0 : 1;
    for (let i = 1; i < n; i++) {
      const [px, py] = points[i - 1];
      const [x, y] = points[i];
      if (k <= 0) d += `L${p(px, y)}L${p(x, y)}`;
      else { const x1 = px * (1 - k) + x * k; d += `L${p(x1, py)}L${p(x1, y)}`; }
    }
    if (k > 0 && k < 1) d += `L${p(points[n - 1][0], points[n - 1][1])}`;
    return d;
  }
  for (let i = 1; i < n; i++) d += `L${p(points[i][0], points[i][1])}`;
  return d;
}

// --------------------------------------------------------------------------
// Shapes (Recharts' Rectangle and Sector paths)
// --------------------------------------------------------------------------

/** A bar: Recharts' rectangle path, `radius` one number or `[tl, tr, br, bl]`. */
export function rectanglePath(x: number, y: number, width: number, height: number, radius: number | number[] = 0): string {
  const w = Math.round(width * 1e4) / 1e4;
  const h = Math.round(height * 1e4) / 1e4;
  const maxR = Math.min(Math.abs(w) / 2, Math.abs(h) / 2);
  const ys = h >= 0 ? 1 : -1;
  const xs = w >= 0 ? 1 : -1;
  const cw = (h >= 0 && w >= 0) || (h < 0 && w < 0) ? 1 : 0;
  const r4 = Array.isArray(radius) ? radius : radius > 0 ? [radius, radius, radius, radius] : null;
  if (maxR > 0 && r4) {
    const r = [0, 1, 2, 3].map((i) => Math.min(r4[i] ?? 0, maxR));
    let d = `M${fmt(x)},${fmt(y + ys * r[0])}`;
    if (r[0] > 0) d += `A ${fmt(r[0])},${fmt(r[0])},0,0,${cw},${fmt(x + xs * r[0])},${fmt(y)}`;
    d += `L ${fmt(x + width - xs * r[1])},${fmt(y)}`;
    if (r[1] > 0) d += `A ${fmt(r[1])},${fmt(r[1])},0,0,${cw},${fmt(x + width)},${fmt(y + ys * r[1])}`;
    d += `L ${fmt(x + width)},${fmt(y + height - ys * r[2])}`;
    if (r[2] > 0) d += `A ${fmt(r[2])},${fmt(r[2])},0,0,${cw},${fmt(x + width - xs * r[2])},${fmt(y + height)}`;
    d += `L ${fmt(x + xs * r[3])},${fmt(y + height)}`;
    if (r[3] > 0) d += `A ${fmt(r[3])},${fmt(r[3])},0,0,${cw},${fmt(x)},${fmt(y + height - ys * r[3])}`;
    return `${d}Z`;
  }
  return `M ${fmt(x)},${fmt(y)} h ${fmt(width)} v ${fmt(height)} h ${fmt(-width)} Z`;
}

/** Recharts' polar coordinates: degrees counter-clockwise from three o'clock. */
export function polarToCartesian(cx: number, cy: number, radius: number, angle: number): { x: number; y: number } {
  return { x: cx + Math.cos(-RADIAN * angle) * radius, y: cy + Math.sin(-RADIAN * angle) * radius };
}

export interface SectorGeometry {
  cx: number;
  cy: number;
  innerRadius: number;
  outerRadius: number;
  startAngle: number;
  endAngle: number;
  cornerRadius?: number;
}

function tangentCircle(cx: number, cy: number, radius: number, angle: number, sign: number, isExternal: boolean, cornerRadius: number) {
  const centerRadius = cornerRadius * (isExternal ? 1 : -1) + radius;
  const theta = Math.asin(cornerRadius / centerRadius) / RADIAN;
  const centerAngle = angle + sign * theta;
  const circleTangency = polarToCartesian(cx, cy, radius, centerAngle);
  const lineTangency = polarToCartesian(cx, cy, centerRadius * Math.cos(theta * RADIAN), angle);
  return { circleTangency, lineTangency, theta };
}

/** A pie slice or radial bar: Recharts' sector path, with rounded corners when asked. */
export function sectorPath(s: SectorGeometry): string {
  const { cx, cy, innerRadius, outerRadius, startAngle, endAngle } = s;
  if (outerRadius < innerRadius || startAngle === endAngle) return '';
  const cr = Math.min(s.cornerRadius ?? 0, (outerRadius - innerRadius) / 2);
  const sign = Math.sign(endAngle - startAngle) || 1;
  if (cr > 0 && Math.abs(startAngle - endAngle) < 360) {
    const so = tangentCircle(cx, cy, outerRadius, startAngle, sign, false, cr);
    const eo = tangentCircle(cx, cy, outerRadius, endAngle, -sign, false, cr);
    const outerArc = Math.abs(startAngle - endAngle) - so.theta - eo.theta;
    if (outerArc >= 0) {
      const P = (q: { x: number; y: number }) => `${fmt(q.x)},${fmt(q.y)}`;
      let d = `M ${P(so.lineTangency)} A${fmt(cr)},${fmt(cr)},0,0,${+(sign < 0)},${P(so.circleTangency)} A${fmt(outerRadius)},${fmt(outerRadius)},0,${+(outerArc > 180)},${+(sign < 0)},${P(eo.circleTangency)} A${fmt(cr)},${fmt(cr)},0,0,${+(sign < 0)},${P(eo.lineTangency)}`;
      if (innerRadius > 0) {
        const si = tangentCircle(cx, cy, innerRadius, startAngle, sign, true, cr);
        const ei = tangentCircle(cx, cy, innerRadius, endAngle, -sign, true, cr);
        const innerArc = Math.abs(startAngle - endAngle) - si.theta - ei.theta;
        d += `L${P(ei.lineTangency)} A${fmt(cr)},${fmt(cr)},0,0,${+(sign < 0)},${P(ei.circleTangency)} A${fmt(innerRadius)},${fmt(innerRadius)},0,${+(innerArc > 180)},${+(sign > 0)},${P(si.circleTangency)} A${fmt(cr)},${fmt(cr)},0,0,${+(sign < 0)},${P(si.lineTangency)}Z`;
      } else d += `L${fmt(cx)},${fmt(cy)}Z`;
      return d;
    }
  }
  const delta = sign * Math.min(Math.abs(endAngle - startAngle), 359.999);
  const end = startAngle + delta;
  const os = polarToCartesian(cx, cy, outerRadius, startAngle);
  const oe = polarToCartesian(cx, cy, outerRadius, end);
  const large = +(Math.abs(delta) > 180);
  let d = `M ${fmt(os.x)},${fmt(os.y)} A ${fmt(outerRadius)},${fmt(outerRadius)},0,${large},${+(startAngle > end)},${fmt(oe.x)},${fmt(oe.y)}`;
  if (innerRadius > 0) {
    const is = polarToCartesian(cx, cy, innerRadius, startAngle);
    const ie = polarToCartesian(cx, cy, innerRadius, end);
    d += ` L ${fmt(ie.x)},${fmt(ie.y)} A ${fmt(innerRadius)},${fmt(innerRadius)},0,${large},${+(startAngle <= end)},${fmt(is.x)},${fmt(is.y)} Z`;
  } else d += ` L ${fmt(cx)},${fmt(cy)} Z`;
  return d;
}

/** A closed polygon through `points` (a radar's area, a polar grid ring). */
export function polygonPath(points: { x: number; y: number }[]): string {
  if (!points.length) return '';
  return `${points.map((q, i) => `${i ? 'L' : 'M'}${fmt(q.x)},${fmt(q.y)}`).join('')}L${fmt(points[0].x)},${fmt(points[0].y)}Z`;
}

// --------------------------------------------------------------------------
// Stacking
// --------------------------------------------------------------------------

/**
 * Stack `keys` over `data`: for each key, the `[low, high]` band of every
 * row. `expand` normalises each row to 0..1 (Recharts' `stackOffset="expand"`),
 * `sign` stacks negative values downward from zero, as Recharts does for bars.
 */
export function stackData(data: Array<Record<string, unknown>>, keys: string[], offset: 'none' | 'expand' | 'sign' = 'none'): Record<string, Array<[number, number]>> {
  const out: Record<string, Array<[number, number]>> = {};
  for (const k of keys) out[k] = [];
  data.forEach((row) => {
    const total = keys.reduce((s, k) => s + Math.abs(num(row[k])), 0) || 1;
    let pos = 0;
    let neg = 0;
    for (const k of keys) {
      let v = num(row[k]);
      if (offset === 'expand') v /= total;
      if (offset === 'sign' && v < 0) { out[k].push([neg + v, neg]); neg += v; }
      else { out[k].push([pos, pos + v]); pos += v; }
    }
  });
  return out;
}

// --------------------------------------------------------------------------
// Axis ticks (Recharts' getTicks: which labels fit)
// --------------------------------------------------------------------------

export interface Tick { value: unknown; label: unknown; coord: number; at?: number }

function isVisible(sign: number, pos: number, size: number, start: number, end: number): boolean {
  if (sign * pos < sign * start || sign * pos > sign * end) return false;
  return sign * (pos - (sign * size) / 2 - start) >= 0 && sign * (pos + (sign * size) / 2 - end) <= 0;
}

/**
 * The ticks an axis shows: every one that fits, keeping the last (Recharts'
 * default `preserveEnd`), `minTickGap` apart. A number keeps every nth + 1.
 */
export function visibleTicks(ticks: Tick[], sizeOf: (t: Tick) => number, start: number, end: number, minTickGap = 5, interval: number | 'preserveEnd' | 'preserveStart' | 'preserveStartEnd' = 'preserveEnd'): Tick[] {
  if (typeof interval === 'number') return ticks.filter((_, i) => i % (interval + 1) === 0).map((t) => ({ ...t, at: t.coord }));
  const sign = ticks.length >= 2 ? Math.sign(ticks[1].coord - ticks[0].coord) || 1 : 1;
  let [s, e] = sign === 1 ? [start, end] : [end, start];
  const out: Array<Tick & { show?: boolean }> = ticks.map((t) => ({ ...t, at: t.coord }));
  const len = out.length;
  if (interval === 'preserveEnd') {
    for (let i = len - 1; i >= 0; i--) {
      const t = out[i];
      const size = sizeOf(t);
      if (i === len - 1) {
        const gap = sign * (t.coord + (sign * size) / 2 - e);
        t.at = gap > 0 ? t.coord - gap * sign : t.coord;
      }
      if (isVisible(sign, t.at ?? t.coord, size, s, e)) {
        e = (t.at ?? t.coord) - sign * (size / 2 + minTickGap);
        t.show = true;
      }
    }
  } else {
    let count = len;
    if (interval === 'preserveStartEnd' && len) {
      const tail = out[len - 1];
      const size = sizeOf(tail);
      const gap = sign * (tail.coord + (sign * size) / 2 - e);
      tail.at = gap > 0 ? tail.coord - gap * sign : tail.coord;
      if (isVisible(sign, tail.at, size, s, e)) { e = tail.at - sign * (size / 2 + minTickGap); tail.show = true; }
      count = len - 1;
    }
    for (let i = 0; i < count; i++) {
      const t = out[i];
      const size = sizeOf(t);
      if (i === 0) {
        const gap = sign * (t.coord - (sign * size) / 2 - s);
        t.at = gap < 0 ? t.coord - gap * sign : t.coord;
      }
      if (isVisible(sign, t.at ?? t.coord, size, s, e)) { s = (t.at ?? t.coord) + sign * (size / 2 + minTickGap); t.show = true; }
    }
  }
  return out.filter((t) => t.show);
}

// --------------------------------------------------------------------------
// Bar layout
// --------------------------------------------------------------------------

/** Recharts' getBarPositions: each bar slot's offset into its band and its size. */
export function barPositions(bandSize: number, slots: Array<{ barSize?: number }>, barGap: number | string = 4, barCategoryGap: number | string = '10%', maxBarSize?: number): Array<{ offset: number; size: number }> {
  const len = slots.length;
  if (!len) return [];
  let gap = percent(barGap, bandSize, 0);
  if (slots[0].barSize != null) {
    let useFull = false;
    let full = bandSize / len;
    let sum = slots.reduce((s, x) => s + (x.barSize ?? 0), 0) + (len - 1) * gap;
    if (sum >= bandSize) { sum -= (len - 1) * gap; gap = 0; }
    if (sum >= bandSize && full > 0) { useFull = true; full *= 0.9; sum = len * full; }
    let prev = { offset: Math.trunc((bandSize - sum) / 2) - gap, size: 0 };
    return slots.map((x) => (prev = { offset: prev.offset + prev.size + gap, size: useFull ? full : x.barSize ?? 0 }));
  }
  const offset = percent(barCategoryGap, bandSize, 0);
  if (bandSize - 2 * offset - (len - 1) * gap <= 0) gap = 0;
  let original = (bandSize - 2 * offset - (len - 1) * gap) / len;
  if (original > 1) original = Math.trunc(original);
  const size = maxBarSize != null ? Math.min(original, maxBarSize) : original;
  return slots.map((_, i) => ({ offset: offset + (original + gap) * i + (original - size) / 2, size }));
}
```

### Update the import paths to match your project setup.

## Your First Chart

Let's build your first chart. We'll build a bar chart, add a grid, axis, tooltip and legend.

### Start by defining your data

The following data represents the number of desktop and mobile users for each month.

**Note:** Your data can be in any shape. You are not limited to the shape of the data below. Use the `dataKey` option to map your data to the chart.

```ts title="components/example-chart.ts"
const chartData = [
  { month: 'January', desktop: 186, mobile: 80 },
  { month: 'February', desktop: 305, mobile: 200 },
  { month: 'March', desktop: 237, mobile: 120 },
  { month: 'April', desktop: 73, mobile: 190 },
  { month: 'May', desktop: 209, mobile: 130 },
  { month: 'June', desktop: 214, mobile: 140 },
];
```

### Define your chart config

The chart config holds configuration for the chart. This is where you place human-readable strings, such as labels, icons and color tokens for theming.

```ts title="components/example-chart.ts"
import type { ChartConfig } from '#components/ui/chart.ts';

const chartConfig = {
  desktop: {
    label: 'Desktop',
    color: '#2563eb',
  },
  mobile: {
    label: 'Mobile',
    color: '#60a5fa',
  },
} satisfies ChartConfig;
```

### Build your chart

You can now build your chart with `barChart()`.

**Important:** Keep a height, a `min-h-[VALUE]` or an `aspect-*` class on the chart. The SVG scales to the box its container gives it.

```ts
import { html } from '@webjsdev/core';
import { barChart, type ChartConfig } from '#components/ui/chart.ts';

export const description = 'A bar chart';

const chartData = [
  { month: 'January', desktop: 186, mobile: 80 },
  { month: 'February', desktop: 305, mobile: 200 },
  { month: 'March', desktop: 237, mobile: 120 },
  { month: 'April', desktop: 73, mobile: 190 },
  { month: 'May', desktop: 209, mobile: 130 },
  { month: 'June', desktop: 214, mobile: 140 },
];

const chartConfig = {
  desktop: {
    label: 'Desktop',
    color: '#2563eb',
  },
  mobile: {
    label: 'Mobile',
    color: '#60a5fa',
  },
} satisfies ChartConfig;

export default function ChartExample() {
  return html`
    ${barChart({
      config: chartConfig,
      data: chartData,
      class: 'min-h-[200px] w-full',
      title: 'Desktop and mobile visitors, January to June',
      bars: [
        { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
        { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
      ],
    })}
  `;
}
```

### Add a Grid

Let's add a grid to the chart.

### Add the `grid` option to your chart.

```ts
${barChart({
  config: chartConfig,
  data: chartData,
  class: 'min-h-[200px] w-full',
  grid: { vertical: false },
  bars: [
    { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
    { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
  ],
})}
```

```ts
import { html } from '@webjsdev/core';
import { barChart, type ChartConfig } from '#components/ui/chart.ts';

export const description = 'A bar chart with a grid';

const chartData = [
  { month: 'January', desktop: 186, mobile: 80 },
  { month: 'February', desktop: 305, mobile: 200 },
  { month: 'March', desktop: 237, mobile: 120 },
  { month: 'April', desktop: 73, mobile: 190 },
  { month: 'May', desktop: 209, mobile: 130 },
  { month: 'June', desktop: 214, mobile: 140 },
];

const chartConfig = {
  desktop: {
    label: 'Desktop',
    color: '#2563eb',
  },
  mobile: {
    label: 'Mobile',
    color: '#60a5fa',
  },
} satisfies ChartConfig;

export default function ChartBarDemoGrid() {
  return html`
    ${barChart({
      config: chartConfig,
      data: chartData,
      class: 'min-h-[200px] w-full',
      title: 'Desktop and mobile visitors, January to June',
      grid: { vertical: false },
      bars: [
        { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
        { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
      ],
    })}
  `;
}
```

### Add an Axis

To add an x-axis to the chart, we'll use the `xAxis` option.

### Add the `xAxis` option to your chart.

```ts
${barChart({
  config: chartConfig,
  data: chartData,
  class: 'h-[200px] w-full',
  grid: { vertical: false },
  xAxis: {
    dataKey: 'month',
    tickLine: false,
    tickMargin: 10,
    axisLine: false,
    tickFormatter: (value) => String(value).slice(0, 3),
  },
  bars: [
    { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
    { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
  ],
})}
```

```ts
import { html } from '@webjsdev/core';
import { barChart, type ChartConfig } from '#components/ui/chart.ts';

export const description = 'A bar chart with a grid and an x axis';

const chartData = [
  { month: 'January', desktop: 186, mobile: 80 },
  { month: 'February', desktop: 305, mobile: 200 },
  { month: 'March', desktop: 237, mobile: 120 },
  { month: 'April', desktop: 73, mobile: 190 },
  { month: 'May', desktop: 209, mobile: 130 },
  { month: 'June', desktop: 214, mobile: 140 },
];

const chartConfig = {
  desktop: {
    label: 'Desktop',
    color: '#2563eb',
  },
  mobile: {
    label: 'Mobile',
    color: '#60a5fa',
  },
} satisfies ChartConfig;

export default function ChartBarDemoAxis() {
  return html`
    ${barChart({
      config: chartConfig,
      data: chartData,
      class: 'min-h-[200px] w-full',
      title: 'Desktop and mobile visitors, January to June',
      grid: { vertical: false },
      xAxis: { dataKey: 'month', tickLine: false, tickMargin: 10, axisLine: false, tickFormatter: (value) => String(value).slice(0, 3) },
      bars: [
        { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
        { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
      ],
    })}
  `;
}
```

### Add Tooltip

So far the chart is static SVG. It looks great out of the box thanks to the chart's container classes.

To add a tooltip, we'll use the `tooltip` option, which draws the kit's tooltip card.

### Add the `tooltip` option to your chart.

```ts
${barChart({
  config: chartConfig,
  data: chartData,
  class: 'h-[200px] w-full',
  grid: { vertical: false },
  xAxis: {
    dataKey: 'month',
    tickLine: false,
    tickMargin: 10,
    axisLine: false,
    tickFormatter: (value) => String(value).slice(0, 3),
  },
  tooltip: {},
  bars: [
    { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
    { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
  ],
})}
```

```ts
import { html } from '@webjsdev/core';
import { barChart, type ChartConfig } from '#components/ui/chart.ts';

export const description = 'A bar chart with a tooltip';

const chartData = [
  { month: 'January', desktop: 186, mobile: 80 },
  { month: 'February', desktop: 305, mobile: 200 },
  { month: 'March', desktop: 237, mobile: 120 },
  { month: 'April', desktop: 73, mobile: 190 },
  { month: 'May', desktop: 209, mobile: 130 },
  { month: 'June', desktop: 214, mobile: 140 },
];

const chartConfig = {
  desktop: {
    label: 'Desktop',
    color: '#2563eb',
  },
  mobile: {
    label: 'Mobile',
    color: '#60a5fa',
  },
} satisfies ChartConfig;

export default function ChartBarDemoTooltip() {
  return html`
    ${barChart({
      config: chartConfig,
      data: chartData,
      class: 'min-h-[200px] w-full',
      title: 'Desktop and mobile visitors, January to June',
      grid: { vertical: false },
      xAxis: { dataKey: 'month', tickLine: false, tickMargin: 10, axisLine: false, tickFormatter: (value) => String(value).slice(0, 3) },
      tooltip: {},
      bars: [
        { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
        { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
      ],
    })}
  `;
}
```

Hover to see the tooltips. Easy, right? One option, and we've got a beautiful tooltip.

### Add Legend

We'll do the same for the legend, with the `legend` option, which draws the kit's legend.

### Add the `legend` option to your chart.

```ts
${barChart({
  config: chartConfig,
  data: chartData,
  class: 'h-[200px] w-full',
  grid: { vertical: false },
  xAxis: {
    dataKey: 'month',
    tickLine: false,
    tickMargin: 10,
    axisLine: false,
    tickFormatter: (value) => String(value).slice(0, 3),
  },
  tooltip: {},
  legend: {},
  bars: [
    { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
    { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
  ],
})}
```

```ts
import { html } from '@webjsdev/core';
import { barChart, type ChartConfig } from '#components/ui/chart.ts';

export const description = 'A bar chart with a tooltip and a legend';

const chartData = [
  { month: 'January', desktop: 186, mobile: 80 },
  { month: 'February', desktop: 305, mobile: 200 },
  { month: 'March', desktop: 237, mobile: 120 },
  { month: 'April', desktop: 73, mobile: 190 },
  { month: 'May', desktop: 209, mobile: 130 },
  { month: 'June', desktop: 214, mobile: 140 },
];

const chartConfig = {
  desktop: {
    label: 'Desktop',
    color: '#2563eb',
  },
  mobile: {
    label: 'Mobile',
    color: '#60a5fa',
  },
} satisfies ChartConfig;

export default function ChartBarDemoLegend() {
  return html`
    ${barChart({
      config: chartConfig,
      data: chartData,
      class: 'min-h-[200px] w-full',
      title: 'Desktop and mobile visitors, January to June',
      grid: { vertical: false },
      xAxis: { dataKey: 'month', tickLine: false, tickMargin: 10, axisLine: false, tickFormatter: (value) => String(value).slice(0, 3) },
      tooltip: {},
      legend: {},
      bars: [
        { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
        { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
      ],
    })}
  `;
}
```

Done. You've built your first chart! What's next?

- Themes and Colors
- Tooltip
- Legend

## Chart Config

The chart config is where you define the labels, icons and colors for a chart.

It is intentionally decoupled from chart data.

This allows you to share config and color tokens between charts. It can also work independently for cases where your data or color tokens live remotely or in a different format.

```ts
import { MonitorIcon } from '#lib/utils/icons.ts';
import type { ChartConfig } from '#components/ui/chart.ts';

const chartConfig = {
  desktop: {
    label: 'Desktop',
    // A function returning an html or svg template.
    icon: () => MonitorIcon(),
    // A color like 'hsl(220, 98%, 61%)' or 'var(--color-name)'
    color: '#2563eb',
    // OR a theme object with 'light' and 'dark' keys
    theme: {
      light: '#2563eb',
      dark: '#dc2626',
    },
  },
} satisfies ChartConfig;
```

## Theming

Charts have built-in support for theming. You can use css variables (recommended) or color values in any color format, such as hex, hsl or oklch.

### CSS Variables

### Define your colors in your css file

```css title="app/globals.css"
@layer base {
  :root {
    --chart-1: oklch(0.646 0.222 41.116);
    --chart-2: oklch(0.6 0.118 184.704);
  }

  .dark {
    --chart-1: oklch(0.488 0.243 264.376);
    --chart-2: oklch(0.696 0.17 162.48);
  }
}
```

### Add the color to your `chartConfig`

```ts title="components/example-chart.ts"
const chartConfig = {
  desktop: {
    label: 'Desktop',
    color: 'var(--chart-1)',
  },
  mobile: {
    label: 'Mobile',
    color: 'var(--chart-2)',
  },
} satisfies ChartConfig;
```

### hex, hsl or oklch

You can also define your colors directly in the chart config. Use the color format you prefer.

```ts title="components/example-chart.ts"
const chartConfig = {
  desktop: {
    label: 'Desktop',
    color: '#2563eb',
  },
  mobile: {
    label: 'Mobile',
    color: 'hsl(220, 98%, 61%)',
  },
  tablet: {
    label: 'Tablet',
    color: 'oklch(0.5 0.2 240)',
  },
  laptop: {
    label: 'Laptop',
    color: 'var(--chart-2)',
  },
} satisfies ChartConfig;
```

### Using Colors

To use the theme colors in your chart, reference the colors using the format `var(--color-KEY)`. The chart sets one such variable per config entry on its container.

#### Components

```ts
bars: [{ dataKey: 'desktop', fill: 'var(--color-desktop)' }]
```

#### Chart Data

```ts title="components/example-chart.ts"
const chartData = [
  { browser: 'chrome', visitors: 275, fill: 'var(--color-chrome)' },
  { browser: 'safari', visitors: 200, fill: 'var(--color-safari)' },
];
```

#### Tailwind

```ts title="components/example-chart.ts"
labels: [{ class: 'fill-(--color-desktop)' }]
```

## Tooltip

A chart tooltip contains a label, name, indicator and value. You can use a combination of these to customize your tooltip.

```ts
import { html } from '@webjsdev/core';
import { chartTooltipMarkup, type ChartTooltipOptions } from '#components/ui/chart.ts';

export const description = 'The parts of a chart tooltip: label, name, indicator and value';

// One tooltip drawn on its own, with the markup a chart draws on hover.
function tooltipDemo(o: {
  label: string;
  hideLabel?: boolean;
  indicator?: ChartTooltipOptions['indicator'];
  payload: Array<{ name: string; value: number; fill: string }>;
  class?: string;
}) {
  return chartTooltipMarkup(
    {
      label: o.hideLabel ? '' : o.label,
      items: o.payload.map((item) => ({ name: item.name, value: item.value.toLocaleString(), color: item.fill })),
    },
    { indicator: o.indicator ?? 'dot', class: `transition-all ease-in-out hover:-translate-y-0.5 ${o.class ?? ''}` },
  );
}

export default function ChartTooltipDemo() {
  return html`
    <div class="grid aspect-video w-full max-w-md justify-center text-foreground md:grid-cols-2 [&>div]:relative [&>div]:flex [&>div]:h-[137px] [&>div]:w-[224px] [&>div]:items-center [&>div]:justify-center [&>div]:p-4">
      <div>
        <div class="absolute top-[45px] left-[-35px] z-10 text-sm font-medium">Label</div>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 193 40" width="50" height="12" fill="none" aria-hidden="true" class="absolute top-[50px] left-[5px] z-10">
          <path fill="currentColor" d="M173.928 21.13C115.811 44.938 58.751 45.773 0 26.141c4.227-4.386 7.82-2.715 10.567-1.88 21.133 5.64 42.9 6.266 64.457 7.101 31.066 1.253 60.441-5.848 89.183-17.335 1.268-.418 2.325-1.253 4.861-2.924-14.582-2.924-29.165 2.089-41.845-3.76.212-.835.212-1.879.423-2.714 9.51-.627 19.231-1.253 28.742-2.089 9.51-.835 18.808-1.88 28.318-2.506 6.974-.418 9.933 2.924 7.397 9.19-3.17 8.145-7.608 15.664-11.623 23.391-.423.836-1.057 1.88-1.902 2.298-2.325.835-4.65 1.044-7.186 1.67-.422-2.088-1.479-4.386-1.268-6.265.423-2.506 1.902-4.595 3.804-9.19Z"></path>
        </svg>
        ${tooltipDemo({
          label: 'Page Views',
          payload: [
            { name: 'Desktop', value: 186, fill: 'var(--chart-1)' },
            { name: 'Mobile', value: 80, fill: 'var(--chart-2)' },
          ],
          class: 'w-[8rem]',
        })}
      </div>
      <div class="items-end">
        <div class="absolute top-[0px] left-[122px] z-10 text-sm font-medium">Name</div>
        <svg xmlns="http://www.w3.org/2000/svg" width="35" height="42" fill="none" viewBox="0 0 122 148" aria-hidden="true" class="absolute top-[10px] left-[85px] z-10 -scale-x-100">
          <path fill="currentColor" d="M0 2.65c6.15-4.024 12.299-2.753 17.812-.847a115.56 115.56 0 0 1 21.84 10.59C70.4 32.727 88.849 61.744 96.483 97.54c1.908 9.108 2.544 18.639 3.817 29.017 8.481-4.871 12.934-14.402 21.416-19.909 1.061 4.236-1.06 6.989-2.756 9.319-6.998 9.531-14.207 19.062-21.63 28.382-3.604 4.448-6.36 4.871-10.177 1.059-8.058-7.837-12.935-17.368-14.42-28.382 0-.424.636-1.059 1.485-2.118 9.118 2.33 6.997 13.979 14.843 18.215 3.393-14.614.848-28.593-2.969-42.149-4.029-14.19-9.33-27.746-17.812-39.82-8.27-11.86-18.66-21.392-30.11-30.287C26.93 11.758 14.207 6.039 0 2.65Z"></path>
        </svg>
        ${tooltipDemo({
          label: 'Browser',
          hideLabel: true,
          payload: [
            { name: 'Chrome', value: 1286, fill: 'var(--chart-3)' },
            { name: 'Firefox', value: 1000, fill: 'var(--chart-4)' },
          ],
          indicator: 'dashed',
          class: 'w-[8rem]',
        })}
      </div>
      <div class="hidden! md:flex!">
        ${tooltipDemo({
          label: 'Page Views',
          payload: [{ name: 'Desktop', value: 12486, fill: 'var(--chart-3)' }],
          indicator: 'line',
          class: 'w-[9rem]',
        })}
      </div>
      <div class="items-start! justify-start!">
        <div class="absolute top-[60px] left-[50px] z-10 text-sm font-medium">Indicator</div>
        ${tooltipDemo({
          label: 'Browser',
          hideLabel: true,
          payload: [{ name: 'Chrome', value: 1286, fill: 'var(--chart-1)' }],
          indicator: 'dot',
          class: 'w-[8rem]',
        })}
        <svg xmlns="http://www.w3.org/2000/svg" width="15" height="34" fill="none" viewBox="0 0 75 175" aria-hidden="true" class="absolute top-[38px] left-[30px] z-10 rotate-[-40deg]">
          <path fill="currentColor" d="M20.187 175c-4.439-2.109-7.186-2.531-8.032-4.008-3.17-5.484-6.763-10.968-8.454-17.084-5.073-16.242-4.439-32.694-1.057-49.146 5.707-28.053 18.388-52.942 34.24-76.565 1.692-2.531 3.171-5.063 4.862-7.805 0-.21-.211-.632-.634-1.265-4.65 1.265-9.511 2.53-14.161 3.585-2.537.422-5.496.422-8.032-.421-1.48-.422-3.593-2.742-3.593-4.219 0-1.898 1.48-4.218 2.747-5.906 1.057-1.054 2.96-1.265 4.65-1.687C35.406 7.315 48.088 3.729 60.98.776c10.99-2.53 14.584 1.055 13.95 11.812-.634 11.18-.846 22.358-1.268 33.326-.212 3.375-.846 6.96-1.268 10.757-8.878-4.007-8.878-4.007-12.048-38.177C47.03 33.259 38.153 49.289 29.91 65.741 21.667 82.193 16.17 99.49 13.212 117.84c-2.959 18.984.634 36.912 6.975 57.161Z"></path>
        </svg>
      </div>
    </div>
  `;
}
```

You can turn on/off any of these using the `hideLabel`, `hideIndicator` options and customize the indicator style using the `indicator` option.

Use `labelKey` and `nameKey` to use a custom key for the tooltip label and name.

Every chart function takes a `tooltip` option. Pass it to add the tooltip to your chart.

```ts title="components/example-chart.ts"
tooltip: {}
```

The tooltip for each point is resolved on the server, so a `labelFormatter`, a `formatter` or a config `icon` runs there and never ships to the browser.

### Props

Use the following options to customize the tooltip.

| Option | Type | Description |
| --- | --- | --- |
| `labelKey` | string | The config or data key to use for the label. |
| `nameKey` | string | The config or data key to use for the name. |
| `indicator` | `dot` `line` or `dashed` | The indicator style for the tooltip. |
| `hideLabel` | boolean | Whether to hide the label. |
| `hideIndicator` | boolean | Whether to hide the indicator. |

### Colors

Colors are automatically referenced from the chart config.

### Custom

To use a custom key for tooltip label and names, use the `labelKey` and `nameKey` options.

```ts
const chartData = [
  { browser: 'chrome', visitors: 187, fill: 'var(--color-chrome)' },
  { browser: 'safari', visitors: 200, fill: 'var(--color-safari)' },
];

const chartConfig = {
  visitors: {
    label: 'Total Visitors',
  },
  chrome: {
    label: 'Chrome',
    color: 'var(--chart-1)',
  },
  safari: {
    label: 'Safari',
    color: 'var(--chart-2)',
  },
} satisfies ChartConfig;
```

```ts title="components/example-chart.ts"
tooltip: { labelKey: 'visitors', nameKey: 'browser' }
```

This will use `Total Visitors` for label and `Chrome` and `Safari` for the tooltip names.

## Legend

Every chart function takes a `legend` option. Pass it to add a legend to your chart.

```ts title="components/example-chart.ts"
legend: {}
```

### Colors

Colors are automatically referenced from the chart config.

### Custom

To use a custom key for legend names, use the `nameKey` option.

```ts
const chartData = [
  { browser: 'chrome', visitors: 187, fill: 'var(--color-chrome)' },
  { browser: 'safari', visitors: 200, fill: 'var(--color-safari)' },
];

const chartConfig = {
  chrome: {
    label: 'Chrome',
    color: 'var(--chart-1)',
  },
  safari: {
    label: 'Safari',
    color: 'var(--chart-2)',
  },
} satisfies ChartConfig;
```

```ts title="components/example-chart.ts"
legend: { nameKey: 'browser' }
```

This will use `Chrome` and `Safari` for the legend names.

## Accessibility

A chart with a tooltip has an accessible layer by default, the `accessibilityLayer` option: it takes focus, the arrow keys step through its points, Home and End jump to the first and last, Escape hides the tooltip, and each step is announced to screen readers. Pass `accessibilityLayer: false` to turn it off.

Give every chart a `title`, which names it for screen readers, and keep its numbers in the text around it for a reader who cannot use the chart.

```ts title="components/example-chart.ts"
${lineChart({ config, data, title: 'Visitors by month', tooltip: {}, lines })}
```

## RTL

To enable RTL support, see the [RTL configuration guide](https://webjs.dev/ui/docs/rtl). The legend and the tooltip follow the `dir` attribute, and `reversed` on the x axis runs the categories from the right.

```ts
import { html } from '@webjsdev/core';
import { barChart, type ChartConfig } from '#components/ui/chart.ts';

export const description = 'A bar chart, right to left';

const translations = {
  en: {
    dir: 'ltr',
    values: {
      january: 'January',
      february: 'February',
      march: 'March',
      april: 'April',
      may: 'May',
      june: 'June',
      desktop: 'Desktop',
      mobile: 'Mobile',
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      january: 'يناير',
      february: 'فبراير',
      march: 'مارس',
      april: 'أبريل',
      may: 'مايو',
      june: 'يونيو',
      desktop: 'سطح المكتب',
      mobile: 'الجوال',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      january: 'ינואר',
      february: 'פברואר',
      march: 'מרץ',
      april: 'אפריל',
      may: 'מאי',
      june: 'יוני',
      desktop: 'מחשב',
      mobile: 'נייד',
    },
  },
} as const;

const chartData = [
  { month: 'january', desktop: 186, mobile: 80 },
  { month: 'february', desktop: 305, mobile: 200 },
  { month: 'march', desktop: 237, mobile: 120 },
  { month: 'april', desktop: 73, mobile: 190 },
  { month: 'may', desktop: 209, mobile: 130 },
  { month: 'june', desktop: 214, mobile: 140 },
];

// The provider is the dir attribute: the legend and the tooltip are HTML and
// follow it, and the x axis is reversed so January starts on the right.
export default function ChartRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];
  const label = (value: unknown) => t[value as keyof typeof t] ?? String(value);

  const chartConfig = {
    desktop: {
      label: t.desktop,
      color: 'var(--chart-2)',
    },
    mobile: {
      label: t.mobile,
      color: 'var(--chart-1)',
    },
  } satisfies ChartConfig;

  return html`
    <div dir=${dir} lang=${lang} class="w-full">
      ${barChart({
        config: chartConfig,
        data: chartData,
        class: 'min-h-[200px] w-full',
        grid: { vertical: false },
        xAxis: {
          dataKey: 'month',
          tickLine: false,
          tickMargin: 10,
          axisLine: false,
          tickFormatter: (value) => label(value).slice(0, 3),
          reversed: dir === 'rtl',
        },
        tooltip: { labelFormatter: (value) => label(value), labelClass: 'w-32' },
        legend: {},
        bars: [
          { dataKey: 'desktop', fill: 'var(--color-desktop)', radius: 4 },
          { dataKey: 'mobile', fill: 'var(--color-mobile)', radius: 4 },
        ],
      })}
    </div>
  `;
}
```
