Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(charts): split agent guide into topic docs and add charts skill (#95067)

Sam Pennington139856107676
diff --git a/.agents/skills/visualizing-change-over-time/SKILL.md b/.agents/skills/visualizing-change-over-time/SKILL.md
index a6cf63295272..8cdfcb1f8f2d 100644
--- a/.agents/skills/visualizing-change-over-time/SKILL.md
+++ b/.agents/skills/visualizing-change-over-time/SKILL.md
@@ -62,7 +62,7 @@ const series: Series<SlopeSeriesMeta>[] = [
```
Key options (full list in the charts
-[AGENTS.md](../../../packages/quill/packages/charts/AGENTS.md) "Composition" section):
+[docs/chart-types.md](../../../packages/quill/packages/charts/src/docs/chart-types.md) "SlopeChart" section):
- `showStartLabels` / `showEndLabels` — chart-level defaults for the value labels;
override per series with `meta.showStartLabel` / `meta.showEndLabel`.
diff --git a/.agents/skills/working-with-charts/SKILL.md b/.agents/skills/working-with-charts/SKILL.md
new file mode 100644
index 000000000000..73e80195ac6a
--- /dev/null
+++ b/.agents/skills/working-with-charts/SKILL.md
@@ -0,0 +1,57 @@
+---
+name: working-with-charts
+description: >
+ Guides consumers of @posthog/quill-charts through chart selection, data, themes, sizing, and composition.
+ Use when adding or changing a chart built with the package, including its axes, tooltips, legend, overlays, or interactions.
+ Links to package examples and API docs. Does not cover product integration or library internals.
+---
+
+# Consuming quill-charts
+
+Use the package's components and defaults before writing custom chart code.
+Read only the example or topic needed for the task.
+For changes inside the library, use [CONTRIBUTING.md](../../../packages/quill/packages/charts/src/docs/CONTRIBUTING.md) instead.
+
+## Choose a component
+
+Use the [chart-selection table](../../../packages/quill/packages/charts/AGENTS.md#choosing-a-chart), then read a matching [package story](../../../packages/quill/packages/charts/src/charts/).
+For a date axis, start with `DateAxis` in [TimeSeriesLineChart stories](../../../packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx).
+Import components and types from `@posthog/quill-charts`, not internal source paths.
+
+## Supply data, theme, and dimensions
+
+- Use stable series keys and typed `meta` for tooltip or click data.
+- For label-based charts, keep labels unique and align each series' data with them.
+- Use ISO date labels with `TimeSeries*` charts; format ticks through the axis config.
+- Use `NaN` for missing numeric series values, not zero.
+- Keep series, config, and callbacks stable across unrelated renders.
+- Give charts that fill their container a parent with real dimensions, including a nonzero height.
+
+Reuse the host's existing chart theme setup.
+For a new host without chart theming, use the package's `useChartTheme` hook.
+Follow the [setup and theme docs](../../../packages/quill/packages/charts/src/README.md#setup) for tokens and CSS.
+Omit series colors to use the theme palette; resolve CSS variables before passing explicit canvas colors.
+Read the selected chart's props and the [Series type](../../../packages/quill/packages/charts/src/core/types.ts) for its data contract.
+
+## Configure before customizing
+
+Prefer the selected chart's built-in tooltip and legend.
+Use config options and exported overlays before custom renderers.
+Load only the relevant topic:
+
+| Task | Package docs |
+| ------------------------------------------- | -------------------------------------------------------------------------------- |
+| Axis formatting, ranges, or multiple axes | [Axes](../../../packages/quill/packages/charts/src/docs/axes.md) |
+| Bar layouts or per-bar styling | [Bars](../../../packages/quill/packages/charts/src/docs/bars.md) |
+| Tooltip formatting or content | [Tooltips](../../../packages/quill/packages/charts/src/docs/tooltips.md) |
+| Legend visibility or interaction | [Legend](../../../packages/quill/packages/charts/src/docs/legend.md) |
+| Reference lines, labels, or custom overlays | [Overlays](../../../packages/quill/packages/charts/src/docs/overlays.md) |
+| Clicks, zoom, or selection | [Interactions](../../../packages/quill/packages/charts/src/docs/interactions.md) |
+
+## Verify
+
+Render at the intended container sizes and in light and dark themes.
+Check missing values, long labels, and any interactions you changed.
+Extend relevant tests and stories; use the [consumer testing guide](../../../packages/quill/packages/charts/src/docs/TESTING.md#testing-code-that-uses-hog-charts) for chart accessors.
+
+Keep detailed API behavior in the package docs rather than copying it into this skill.
diff --git a/.github/scripts/check-commit-warnings.test.sh b/.github/scripts/check-commit-warnings.test.sh
index 7b3e3adb8a0c..46ac62e6c5fd 100755
--- a/.github/scripts/check-commit-warnings.test.sh
+++ b/.github/scripts/check-commit-warnings.test.sh
@@ -48,6 +48,21 @@ stage packages/quill/packages/primitives/AGENTS.md
output="$(run .github/scripts/check-quill-agents-md.sh)"
[ -z "$output" ] || fail "quill warning fired even though AGENTS.md was staged too"
+from_head
+stage packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+stage packages/quill/packages/charts/src/docs/tooltips.md
+output="$(run .github/scripts/check-quill-agents-md.sh)"
+[ -z "$output" ] || fail "quill warning fired even though a topic doc was staged too"
+
+from_head
+stage packages/quill/packages/primitives/src/Button.tsx
+stage packages/quill/packages/charts/src/docs/tooltips.md
+output="$(run .github/scripts/check-quill-agents-md.sh)"
+case "$output" in
+ *"update (primitives)"*) ;;
+ *) fail "a topic doc in another package silenced the quill warning" ;;
+esac
+
from_head
stage posthog/models/team/team.py
output="$(run .github/scripts/check-claude-hooks.sh)"
diff --git a/.github/scripts/check-quill-agents-md.sh b/.github/scripts/check-quill-agents-md.sh
index 1c9024aa814a..02d6fd774010 100755
--- a/.github/scripts/check-quill-agents-md.sh
+++ b/.github/scripts/check-quill-agents-md.sh
@@ -13,9 +13,19 @@ set -uo pipefail
# the whole pipeline then reads as failed and the warning never prints.
staged=$(git diff --cached --name-only)
-if grep -qE '^packages/quill/packages/[^/]+/src/.*\.(ts|tsx|css)$' <<< "$staged" \
- && ! grep -qE '^packages/quill/.*AGENTS\.md$' <<< "$staged"; then
- printf "\n\033[33mWarning: quill component sources changed without an AGENTS.md update.\n"
+# A package's consumer guide is its own AGENTS.md or, where the guide is split by topic,
+# any doc under its own src/docs/. The workspace AGENTS.md covers every package. A doc
+# in a different package does not count.
+packages=$(grep -oE '^packages/quill/packages/[^/]+/src/.*\.(ts|tsx|css)$' <<< "$staged" | cut -d/ -f4 | sort -u)
+stale=""
+for pkg in $packages; do
+ if ! grep -qE "^packages/quill/(AGENTS\.md|packages/$pkg/(AGENTS\.md|src/docs/[^/]+\.md))$" <<< "$staged"; then
+ stale="$stale $pkg"
+ fi
+done
+
+if [ -n "$stale" ]; then
+ printf "\n\033[33mWarning: quill component sources changed without an AGENTS.md update (%s).\n" "${stale# }"
printf "If variants, composition, or spacing changed, update the consumer guide\n"
- printf "(packages/quill/packages/<pkg>/AGENTS.md) in the same PR.\033[0m\n\n"
+ printf "(packages/quill/packages/<pkg>/AGENTS.md, or a topic doc under its src/docs/) in the same PR.\033[0m\n\n"
fi
diff --git a/AGENTS.md b/AGENTS.md
index 1d613fa97028..203d9080f6b6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -214,7 +214,7 @@ See [.agents/security.md](.agents/security.md) for security guidelines — least
- Frontend: for any frontend work — the main app (`frontend/src/`) **or** a product frontend (`products/*/frontend/`) — follow [frontend/src/AGENTS.md](frontend/src/AGENTS.md): reuse existing Lemon/quill components instead of hand-rolling tables/badges/labels, import generated `*Api` types instead of handwriting them, and run typecheck/typegen at the right moments. Product frontends share the same components and generated types, so the same rules apply there
- Frontend: TypeScript required, explicit return types
- Frontend: If there is a kea logic file, write all business logic there, avoid React hooks at all costs.
-- Frontend (quill design system): before writing UI that imports `@posthog/quill` / `lib/ui/quill`, read [packages/quill/packages/primitives/AGENTS.md](packages/quill/packages/primitives/AGENTS.md) — component choice (dropdown vs select vs combobox, accordion vs collapsible, etc.), composition, and spacing rules. Charts: [packages/quill/packages/charts/AGENTS.md](packages/quill/packages/charts/AGENTS.md); DataTable/DateTimePicker: [packages/quill/packages/components/AGENTS.md](packages/quill/packages/components/AGENTS.md)
+- Frontend (quill design system): before writing UI that imports `@posthog/quill` / `lib/ui/quill`, read [packages/quill/packages/primitives/AGENTS.md](packages/quill/packages/primitives/AGENTS.md) — component choice (dropdown vs select vs combobox, accordion vs collapsible, etc.), composition, and spacing rules. Charts: [working-with-charts](.agents/skills/working-with-charts/SKILL.md) for consumers; [package guide](packages/quill/packages/charts/AGENTS.md) for library changes. DataTable/DateTimePicker: [packages/quill/packages/components/AGENTS.md](packages/quill/packages/components/AGENTS.md)
- Frontend (quill vs LemonUI): quill is for MCP apps and the desktop app. It is deliberately more compact than LemonUI, so its components look out of place in the main app, and there is no active migration of the main app onto it. In `frontend/src/` and `products/*/frontend/`, use LemonUI, including for menus — `LemonMenu` with a `LemonButton` trigger is the default there. `lib/ui/DropdownMenu` (Radix) is legacy; don't add new ones. Where quill is the right library, don't mix quill and Lemon components within one component's internals, and note that quill uses Base UI's `render` prop rather than Radix's `asChild`, so don't carry `asChild` over when converting
- Frontend: Any button or form submit that triggers a network request must guard against double-submission — disable the button and show a loading state (`loading` / `disabledReason` on `LemonButton`, or equivalent) while the request is in flight. Never leave a submit button clickable during an active mutation; reset the state in both success and error paths. This applies to `<form onSubmit>` handlers, `onClick` handlers that call `api.*`, and any kea `listener` that issues a request — wire the in-flight state (loader `*Loading` selectors, local `useState`, or a reducer) into the trigger's disabled/loading props.
- Frontend: Any UI a person reads must hold up in a narrow scene. The nav sidebar and an open side panel leave a 1280px window about 520px of scene, so break on container queries rather than `md:`/`lg:`/`xl:`, wrap or truncate instead of clipping, and stack halves that no longer fit. Render the surface at a few widths before calling the work done. We do not support mobile — don't add phone-width layouts or touch-sized targets. See "Rule 6" in [frontend/src/AGENTS.md](frontend/src/AGENTS.md)
@@ -270,6 +270,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a
- `/clickhouse-migrations` — any ClickHouse migration
- `/adopting-generated-api-types` — any frontend file using `lib/api`, `api.get<`, `api.create<`, or handwritten API types
- `/writing-ui-components` — creating, moving, splitting, or restructuring any component or file under `frontend/src/` or `products/*/frontend/`, extracting or promoting a shared component, or renaming frontend symbols or feature vocabulary
+- `/working-with-charts`: adding or editing a consumer of `@posthog/quill-charts`. For changes inside the library, follow its package guide instead.
- `/writing-tests` — any change to what a test asserts or sets up (pytest, Jest, or Playwright), down to one fixture or one assertion added to an existing block; renames, formatting, and import sorts are exempt
- `/writing-user-facing-copy` — writing or editing any text a user reads (UI labels, tooltips, empty/error states, notifications, docs, support replies), or any code change that adds or changes a visible string
- `/writing-code-comments` — writing or editing a code comment in any language, or reviewing a diff that adds comments
diff --git a/frontend/src/AGENTS.md b/frontend/src/AGENTS.md
index 29a651bf686b..491c6b1935f5 100644
--- a/frontend/src/AGENTS.md
+++ b/frontend/src/AGENTS.md
@@ -13,6 +13,9 @@ Where to look, in order:
`@posthog/quill` is **not** for this tree. It targets MCP apps and the desktop app, it's deliberately more compact than LemonUI, and the main app isn't being migrated onto it, so quill components read as out of place here. A handful of files already import it; treat those as exceptions rather than a pattern to copy.
+For `@posthog/quill-charts` consumers in the main app and product frontends, use `useChartTheme` from [`lib/charts/hooks`](./lib/charts/hooks.ts).
+Prefer its `useChartConfig` helper for memoized configuration.
+
Common reinventions and what to use instead:
| You're about to build… | Use instead |
@@ -107,5 +110,6 @@ Adding a button/toggle/action to a scene's `ScenePanel`? It must also go in that
- Root `AGENTS.md` — full Code Style + architecture rules (authoritative).
- `layout/scenes/AGENTS.md` (scene action surfaces: `ScenePanel` + `SceneMenuBar` dual-write rule).
- `packages/quill/packages/primitives/AGENTS.md` — component selection matrix.
+- `/working-with-charts`: chart consumption workflow with links to the relevant examples and package docs.
- `docs/published/handbook/engineering/conventions/frontend-coding.md` — frontend conventions.
-- Skills: `/writing-ui-components`, `/placing-product-frontend-code`, `/adopting-generated-api-types`, `/writing-kea-logics`, `/using-kea-disposables`, `/writing-tests`.
+- Skills: `/writing-ui-components`, `/placing-product-frontend-code`, `/adopting-generated-api-types`, `/writing-kea-logics`, `/using-kea-disposables`, `/writing-tests`, `/working-with-charts`.
diff --git a/packages/quill/AGENTS.md b/packages/quill/AGENTS.md
index fb2ff3a9d5a2..912850d05737 100644
--- a/packages/quill/AGENTS.md
+++ b/packages/quill/AGENTS.md
@@ -129,7 +129,7 @@ ButtonGroup
4. Define variants with CVA if the component has visual variants
5. Accept `className` prop and merge with `cn()`
6. Export from the component file (barrel export is in `index.ts`)
-7. Update the consumer guide in the same PR — `packages/primitives/AGENTS.md` (catalog row, "Choosing a component" cluster, composition pattern). Same rule applies to `packages/components/AGENTS.md` and `packages/charts/AGENTS.md` for their packages. A lint-staged warning fires if quill sources change without an AGENTS.md update
+7. Update the consumer guide in the same PR — `packages/primitives/AGENTS.md` (catalog row, "Choosing a component" cluster, composition pattern). Same rule applies to `packages/components/AGENTS.md`; charts keeps its `AGENTS.md` as a map and takes the update in a topic doc under `packages/charts/src/docs/`. A lint-staged warning fires if quill sources change without an update to the package's `AGENTS.md` or a topic doc under its `src/docs/`
### Styling rules
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 9f038308c950..5bec405d2746 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -1,25 +1,29 @@
# Charts — Agent Reference
-Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered charts, themed via quill design tokens. Ships no CSS — colors come from CSS variables at runtime.
+Quick-reference for agents using `@posthog/quill-charts`. Canvas-rendered charts, D3 scales, React DOM overlays, themed via quill design tokens. Ships no CSS — colors come from CSS variables at runtime.
+
+This file is the map. Prop-level semantics live in the JSDoc on the config and props types (`src/core/types.ts`, `src/utils/use-axis-formatters.ts`, each chart's `*Props`), and behavior that spans several fields lives in [`src/docs/`](./src/docs/). Read the type, then the topic doc, in that order.
## Choosing a chart
-| Chart | Use when |
-| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| LineChart | Categorical x-axis trends; area fills, fill-between (confidence ribbons) |
-| ScatterChart | Two continuous numeric axes — one marker per `{ x, y }` point, no connecting line. Takes `series` of `points` instead of `series`/`labels`; per-axis linear/log scale and pinned domain, per-series shape and color, drag-to-select |
-| BarChart | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars; end-cap rounding via top-level `barCornerRadius` (the same key across the time-series/combo configs) |
-| FunnelChart | Funnel steps as grouped vertical bars over a hatched drop-off track — one band per step, one bar per variant, valued as percent-of-first-step (0–100) |
-| ComboChart | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical-only, `barLayout: 'stacked' \| 'grouped' \| 'percent'` (percent stacks bar series to 100%; a line/area series needs its own `yAxisId: 'right'` axis — one sharing the bars' axis can't plot raw values against their [0,1] scale) |
-| TimeSeriesLineChart | Time-indexed labels (ISO strings) with timezone/interval-aware x-axis |
-| TimeSeriesBarChart | Same x-axis handling, bar rendering; supports per-series `yAxisId` axes |
-| TimeSeriesComboChart | Mixed bar + line/area on a time x-axis — `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) |
-| PieChart | Part-of-whole, one value per series; `innerRadiusRatio` for donut + `centerLabel`; on-slice labels via `showLabelOnSlice`/`showValueOnSlice`, positioned with `labelRadiusRatio` (0=center, 1=rim) and gated by `minSlicePercentForLabel`; `sliceValueDisplay` picks what the numeric line holds — `'value'`, `'percent'`, or `'both'` for `352 (18.4%)` (defaults to `'percent'` when `isPercent` is set, else `'value'`); `config.legend` for the built-in legend (a toggled-off slice is removed and the rest rescale to the full circle) |
-| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label; supports `config.legend` for grouped series |
-| Heatmap | 2D density grid (e.g. latency over time) — `xLabels` × `yLabels` (row 0 at the bottom), `cells[row][col]` counts → color intensity on one accent (log ramp by default, `colorScale: 'linear'` to opt out); single-cell tooltip resolved from the cursor, `onCellClick` reports `{ xIndex, yIndex, value }` |
-| Sparkline | Tiny inline trend, no axes — a gradient-filled line (default) or stacked bars via `type: 'bar'`; a flat `number[]` + `color`, or full `series` for multi-series; tooltip off by default, opt in with a `tooltip` render prop |
-| MetricCard | Headline number + sparkline + change pill (dashboard stat tiles) |
-| SlopeChart | Change between two points (slopegraph) — one line per series, left "before" → right "after"; `data: [start, end]` |
+| Chart | Use when |
+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
+| `LineChart` | Categorical x-axis trends; area fills, fill-between (confidence ribbons) |
+| `TimeSeriesLineChart` | Time-indexed labels (ISO strings) with timezone/interval-aware x-axis; goal lines, trend lines, moving averages, confidence bands as config |
+| `BarChart` | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars |
+| `TimeSeriesBarChart` | Same x-axis handling as the time-series line chart, bar rendering, per-series `yAxisId` axes |
+| `ComboChart` | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical only |
+| `TimeSeriesComboChart` | `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) |
+| `FunnelChart` | Funnel steps as grouped bars over a hatched drop-off track — one band per step, one bar per variant, valued as percent of first step |
+| `PieChart` | Part of whole, one value per series; `innerRadiusRatio` for a donut |
+| `ScatterChart` | Two continuous numeric axes — one marker per `{ x, y }` point; takes `points`, not `labels` |
+| `BoxPlot` | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label |
+| `Heatmap` | 2D density grid (latency over time) — `xLabels` × `yLabels`, `cells[row][col]` |
+| `SlopeChart` | Change between two points — one line per series, `data: [start, end]` |
+| `Sparkline` | Tiny inline trend, no axes — gradient line or stacked bars; tooltip off by default |
+| `MetricCard` | Headline number + sparkline + change pill (dashboard stat tiles) |
+
+Behavior notes per chart: [docs/chart-types.md](./src/docs/chart-types.md).
## Theme wiring
@@ -30,39 +34,28 @@ const theme = useChartTheme() // reads CSS vars, tracks light/dark switches
<LineChart series={series} labels={labels} theme={theme} />
```
-- Series colors come from `--data-color-1..15` (ordered categorical palette from `@posthog/quill-tokens`); chrome from `--color-graph-axis-label` / `--color-graph-axis-line` / `--color-graph-crosshair`.
-- `themeFromCssVars()` is the one-shot non-hook version; `DEFAULT_CHART_COLORS` is the no-DOM fallback (kept in sync with tokens by a CI-enforced test).
-- Omit `color` on a series to get palette assignment by index — preferred. Explicit `color` accepts hex or `var(--...)`.
-- Restyle knobs, all optional and off by default so themes/hosts opt in: `theme.axisLineColor` strokes the L-axis baselines and tick marks without changing tick-label text color (falls back `axisColor` → `gridColor`); `theme.gridDashPattern` / `theme.crosshairDashPattern` (e.g. `[3, 3]`) dash the interior grid lines / hover crosshair (plot-edge frame strokes stay solid). Config side: `showGrid` draws the grid lines — a top-level key on every chart, including the time-series wrappers; grid lines are always aligned to the primary (left) y-axis ticks, and a `showGrid` set on the primary `yAxis` config wins (on secondary axes it is ignored — two grids with unaligned ticks would just be noise); `showAxisLines` draws the L-axis (alongside the grid; the grid then skips its own frame and category lines; a right-positioned y-axis gets its own right axis line; `{ x, y }` toggles each edge independently), `showTickMarks` draws short canvas tick marks snapped to the same pixel grid as the axis, and `curve: 'monotone'` smooths line/area series through every point without overshoot. With axis lines on, line strokes are trimmed at the y-axis and floored onto the x-axis so they rest against the axis instead of straddling it.
-- `useChartTheme()` / `themeFromCssVars()` already carry the default styling: a faint dashed grid, a stronger axis line, and a dashed crosshair, each mixed as a share of the host's `--foreground` so they flip with light/dark. A host with its own token reader can layer just that part via `themeDefaultsFromCssVars()`. The matching config switches — grid, axis lines, tick marks, crosshair, monotone curve, rounded bars, and cursor-anchored tooltip — are the library default: LineChart, BarChart, ComboChart, and their TimeSeries variants layer `DEFAULT_CHART_CONFIG` under your `config` via `applyChartDefaults`, so a consumer opts _out_ field by field (e.g. `showGrid: false`) rather than opting in, and the nested `tooltip` merges key by key so setting one field keeps `placement: 'cursor'`. ScatterChart renders the same chrome from its own inline defaults (its config shape differs, so it doesn't call `applyChartDefaults`). Sparkline and MetricCard build their own config that opts out of the chrome, so they stay chromeless. `DEFAULT_CHART_CONFIG` is still exported for a host that builds a chart config object directly.
-- `theme.skipDraw` suppresses all canvas painting (static layer + hover overlay) while still mounting the `<canvas>` element. Use it for deterministic visual-snapshot tests where the async paint pipeline (ResizeObserver → requestAnimationFrame) races the screenshot — the chart renders blank but layout and DOM selectors are unaffected.
+- Series colors come from `--data-color-1..15`; chrome from `--color-graph-axis-label` / `--color-graph-axis-line` / `--color-graph-crosshair`. `themeFromCssVars()` is the one-shot version; `DEFAULT_CHART_COLORS` is the no-DOM fallback.
+- Omit `color` on a series to get palette assignment by index (preferred). An explicit `color` must be a concrete color (hex, rgb): line, area, and bar series hand it to the canvas unresolved, so resolve `var(--...)` in the host first. Only `Heatmap` and `ScatterChart` resolve `var()` themselves.
+- The theme helpers carry the default chrome (faint dashed grid, stronger axis line, dashed crosshair), and `DEFAULT_CHART_CONFIG` carries the matching switches. Consumers opt out field by field (`showGrid: false`). Details: [docs/axes.md](./src/docs/axes.md).
+- `theme.skipDraw` mounts the canvas without painting, for deterministic visual snapshots.
-## Series shape (all multi-series charts)
+## Series shape
```tsx
const series: Series[] = [
{ key: 'visits', label: 'Visits', data: [20, 35, 28] }, // data.length === labels.length
- { key: 'goal', label: 'Goal', data: [30, 30, 30], overlay: true }, // excluded from stacking
+ { key: 'goal', label: 'Goal', data: [30, 30, 30], overlay: true }, // excluded from stacking and the baseline
]
```
-- `key` (React key + stacking identity), `label` (legend/tooltip), `data` are required.
-- `labels` entries must be **unique** — the x-scale keys positions off the strings, so a duplicate collapses onto the first occurrence's position and draws the series backwards. On time-series charts pass ISO date strings (never formatted display labels like "1–7 Jun", which repeat across years) and format ticks via `xAxis.timezone`/`interval` or `tickFormatter`.
-- Line-only options: `points`, `stroke.pattern` (dashes/projections), `fill.opacity` / `fill.gradient` (area), `fill.lowerData` (ribbon).
-- Bar-only options: `bars` (per-bar `color`/`label`/`meta` overrides, plus `hatch: true` to fill that bar with a diagonal-hatch pattern in its resolved color — flags individual not-final bars, e.g. buckets still being ingested, at arbitrary indices; for a contiguous trailing range `stroke.partial.fromIndex` does the same); `trackData` caps each bar's interactive extent at a per-bar ceiling in value units — the region beyond `trackData[i]` is a fully inert gap: no hover, tooltip, pointer cursor, highlight, or click (the chart vetoes the hover there via `resolveHoverIndex`). On grouped charts with `bars.track` the hatched "share of a whole" track also fills only to the ceiling; on stacked charts no track is drawn — the ceiling only bounds interactivity. Funnel compare uses it to draw a shorter period's volume gap as empty space rather than drop-off, in both its grouped (left-to-right) and stacked (top-to-bottom) charts.
-- `BarChartConfig.bars.minBarSize` (px) floors each non-zero bar's thickness along the value axis so a single-occurrence bucket stays visible beside a spike three orders of magnitude taller (the old chart.js `minBarLength`) — zero-valued bars are never floored, so empty buckets stay empty. On a stacked chart only the outermost segment is floored — flooring an interior one would oversize a rect the segment above overpaints while still capturing its hover and clicks — so a breakdown stack floors only its top segment, and the option is aimed at single-series volume charts and grouped bars; `Sparkline` doesn't expose the prop. `bars.minBarSizeScope: 'hover'` restricts the floor to the hover highlight and hit-testing — the static layer draws true sizes and a tiny bar "grows" to a clickable nub under the cursor (while its track is hovered, the floored bar is also revealed in its plain color); the default `'always'` floors the static layer too. `TimeSeriesBarChart` takes `minBarSize`, `bandPadding`, `margins`, and `maxCategoryLabelWidth` as top-level config keys (alongside `barCornerRadius`/`fillStyle`) rather than under `bars`.
-- `ChartConfig.margins` overrides only the sides it sets — a side left `undefined` keeps the chart's computed margin, so an object built conditionally (`{ top: reserveOrUndefined }`) is safe. `SlopeChart` merges consumer margins over its computed label gutters with the same rule (`applyMarginOverride`), so an `undefined` side keeps the gutter its value/name labels reserved.
-- `yAxisId` scales a series against a second axis; `meta` carries arbitrary data into tooltips.
+- `key`, `label`, `data` are required. `key` is the React key and the stacking identity.
+- `labels` must be unique. The x-scale keys positions off the strings; a duplicate collapses onto the first occurrence and draws the series backwards. On time-series charts pass ISO dates and format ticks via `xAxis.timezone` / `interval`.
+- `meta` carries arbitrary data into tooltips and click handlers; narrow it with `Series<MyMeta>`.
+- `visibility.{excluded,tooltip,total,valueLabel}` controls where a series appears. `overlay: true` marks a derived series (trend line, moving average). Line-only: `points`, `stroke.pattern`, `stroke.partial`, `fill`. Bar-only: `bars[]`, `trackData`. Full field docs on `Series` in `src/core/types.ts`.
## Sizing
-Charts fill their container and need a parent with real dimensions — a `0`-height flex child renders nothing. Give the wrapper an explicit height (`h-64`, `flex-1` in a sized column). Sparkline alone takes `height`/`width` props.
-
-Overlays (axis labels, axis titles, reference/goal lines, value labels, legend, tooltip) are DOM, positioned from the scales; the grid, axis lines, tick marks, and the series themselves are canvas.
-That split is the first thing to check when a chart looks broken: if the labels and goal lines render in the right places but the plot area is empty, the layout is fine and the canvas alone failed.
-Check the cheap causes first: `theme.skipDraw` suppresses all canvas painting by design, and a `drawStatic` that throws leaves the frame it was clearing empty.
-Beyond those, the bitmap is discarded either by `syncCanvasSize` reallocating it (a real resize) or by the browser losing the 2D context, and `useChartCanvas` repaints after both — so a blank plot under correct overlays means one of those paths didn't schedule its repaint.
-Safari is the exception: it never fires `contextrestored`, so a context lost there stays blank.
+Charts fill their container and need a parent with real dimensions — a zero-height flex child renders nothing. Give the wrapper an explicit height. `Sparkline` alone takes `height` / `width` props.
## Composition
@@ -74,6 +67,8 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the
config={{
xAxis: { timezone: 'UTC', interval: 'day' },
yAxis: { format: 'currency', currency: 'USD' },
+ tooltip: { pinnable: true },
+ legend: { show: true, position: 'right' },
}}
>
<ReferenceLine value={100} orientation="horizontal" variant="goal" label="Target" />
@@ -81,42 +76,47 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the
</TimeSeriesLineChart>
```
-- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`, `HighlightedRange`) compose as children.
-- A custom overlay child with its own click/hover behavior (e.g. a clickable marker) should mark its interactive root with the `data-hog-charts-interactive-overlay` attribute. It bubbles inside the same wrapper the chart's own mousemove hover tracking listens on, so without the attribute the chart's nearest-point tooltip fights the overlay's own tooltip for the cursor.
-- `HighlightedRange` draws a translucent box spanning an x-axis range — pass `start`/`end` as data indices or labels (e.g. straight from `onDateRangeZoom`'s `startIndex`/`endIndex`). Use it to mirror an external selection (the rows visible in a paired virtualized list, a picked time window) onto the chart. On band (bar) charts the box covers the endpoints' full bands; on point (line) charts it runs point to point. `color`, `fillOpacity`, and `borderOpacity` tune the look (`borderOpacity: 0` drops the edge border); it clamps to the plot area and renders null when an endpoint doesn't resolve.
-- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) and series with `visibility.total: false` (values that don't sum meaningfully with the rest, e.g. a percentage column alongside counts — the row itself still renders) from the sum, and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored. Rows share one grid (swatch, label, value), so the value column is as wide as the widest value and every row's label ends at the same x — a `labelRenderer` that pushes part of its label right (e.g. a date) lines up as a column down the tooltip. Pinned tooltips are copy-friendly: outside-dismissal keys off where the press _started_ (pointer-down outside the tooltip/chart, or Escape), so a text-selection drag that releases outside the tooltip doesn't dismiss it, and a click that completes a text selection inside a row doesn't fire `onRowClick`.
-- A custom `tooltip` render prop builds its panel from the exported tooltip pieces: `TooltipSurface` (the floating panel), `TooltipSwatch` (series-color dot), and `TooltipFooter` (divider + muted row for a "click to inspect" hint — the same slot `DefaultTooltip`'s `footer` renders into, so a bespoke tooltip's hint stays styled like the built-in one).
-- Touch devices are tap-driven (cartesian charts): a tap on a data point reveals its tooltip — pinned when `config.tooltip.pinnable`, so its rows are tappable for `onRowClick` drill-downs — a tap on a different point moves it there, and a tap on the point whose tooltip is already showing runs the click action (dismiss a pinned tooltip; fire `onPointClick` on non-pinnable charts). Tapping outside the chart, scrolling, or Escape dismisses. Mouse hover/click behavior is unchanged; the split lives in `useChartInteraction`, keyed off the pointerdown's `pointerType`.
-- BarChart sets `TooltipContext.hoveredSeriesKey` — the key of the bar/segment under the cursor (stacked: the visible segment; grouped: the band-slot hit). Stacked `seriesData` keeps every segment in declaration order, so a custom tooltip that describes a single segment (e.g. a funnel breakdown) must select by `hoveredSeriesKey`, not `seriesData[0]`. It may reference a series hidden from `seriesData` via `visibility.tooltip: false` (e.g. a drop-off filler), and is `undefined` on other chart types and pinned rebuilds without a cursor. Grouped layouts also set `TooltipContext.inTrackArea` — `true` when the cursor is in the hovered bar's band slot but beyond its filled extent, measured on the same laid-out rects as click routing (`minBarSize` flooring included), so a tooltip's converted/drop-off framing always matches what a click at that position resolves to.
-- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, resolveClickToNearestSeries, placement, hitArea, valueFormatter, labelFormatter, showTotal, totalLabel, totalFormatter, sortedByValue }`). When no `tooltip` render prop is supplied, the chart renders `DefaultTooltip` with them applied; a render prop, if given, owns content entirely and these are ignored. Prefer config for "format each row / add a total" cases (e.g. SQL insights pass per-column formatters this way) and reach for the render prop only for genuinely custom tooltip markup (e.g. adding a `footer` hint). `hitArea` applies to bar charts and sets what the cursor must be over: `bar` (the default) needs the painted bar, so the empty space above a short bar shows nothing, while `band` accepts anywhere in the hovered band. `Sparkline` uses `band` for its bars, because a sparkline bar can be a pixel tall and a zero bucket has no bar to aim at. `resolveClickToNearestSeries` (default false) changes what a click on a `pinnable` multi-series chart does: instead of always pinning first (letting the user then click a specific row), it resolves the series nearest the cursor and fires `onPointClick` for it directly — skip pinning only where a click's target series is visually unambiguous by position (e.g. funnel breakdown areas, one per breakdown value); leave it off where series overlap closely and a wrong guess is costly (e.g. trend lines).
-- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin). A numeric line reveals its value on hover of the line itself (via a wider invisible hit area) or its label — appended as `label: value` when it has a label, shown alone when it doesn't — matching the legacy chart.js goal-line behavior.
-- `TrendLineOverlay` renders linear/exponential regression lines as SVG polylines on vertical bar and combo charts. Use via `trendLines?: TrendLineConfig[]` in `TimeSeriesBarChartConfig` or `TimeSeriesComboChartConfig` — the chart computes the derived series via `buildTrendLineSeries` and passes them to the overlay as a child. Only works for `axisOrientation: 'vertical'`; returns null on horizontal charts. Legend-toggled-off series are filtered automatically.
-- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original. `context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band (e.g. period-over-period). Collision avoidance is a single greedy pass over the full 2D label box (`minGap` on every side): a label is dropped only when it actually overlaps a higher-priority one, so on bar charts neighbours at different heights both keep their labels instead of the axis dropping every other bar. Ties resolve toward earlier series and left-to-right / top-to-bottom.
-- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`, `PieChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, onToggleSeries, onSetHiddenSeries, visibilityGroupKey, renderItem }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), follows Grafana's click model: **a plain click isolates that series** — every other row is hidden (no draw, no scale contribution, no tooltip, so the axes rescale into the freed space) while staying listed but dimmed — and clicking the isolated row again restores all. **⌘/Ctrl-click (or Shift-click) toggles one series** in or out of the visible set, so a selection is built up a row at a time. Picking one series out of twenty is the common case, and it costs one click rather than nineteen. A legend with one visibility group has nothing to isolate, so a plain click toggles instead. On a coarse pointer (touch screen) there is no ⌘/Ctrl/Shift, so a plain tap toggles instead of isolating, letting taps build any subset the way the checkbox legend table does (isolate stays reachable through the row menu). `visibilityGroupKey(rowKey)` maps a row onto the identity its visibility is actually stored against: rows sharing a group share one visibility bit, so isolating keeps the whole group visible, "only this one is visible" is judged per group, and the group count — not the row count — is what decides `canIsolate`. It defaults to the row's own key, so a legend whose rows are independent needs nothing. Trends needs it because comparing to the previous period puts a series' current and previous rows on one `resultCustomizations` key: without the hint the library would isolate a row, correctly leave its twin visible, and then never recognise the result as isolated — so the second click could not restore. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. A controlled legend must also pass `onSetHiddenSeries(nextHiddenKeys)` for isolating and hide-all to work — they replace the whole hidden set at once, which the per-key `onToggleSeries` can't express in one update; without it a controlled legend degrades to plain toggling, and an uncontrolled one needs nothing extra. Hidden by default. `config.legend.renderItem(defaultNode, item, controls)` wraps each rendered row, so consumers can augment it (e.g. attach a right-click context menu) while keeping the default swatch/label/toggle rendering — return `defaultNode` to leave a row untouched. `controls` is that row's `LegendItemControls`: state (`isHidden`, `isOnlyVisible`, `areAllVisible`, `canIsolate`) plus the actions (`toggle`, `isolate`, `toggleAll`) running the same paths as the clicks, so a row menu never re-derives visibility or duplicates the isolate logic. "All" and "the others" mean the legend's _rows_, not `series` — derived overlays (CI bands, trend lines) have no row and are never isolated against. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.
-- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. `onItemClick(key, { additive })` reports whether the click carried ⌘/Ctrl/Shift; deciding what each gesture means is the caller's job (`useChartLegend` is what turns it into isolate vs toggle). Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change). Long labels clip with an ellipsis only when they run out of the space actually available — there is no fixed max width. A vertical legend bounds each row to its column and truncates at the column edge; a horizontal legend caps each row at an equal share of the line floored at 180px (flexbox wraps before it shrinks, so without a cap one long label would take a whole line instead of clipping) — many series pack into tidy 180px columns while a few series with room to spare, or a lone series, show unclipped whenever they fit. The full text is always exposed via a native `title` tooltip on hover. The legend slot in `ChartLegendLayout` is bounded and scrolls (a top/bottom legend caps at ~40% of the chart height so the plot keeps the majority; a left/right legend stretches to full chart height and caps at 45% width but never more than 240px), so a many-series legend scrolls instead of squeezing or stretching the chart. A left/right legend uses `align-self: stretch` (resolves against the container's used height, so it works even when no ancestor sets an explicit `height`). The top/bottom `max-height: 40%` cap is a percentage, so it only resolves when the chart container has an **explicit** `height` — a flex-derived used size (e.g. `flex: 1` with only `min-height`/`max-height`) does **not** count and the cap silently no-ops; pin a real `height` on the container.
-- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
-- `FunnelChart` is a thin wrapper over grouped `BarChart` that owns the funnel look (hatched `track`, rounded + shadowed bars, percent value axis). `steps` is a `string[]` of display labels — duplicates are fine, bands are keyed by step index internally. Each `Series.data[stepIndex]` is the conversion from the first step as a percent (0–100); `funnelFromCounts` builds the single-series case from raw `{ label, count }` steps (zero basis yields 0, not NaN). `onStepClick` replaces `onPointClick` and reports `{ stepIndex, converted }` — `converted: false` means the hatched drop-off track above the bar was clicked. `stepFooter(stepIndex)` renders per-step content in a row below the plot, pixel-aligned under each step's bars (and hides the built-in step labels); use it for step legends richer than an axis label. Config: `hideStepLabels`, `hideValueAxis`, `barCornerRadius`, `bandPadding`, `minBarSize` (hover/click floor for near-zero bars, default `FUNNEL_MIN_BAR_SIZE` = 4px — the resting bar keeps its true size and grows to a clickable nub under the cursor via `minBarSizeScope: 'hover'`; pass 0 to disable), `maxBandRange` (cluster a 2–3 step funnel instead of stretching it), `chartMinHeight` (floor the plot region's px height when `stepFooter` is set, so a tall footer can't starve the `flex-1` canvas to zero height in a height-constrained column), plus the usual `tooltip`/`legend`/`margins`.
-- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes the sparkline from that index onward (e.g. an in-progress trailing period). `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).
-- The composable form of `MetricCard` lives one layer up as `Metric` in `@posthog/quill-components` (it needs `Card`/`Badge` from primitives, which charts can't depend on). It's built on `Sparkline` plus the headless metric helpers this package exports — `resolveDelta` / `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell) — and the `MetricChange` / `ResolvedDelta` types. Reach for `Metric` when you need a custom layout; use the monolithic `MetricCard` here for the default self-contained tile.
-- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped' | 'percent'`), `divergingStack` (stacked only — negative bar values stack below the zero baseline instead of being clamped to 0, same semantics as `BarsConfig.divergingStack`), and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.
-- `TimeSeriesBarChart` also takes `config.valueDomain` (same `ValueDomain` semantics as `BarChartConfig.bars.valueDomain`): setting both `min` and `max` skips `d3.nice()` and wins over the goal-line stretch — pin `{ min: 0, max: dataMax }` so the tallest bar reaches the plot top on an axis-less volume chart, where nice-rounded headroom is invisible waste; `include` merges with the goal-line stretch (`mergeValueDomains` in `utils/goal-lines.ts`).
-- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration_ms | duration_ns`, plus `prefix`/`suffix`. Without a `format` or `tickFormatter`, the axis uses the fewest uniform decimal places that keep its generated ticks distinct. Numeric and percentage formats default to two decimals but gain a decimal per leading zero below 0.1, so a small-valued axis (say latency in seconds over 0–0.012) doesn't render every tick as `0.01`; `decimalPlaces` pins the precision instead. The duration formats keep three significant digits below a minute for the same reason, then switch to the `1m 30s` unit breakdown.
-- Fixed x-axis tick rotation: set `xAxis.tickLabelRotation` on a time-series chart (`-45` tilts labels left). Values are clamped to `-90..90`; omit it to keep horizontal labels and existing collision behavior.
-- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.
-- y-axis min/max: `yAxis.min` / `yAxis.max` pin either end of a value axis on `TimeSeriesLineChart` (the primary one here; see the multi-axis entry below for secondary axes) (`config.valueDomain: { min, max }` on the lower-level `LineChart` — the same option that carries `include`, since a capped axis still has to stretch to reach an off-scale goal line; `mergeValueDomains` combines them field by field). How many ends are set decides the behavior: **both** pins the axis (skips `nice()`, discards `include`, overrides percent layout), **one** clamps that end and leaves the other automatic. A single clamp composes with auto-scaling — it runs after `include` folding, the zero-baseline clamp and `nice()`, so only the extreme label is the raw bound while interior ticks stay round — and is ignored under a percent layout, where the domain is already 0..1. On a log scale a non-positive bound is dropped. A non-finite bound counts as unset, so `{ min: 0, max: Math.max(...[]) }` floors at zero rather than collapsing. An inverted `min >= max` pair falls back to the automatic domain rather than swapping. Overlays positioned off the value scale hide themselves outside the bounded window rather than painting over the chrome: a goal line drops out, and so does the value label of a clipped point (a point sitting exactly on the bound keeps its label). Bar and combo charts deliberately ignore `min`/`max`, even though they take the same `yAxis` config: a bar encodes magnitude as length from zero, so a bounded baseline misreads it — 10 vs 11 would draw as 1 vs 2. Pin `valueDomain` there instead, which rescales the bars rather than truncating them.
-- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `hide`, `startAtZero`, and `min`/`max` are honored per entry (bar-series axes keep their zero baseline). Pin `min`/`max` on a secondary axis whose meaning fixes its range rather than letting it float to its data — a 0-1 probability, a 0-100 percentage — otherwise a reference line above every point on that axis falls outside the plot, where it doesn't draw at all (see the overlay note under y-axis min/max above). On the primary axis the same bounds arrive as the chart-level `valueDomain`, merged with the goal-line stretch, so they compose rather than override. A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.
-- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. Despite the name it is label-generic — it resolves the drag against label positions, so it works the same on categorical labels (weekdays, duration buckets) as on dates. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).
-- `onAreaSelect` (base `Chart`, chart-type adapters only) is the 2D-brush sibling of `onDateRangeZoom`: the drag tracks both axes, the selection rect clamps to the dragged vertical range, and the completed gesture reports the x label range plus the raw x and y pixel spans (with the committed scales, so the adapter maps pixels onto its own bands). `Heatmap` exposes it as `onBrush` with row/column index ranges; a near-horizontal drag (<8px vertical) spans every row. `ScatterChart` exposes it as its own `onAreaSelect`, inverting the pixel spans through its continuous scales — the label range is meaningless there, since it snaps to whichever points sit near the drag edges. Each edge is clamped to its axis first, so a drag that overshoots the plot (routine when brushing into a corner) reports the rectangle the user saw rather than an extrapolated one. Takes precedence over `onDateRangeZoom` when both are set.
-- `ScatterChart` takes `series: ScatterSeries[]` — each `{ key, label, points: { x, y, label?, radius?, color?, meta? }[], color?, pointRadius?, shape? }` — and no `labels`, since both axes are continuous. `config.xAxis` / `config.yAxis` are symmetric `ScatterAxisConfig`s (`scaleType: 'linear' | 'log'`, `domain` to pin the range, `label`, `tickFormatter`, `hide`, `startAtZero`); unlike a trend, both axes float to their data range by default, because forcing either to zero squashes the correlation into a corner. On a log axis, points with a non-positive coordinate can't be placed and are dropped from the chart. A pinned `domain` narrows the chart rather than just its viewport: points outside it are dropped too, so nothing is drawn out in the axis gutters or piled onto the plot edge at a value it doesn't have. `shape` (`circle` | `square` | `triangle` | `cross`) separates series without relying on color alone, and markers fill at `config.fillOpacity` (0.7) over an opaque outline so a dense cloud reads as density. Hit-testing is 2D and edge-based: the tooltip resolves the marker nearest the cursor in both axes (a large marker the cursor sits inside beats a small one whose center is nearer), and empty plot area resolves to nothing at all rather than to the nearest column. `onPointClick` and the `tooltip` render prop both receive the resolved point (`ScatterPointDatum`, with its series and `meta`) rather than a data index; `config.legend` and `config.tooltip` (`enabled`, `placement`, `labelFormatter`, `xFormatter`, `yFormatter`) work as elsewhere. The default tooltip labels its two rows from the axis titles, falling back to the hovered point's series label for y (so a chart with one column per series still names the measure) and to `X` for x; a header that would just repeat the y row is dropped, leaving a single-series scatter reading as two labeled coordinates. The chrome toggles are the same keys every other chart takes — `showGrid`, `showAxisLines`, `showTickMarks`, `showCrosshair`, all on by default like the other base charts (pass `false` to opt out). Its x ticks are resolved once per layout, so the grid lines, the tick marks, and the labels are the same set rather than three that can drift. `showBestFit` draws a dashed least-squares line per series, in that series' color, spanning only that series' own points so it doesn't extrapolate a relationship over empty space. It is canvas (over the markers, clipped to the plot), not the SVG `TrendLineOverlay`, whose regression fits y against the array index and so means nothing where x is a measure. The fit runs over the points' pixel positions, which minimizes the same residuals as fitting the raw values on a linear axis and the log values on a log one, and it sees only drawn points — so a series left with fewer than two, or with all of them stacked at a single x, gets no line.
+- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`, `HighlightedRange`, `AnomalyPointsLayer`) compose as children. Custom overlays read `useChartLayout()` / `useChartHover()`. [docs/overlays.md](./src/docs/overlays.md)
+- The built-in `DefaultTooltip` is configured through `config.tooltip`; a `tooltip` render prop replaces its content. [docs/tooltips.md](./src/docs/tooltips.md)
+- `config.legend` renders the built-in legend: plain click isolates, modifier click toggles. [docs/legend.md](./src/docs/legend.md)
+- Axis format, baseline, min/max, multi-axis, grid and axis-line chrome, margins. [docs/axes.md](./src/docs/axes.md)
+- Bar layouts, per-bar overrides, `minBarSize`, `trackData`, combo charts. [docs/bars.md](./src/docs/bars.md)
+- `onPointClick`, drag-to-zoom (`onDateRangeZoom`), 2D brush (`onAreaSelect`), touch. [docs/interactions.md](./src/docs/interactions.md)
+
+## Gotchas that bite
+
+- A duplicate label draws the series backwards. Use ISO dates, not display labels.
+- In percent layouts every formatter receives a 0..1 fraction; `ValueLabelContext.rawValue` has the original.
+- Bar and combo charts ignore `yAxis.min` / `max` on purpose. Pin `valueDomain` instead.
+- A pinned tooltip's `onRowClick` only fires when `config.tooltip.pinnable` is set. Call `ctx.onUnpin()` before opening a modal from it.
+- On stacked bars, describe the hovered segment from `TooltipContext.hoveredSeriesKey`, not `seriesData[0]`.
+- A secondary axis with a fixed meaning (0..1, 0..100) needs `min` / `max` pinned, or a reference line above its data falls off the plot.
+- A custom overlay with its own hover or click needs `data-hog-charts-interactive-overlay` on its root, or the chart's tooltip fights it for the cursor.
+- The top/bottom legend height cap only resolves against an explicit container `height`, not a flex-derived one.
+- A new `Series[]` reference every render recomputes the scales and repaints the canvas. Memoize.
## Testing
-Import test helpers from `@posthog/quill-charts/testing` (jsdom-only).
+Import helpers from `@posthog/quill-charts/testing` (jsdom only): `getHogChart` reads rendered overlays through stable `data-attr` hooks, `renderHogChart` adds tooltip-context capture for library tests, `hoverAtIndex` / `clickAtIndex` / `hoverUntilTooltip` / `dragSelection` drive gestures, and `createDefaultTooltipAccessor` reads the built-in tooltip. The `data-attr` selectors are a public contract. [docs/TESTING.md](./src/docs/TESTING.md)
-- `getHogChart(scope?)` reads rendered overlays via stable `data-attr` hooks — `yTicks()`, `xTicks()`, `valueLabels()`, `referenceLines()`, axis titles, `seriesCount`, etc. Its `waitForTooltip()` returns a structured `TooltipSnapshot` but only when the chart was mounted via `renderHogChart` (it needs the captured tooltip context). `canvas` is the static (data) canvas, for asserting the backing store or dispatching a canvas-level event — use it instead of `container.querySelector('canvas')`.
-- For a chart rendered outside `renderHogChart` (e.g. a real product scene), read the tooltip from the DOM: `getHogChartTooltip()` / `waitForHogChartTooltip()` return the portal element; `createHogChartTooltip(el)` wraps it as `{ element, isPinned }`. If the chart renders the built-in `DefaultTooltip`, use `createDefaultTooltipAccessor(el)` for `label()`, `rows()`, `value(seriesLabel)`, `swatchColors()`, and `total()` — it reads `DefaultTooltip`'s `data-attr="hog-chart-tooltip-*"` hooks (a stable testing contract; keep the accessor and the component's attrs in sync).
-- `hoverUntilTooltip(wrapper, index, totalLabels, timeout?)` and `clickAtIndex(wrapper, index, totalLabels, timeout?)` re-dispatch the hover until the tooltip portal mounts, since the chart drops events fired before it commits its scales. Both default to a 3000ms budget. Pass an explicit `timeout` whenever the call sits behind another wait in the same test (typically waiting for the canvas to render): two full-length waits chained together exceed Jest's 5000ms per-test budget, so the test dies before either helper can report which phase never completed. Give the pair one shared deadline and hand each the time remaining.
+## Docs index
+
+| Doc | Covers |
+| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
+| [src/README.md](./src/README.md) | Public surface, setup, theme, custom tooltip and overlay basics, sparkline |
+| [docs/chart-types.md](./src/docs/chart-types.md) | Per-chart behavior: scatter, funnel, slope, pie, box plot, heatmap, sparkline, metric card |
+| [docs/axes.md](./src/docs/axes.md) | Defaults, grid and axis chrome, x-axis labels, y format, baseline and range, multi-axis, margins, blank-plot diagnosis |
+| [docs/bars.md](./src/docs/bars.md) | Layouts, per-bar overrides, `minBarSize`, `trackData`, hit-testing, trend lines, combo |
+| [docs/tooltips.md](./src/docs/tooltips.md) | `config.tooltip`, `DefaultTooltip` props, custom pieces, context fields, touch |
+| [docs/legend.md](./src/docs/legend.md) | Click model, controlled state, visibility groups, row rendering, layout caps |
+| [docs/overlays.md](./src/docs/overlays.md) | Built-in overlays and writing a custom one |
+| [docs/interactions.md](./src/docs/interactions.md) | Clicks, drag-to-zoom, 2D brush, hover |
+| [docs/CONTRIBUTING.md](./src/docs/CONTRIBUTING.md) | Layers, conventions, adding a chart type |
+| [docs/TESTING.md](./src/docs/TESTING.md) | The accessor contract and test recipes |
## Maintenance
-When adding or changing a chart, overlay, or config option, update this guide in the same PR and add a story next to the component.
+When adding or changing a chart, overlay, or config option: write the JSDoc on the prop, add or update a story next to the component, and update the matching topic doc under `src/docs/` when the behavior spans more than one field. Add a row to this file only when the change alters which chart or approach a consumer should pick, or adds a gotcha. Do not append clauses to existing bullets here; this file stays a map.
+
+Keep detailed library behavior here or in `src/docs/`.
+The [consumer skill](../../../../.agents/skills/working-with-charts/SKILL.md) links to the relevant package docs and examples.
diff --git a/packages/quill/packages/charts/src/README.md b/packages/quill/packages/charts/src/README.md
index 0ebe24806708..08b24c0d0ad7 100644
--- a/packages/quill/packages/charts/src/README.md
+++ b/packages/quill/packages/charts/src/README.md
@@ -132,5 +132,12 @@ import { Sparkline } from '@posthog/quill-charts'
## More
+- Choosing a chart, the gotchas, and the docs index → [AGENTS.md](../AGENTS.md)
+- Per-chart behavior (scatter, funnel, slope, pie, metric card) → [docs/chart-types.md](./docs/chart-types.md)
+- Axes, ranges, multi-axis, chrome → [docs/axes.md](./docs/axes.md)
+- Bars: layouts, per-bar overrides, `minBarSize`, `trackData` → [docs/bars.md](./docs/bars.md)
+- Tooltips → [docs/tooltips.md](./docs/tooltips.md); legend → [docs/legend.md](./docs/legend.md)
+- Overlays, built-in and custom → [docs/overlays.md](./docs/overlays.md)
+- Clicks, drag-to-zoom, brush → [docs/interactions.md](./docs/interactions.md)
- Building a new chart type, library architecture, conventions → [docs/CONTRIBUTING.md](./docs/CONTRIBUTING.md)
- Writing tests against a chart, or against code that uses one → [docs/TESTING.md](./docs/TESTING.md)
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index b7abe1fb4d37..cbbbfbdf5302 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -46,8 +46,10 @@ export interface Series<Meta = unknown> {
label: string
/** Numeric values for each x-axis label. Must be the same length as the labels array. */
data: number[]
- /** CSS color string (hex, rgb, var(--…), etc.) for the line and associated fill/points.
- * When omitted (or empty), the chart picks a color from `theme.colors` by series index. */
+ /** CSS color string (hex, rgb) for the line and associated fill/points. Line, area, and bar
+ * series hand it to the canvas unresolved, so resolve `var(--…)` in the host first; only
+ * `Heatmap` and `ScatterChart` resolve it themselves. When omitted (or empty), the chart
+ * picks a color from `theme.colors` by series index. */
color?: string
/** Bar charts only: per-bar overrides of the series-level `color`/`label`/`meta`, indexed by
* data index. Lets one series draw bars with distinct identity (e.g. an aggregated breakdown,
diff --git a/packages/quill/packages/charts/src/docs/axes.md b/packages/quill/packages/charts/src/docs/axes.md
new file mode 100644
index 000000000000..d1832938e14c
--- /dev/null
+++ b/packages/quill/packages/charts/src/docs/axes.md
@@ -0,0 +1,75 @@
+# Axes, scales, and chrome
+
+Field-level semantics live on `XAxisConfig` and `YAxisConfig` in `utils/use-axis-formatters.ts`, `ChartConfig` and `ValueDomain` in `core/types.ts`, and `YFormatterConfig` in `utils/y-formatters.ts`.
+This page covers the behavior that spans several fields.
+
+## Defaults
+
+`useChartTheme()` and `themeFromCssVars()` carry the default styling: a faint dashed grid, a stronger axis line, and a dashed crosshair, each mixed as a share of the host's `--foreground` so they flip with light and dark.
+A host with its own token reader can layer just that part via `themeDefaultsFromCssVars()`.
+
+The matching config switches are the library default through `DEFAULT_CHART_CONFIG`: grid, axis lines, tick marks, crosshair, monotone curve, rounded bars, and cursor-anchored tooltip.
+`LineChart`, `BarChart`, `ComboChart`, and their time-series variants layer it under `config` via `applyChartDefaults`, so a consumer opts out field by field (`showGrid: false`).
+The nested `tooltip` merges key by key, so setting one field keeps `placement: 'cursor'`.
+`ScatterChart` renders the same chrome from its own inline defaults.
+`Sparkline` and `MetricCard` build their own chromeless config.
+
+## Grid, axis lines, tick marks
+
+- `showGrid` draws grid lines on every chart, including the time-series wrappers. Grid lines always align to the primary (left) y-axis ticks. A `showGrid` on the primary `yAxis` config wins; on secondary axes it is ignored, because two grids with unaligned ticks would be noise.
+- `showAxisLines` draws the L-axis alongside the grid, which then skips its own frame and category lines. A right-positioned y-axis gets its own right axis line. `{ x, y }` toggles each edge independently. With axis lines on, line strokes are trimmed at the y-axis and floored onto the x-axis so they rest against the axis instead of straddling it.
+- `showTickMarks` draws short canvas tick marks snapped to the same pixel grid as the axis.
+- `curve: 'monotone'` smooths line and area series through every point without overshoot.
+
+Theme-side restyle knobs, all optional: `theme.axisLineColor` strokes the baselines and tick marks without changing tick-label color (falls back `axisColor`, then `gridColor`); `theme.gridDashPattern` and `theme.crosshairDashPattern` (`[3, 3]`) dash the interior grid lines and the hover crosshair, while plot-edge frame strokes stay solid.
+
+## X-axis
+
+- Labels must be unique. The x-scale keys positions off the strings, so a duplicate collapses onto the first occurrence and draws the series backwards. On time-series charts pass ISO date strings, never formatted display labels that repeat across years, and format ticks via `xAxis.timezone` and `interval` or `tickFormatter`.
+- `xAxis.tickLabelRotation` (`-45` tilts left) fixes the rotation, clamped to `-90..90`. Omit it to keep horizontal labels and the collision behavior.
+- `maxCategoryLabelWidth` truncates category labels with an ellipsis and reveals the full value on hover. It also clamps the axis margin, so a long label cannot push the plot off screen. `MAX_CATEGORY_LABEL_WIDTH` is the exported default.
+
+## Y-axis format
+
+`format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration_ms | duration_ns`, plus `prefix` and `suffix`.
+
+Without a `format` or `tickFormatter`, the axis uses the fewest uniform decimal places that keep its ticks distinct.
+Numeric and percentage formats default to two decimals but gain a decimal per leading zero below 0.1, so a small-valued axis (latency in seconds over 0..0.012) does not render every tick as `0.01`.
+`decimalPlaces` pins the precision.
+The duration formats keep three significant digits below a minute, then switch to the `1m 30s` breakdown.
+Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`).
+
+## Baseline and range
+
+- The y-axis clamps a non-negative axis down to 0 by default. To float it to the data range, set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale and applied to the primary axis only. Bar charts always draw from zero.
+- `yAxis.min` and `max` pin either end on `TimeSeriesLineChart` (`config.valueDomain: { min, max }` on `LineChart`, the same option that carries `include`). Both set pins the axis: skips `nice()`, discards `include`, overrides percent layout. One set clamps that end and leaves the other automatic; it runs after `include` folding, the zero clamp, and `nice()`, so only the extreme label is the raw bound while interior ticks stay round. A single clamp is ignored under a percent layout, where the domain is already 0..1.
+- On a log scale a non-positive bound is dropped. A non-finite bound counts as unset, so `{ min: 0, max: Math.max(...[]) }` floors at zero rather than collapsing. An inverted `min >= max` pair falls back to the automatic domain rather than swapping.
+- Overlays positioned off the value scale hide themselves outside a bounded window rather than painting over the chrome: a goal line drops out, and so does the value label of a clipped point. A point sitting exactly on the bound keeps its label.
+- Bar and combo charts ignore `min` and `max` even though they take the same `yAxis` config. A bar encodes magnitude as length from zero, so a bounded baseline misreads it: 10 vs 11 would draw as 1 vs 2. Pin `valueDomain` there instead, which rescales the bars rather than truncating them. `TimeSeriesBarChart` takes `config.valueDomain`; setting both `min` and `max` skips `nice()` and wins over the goal-line stretch. Pin `{ min: 0, max: dataMax }` so the tallest bar reaches the plot top on an axis-less volume chart, where nice-rounded headroom is invisible waste. `include` merges with the goal-line stretch (`mergeValueDomains` in `utils/goal-lines.ts`).
+
+## Multiple y-axes
+
+Give a series a `yAxisId` to scale it against a second axis.
+On the time-series charts, pass `config.yAxis` as an array, one `YAxisConfig` per axis: `id` (matches `Series.yAxisId`; the first entry defaults to `'left'`), `position` (the first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`, `format`, `tickFormatter`, `label`, `showGrid`, `hide`, `startAtZero`, `min`, `max` per entry.
+A single object stays single-axis.
+
+- The second axis only renders when a series targets it; the primary axis owns the grid lines.
+- Bar-series axes keep their zero baseline.
+- Pin `min` and `max` on a secondary axis whose meaning fixes its range (a 0..1 probability, a 0..100 percentage) rather than letting it float to its data. Otherwise a reference line above every point on that axis falls outside the plot and does not draw. On the primary axis the same bounds arrive as the chart-level `valueDomain`, merged with the goal-line stretch, so they compose rather than override.
+- More than two axes work (trends `showMultipleYAxes`): they stack outward per side and alternate sides.
+- Each entry's `label` renders that axis's title at its own gutter, driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read, so the two cannot drift. A sole axis pinned `right` renders on the right on every chart type.
+
+## Margins and sizing
+
+- Charts fill their container and need a parent with real dimensions. A zero-height flex child renders nothing. Give the wrapper an explicit height (`h-64`, or `flex-1` in a sized column). `Sparkline` alone takes `height` and `width` props.
+- `ChartConfig.margins` overrides only the sides it sets. A side left `undefined` keeps the computed margin, so an object built conditionally (`{ top: reserveOrUndefined }`) is safe. `SlopeChart` merges consumer margins over its computed label gutters with the same rule (`applyMarginOverride`). Pass a module-level constant.
+
+## When the plot is blank
+
+Overlays (axis labels, titles, reference lines, value labels, legend, tooltip) are DOM positioned from the scales; the grid, axis lines, tick marks, and the series are canvas.
+If the labels and goal lines render in the right places but the plot area is empty, the layout is fine and the canvas alone failed.
+
+Check the cheap causes first: `theme.skipDraw` suppresses all canvas painting by design (use it for deterministic visual-snapshot tests, where the async paint pipeline races the screenshot), and a `drawStatic` that throws leaves the frame it was clearing empty.
+Beyond those, the bitmap is discarded either by `syncCanvasSize` reallocating it (a real resize) or by the browser losing the 2D context, and `useChartCanvas` repaints after both.
+A blank plot under correct overlays means one of those paths did not schedule its repaint.
+Safari never fires `contextrestored`, so a context lost there stays blank.
diff --git a/packages/quill/packages/charts/src/docs/bars.md b/packages/quill/packages/charts/src/docs/bars.md
new file mode 100644
index 000000000000..395851306e33
--- /dev/null
+++ b/packages/quill/packages/charts/src/docs/bars.md
@@ -0,0 +1,73 @@
+# Bars
+
+Applies to `BarChart`, `TimeSeriesBarChart`, `ComboChart`, `TimeSeriesComboChart`, and `FunnelChart`.
+Field docs live on `BarChartConfig` and `BarsConfig` in `core/types.ts`; the per-bar `Series` options are on `Series.bars` and `Series.trackData`.
+
+## Layouts
+
+- `barLayout: 'stacked' | 'grouped' | 'percent'`. Percent stacks bar series to 100% and puts the value scale on 0..1, so formatters receive fractions. Stacking groups by axis.
+- `axisOrientation: 'horizontal'` for horizontal bars. Drag-to-zoom is disabled there, since the interaction axis is vertical.
+- `divergingStack` (stacked only) stacks negative values below the zero baseline instead of clamping them to 0. Same semantics on `ComboChart` and `TimeSeriesComboChart`.
+- `barCornerRadius` rounds the end caps. It is a top-level key on every bar-capable chart, including the time-series and combo configs.
+- `TimeSeriesBarChart` takes `minBarSize`, `bandPadding`, `margins`, and `maxCategoryLabelWidth` as top-level config keys (alongside `barCornerRadius` and `fillStyle`) rather than under `bars`.
+
+## Per-bar overrides
+
+`Series.bars[i]` overrides `color`, `label`, and `meta` for one bar, so one series can draw bars with distinct identity (an aggregated breakdown, one bar per value) instead of paying the cost of one series per bar.
+Bar fill, hover highlight, and the tooltip read it; track decorations do not.
+
+`bars[i].hatch: true` fills that bar with a diagonal-hatch pattern in its resolved color.
+Use it to flag individual not-final bars (a bucket still being ingested) at arbitrary indices.
+For a contiguous trailing range, `stroke.partial.fromIndex` does the same.
+
+## Minimum bar size
+
+`bars.minBarSize` (px) floors each non-zero bar's thickness along the value axis, so a single-occurrence bucket stays visible beside a spike three orders of magnitude taller.
+Zero-valued bars are never floored, so empty buckets stay empty.
+
+On a stacked chart only the outermost segment is floored: flooring an interior one would oversize a rect the segment above overpaints while still capturing its hover and clicks.
+A breakdown stack floors only its top segment, so the option is aimed at single-series volume charts and grouped bars.
+`Sparkline` does not expose it.
+
+`bars.minBarSizeScope: 'hover'` restricts the floor to the hover highlight and hit-testing.
+The static layer draws true sizes and a tiny bar grows to a clickable nub under the cursor; while its track is hovered, the floored bar is also revealed in its plain color.
+The default `'always'` floors the static layer too.
+
+## Interactive extent: `trackData`
+
+`Series.trackData[i]` caps a bar's interactive extent at a per-bar ceiling in value units.
+The region beyond it is a fully inert gap: no hover, tooltip, pointer cursor, highlight, or click (the chart vetoes the hover via `resolveHoverIndex`).
+On grouped charts with `bars.track`, the hatched "share of a whole" track also fills only to the ceiling.
+On stacked charts no track is drawn; the ceiling only bounds interactivity.
+
+Funnel compare uses it to draw a shorter period's volume gap as empty space rather than drop-off, in both its grouped (left to right) and stacked (top to bottom) charts.
+
+## Hit-testing
+
+Bar geometry is computed once by `computeSeriesBars` in `core/bar-layout.ts`, and the hover path resolves the bar under the cursor from the same rects (`charts/BarChart/bars-under-cursor.ts`).
+A change that lets the hover geometry diverge from the draw geometry is a bug.
+`TooltipContext.hoveredSeriesKey` and `inTrackArea` come from this resolution; see [tooltips.md](./tooltips.md).
+
+## Value labels on bars
+
+`ValueLabels` collision avoidance is a single greedy pass over the full 2D label box (`minGap` on every side).
+A label is dropped only when it overlaps a higher-priority one, so neighbors at different heights both keep their labels instead of the axis dropping every other bar.
+Ties resolve toward earlier series and left to right, top to bottom.
+See [overlays.md](./overlays.md) for the formatter contract.
+
+## Trend lines on bars
+
+`TrendLineOverlay` renders linear or exponential regression lines as SVG polylines on vertical bar and combo charts.
+Use it via `trendLines?: TrendLineConfig[]` in `TimeSeriesBarChartConfig` or `TimeSeriesComboChartConfig`; the chart computes the derived series via `buildTrendLineSeries` and passes them to the overlay.
+Vertical orientation only; it returns null on horizontal charts.
+Legend-toggled-off series are filtered automatically.
+
+## Combo charts
+
+`ComboChart` mixes bar, line, and area series on one band x-axis.
+Set `Series.type` per series; vertical only.
+Under `barLayout: 'percent'`, a line or area series needs its own `yAxisId: 'right'` axis, because one sharing the bars' axis cannot plot raw values against their 0..1 scale.
+`ComboChart` honors `valueDomain` (primary axis only) and `showAxisLines`.
+
+`TimeSeriesComboChart` wraps it the way the other time-series charts wrap their base: `config.xAxis` and `config.yAxis` (date tick formatter, y format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `valueDomain`), `config.legend`, and `config.valueLabels`.
+`barLayout`, `divergingStack`, and right-axis series carry over.
diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.md
new file mode 100644
index 000000000000..9da021901004
--- /dev/null
+++ b/packages/quill/packages/charts/src/docs/chart-types.md
@@ -0,0 +1,98 @@
+# Chart types
+
+Behavior notes for the specialized charts.
+The line, bar, and combo families are covered by [axes.md](./axes.md), [bars.md](./bars.md), and the README.
+Prop-level docs live on each chart's props and config interfaces.
+
+## TimeSeriesLineChart
+
+`LineChart` plus time-series chrome: date ticks from `xAxis.timezone` and `interval`, an interval-aware tooltip header, `goalLines`, `valueLabels`, `legend`, and the derived series configs (`confidenceIntervals`, `movingAverage`, `trendLines`).
+`comparisonOf` maps comparison series keys to their primary so they render dimmed.
+`percentStackView` renders area series as a 100% stack with a 0..100% axis.
+
+Derived series: trend lines and moving averages are `overlay: true`, so they are excluded from stacking and from the baseline calculation and a projection cannot drag the axis below zero.
+Confidence bands are not overlays; they represent real uncertainty whose range should still influence the axis.
+Hiding a series through the legend hides everything derived from it.
+
+## ScatterChart
+
+Takes `series: ScatterSeries[]`, each `{ key, label, points: { x, y, label?, radius?, color?, meta? }[], color?, pointRadius?, shape? }`, and no `labels`, since both axes are continuous.
+
+- `config.xAxis` and `config.yAxis` are symmetric `ScatterAxisConfig`s (`scaleType`, `domain`, `label`, `tickFormatter`, `hide`, `startAtZero`). Both axes float to their data range by default, because forcing either to zero squashes the correlation into a corner.
+- On a log axis, points with a non-positive coordinate are dropped. A pinned `domain` narrows the chart rather than the viewport: points outside it are dropped too, so nothing piles onto the plot edge at a value it does not have.
+- `shape` (`circle | square | triangle | cross`) separates series without relying on color. Markers fill at `config.fillOpacity` (0.7) over an opaque outline so a dense cloud reads as density.
+- Hit-testing is 2D and edge-based: the tooltip resolves the marker nearest the cursor in both axes (a large marker the cursor sits inside beats a small one whose center is nearer), and empty plot area resolves to nothing rather than to the nearest column.
+- `onPointClick` and the `tooltip` render prop receive the resolved `ScatterPointDatum` (with its series and `meta`), not a data index. `config.tooltip` takes `enabled`, `placement`, `labelFormatter`, `xFormatter`, `yFormatter`. The default tooltip labels its two rows from the axis titles, falling back to the hovered point's series label for y and to `X` for x; a header that would repeat the y row is dropped.
+- Chrome toggles are the usual `showGrid`, `showAxisLines`, `showTickMarks`, `showCrosshair`, all on by default. X ticks are resolved once per layout, so grid lines, tick marks, and labels are one set.
+- `showBestFit` draws a dashed least-squares line per series, in that series' color, spanning only its own points. It is canvas, not `TrendLineOverlay`, whose regression fits y against the array index and means nothing where x is a measure. The fit runs over pixel positions, so it minimizes the right residuals on both linear and log axes, and it sees only drawn points: a series with fewer than two, or all at one x, gets no line.
+- `onAreaSelect` reports the dragged rectangle through the continuous scales; see [interactions.md](./interactions.md).
+
+## FunnelChart
+
+A thin wrapper over grouped `BarChart` that owns the funnel look: hatched `track`, rounded and shadowed bars, percent value axis.
+
+- `steps` is a `string[]` of display labels; duplicates are fine, bands are keyed by step index.
+- Each `Series.data[stepIndex]` is the conversion from the first step as a percent (0..100). `funnelFromCounts` builds the single-series case from raw `{ label, count }` steps (a zero basis yields 0, not `NaN`).
+- `onStepClick` replaces `onPointClick` and reports `{ stepIndex, converted }`; `converted: false` means the hatched drop-off track above the bar was clicked.
+- `stepFooter(stepIndex)` renders per-step content in a row below the plot, pixel-aligned under each step's bars, and hides the built-in step labels. Use it for step legends richer than an axis label.
+- Config: `hideStepLabels`, `hideValueAxis`, `barCornerRadius`, `bandPadding`, `minBarSize` (hover and click floor for near-zero bars; default `FUNNEL_MIN_BAR_SIZE` of 4px, applied with `minBarSizeScope: 'hover'` so the resting bar keeps its true size and grows to a clickable nub under the cursor; pass 0 to disable), `maxBandRange` (cluster a two or three step funnel instead of stretching it), `chartMinHeight` (floor the plot height when `stepFooter` is set, so a tall footer cannot starve the canvas to zero height in a height-constrained column), plus the usual `tooltip`, `legend`, `margins`.
+- Compare mode uses `trackData` to draw a shorter period's volume gap as empty space; see [bars.md](./bars.md).
+
+## SlopeChart
+
+One line per series from a left "before" to a right "after"; `data` is `[start, end]`.
+
+- `showSeriesLabels` puts the name beside each point; on collision the series with the largest change keeps its label.
+- `showStartLabels` and `showEndLabels` are chart-level defaults, overridable per series via `meta.showStartLabel` and `meta.showEndLabel`. The value axis is hidden by default; the start and end labels are the readout.
+- `legend: { show, position }`. Rows carry the formatted change and are ordered biggest to smallest by end value to match the lines' right-edge order.
+- `valueFormatter` and `deltaFormatter` format the labels and the legend's change.
+- The default tooltip orders rows biggest to smallest by the hovered point's value, so many-breakdown tooltips match the lines' vertical order, and formats with `valueFormatter` so values match the on-chart labels' units.
+- `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period). The renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
+- Consumer `margins` merge over the computed label gutters; an `undefined` side keeps the gutter the labels reserved.
+
+## PieChart
+
+Part of whole, one value per series (`data[0]`).
+
+- `innerRadiusRatio` makes a donut; `centerLabel` fills the hole.
+- On-slice labels via `showLabelOnSlice` and `showValueOnSlice`, positioned with `labelRadiusRatio` (0 is the center, 1 the rim) and gated by `minSlicePercentForLabel`.
+- `sliceValueDisplay` picks what the numeric line holds: `'value'`, `'percent'`, or `'both'` for `352 (18.4%)`. Defaults to `'percent'` when `isPercent` is set, else `'value'`.
+- `config.legend` renders the built-in legend; a toggled-off slice is removed and the rest rescale to the full circle.
+- `theme.backgroundColor` is required for the hover pop-out mask; without it the pop-out is skipped. `disableHoverOffset` turns the pop-out off.
+- Children read `useRadialLayout()` for `layout.slices`, `innerRadius`, `outerRadius`, `cx`, `cy`, and `centroidAngle`.
+
+## BoxPlot
+
+Distribution summaries: `{ min, p25, median, mean, p75, max }` per label.
+Supports `config.legend` for grouped series and `onBoxClick`.
+The tooltip receives a `BoxPlotTooltipContext`; `BoxPlotTooltip` is the default.
+
+## Heatmap
+
+A 2D density grid: `xLabels` by `yLabels` (row 0 at the bottom), `cells[row][col]` counts mapped to color intensity on one accent.
+Log ramp by default; `colorScale: 'linear'` to opt out.
+A single-cell tooltip resolves from the cursor, `onCellClick` reports `{ xIndex, yIndex, value }`, and `onBrush` reports row and column index ranges.
+
+## Sparkline
+
+An axis-less preset over `LineChart` (default, gradient-filled line) or stacked bars via `type: 'bar'`.
+Takes a flat `number[]` plus `color`, or full `series` for multi-series, and `height` and `width` props instead of filling its container.
+The tooltip is off by default; opt in with a `tooltip` render prop.
+Bars use `hitArea: 'band'`.
+`onHoverIndexChange` lets a consumer drive a hover-following headline without subscribing to `useChartHover` itself.
+`minBarSize` is not exposed.
+
+## MetricCard
+
+A left-aligned tile: headline number, change pill, sparkline.
+
+- `title={null}` drops the title row. The header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle and no `labels`, so a value-only card renders just the number.
+- `changeSize="md"` renders a larger pill (default `sm`); `changeInline` puts it beside the headline instead of in the header.
+- `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes it from that index onward (an in-progress trailing period).
+- `subtitle` always wins. `restingSubtitle` (`'Avg'`) shows only at rest and yields to the hovered point's label on hover; pair it with a `value` that summarizes the series.
+- `hoverChangeFromPreviousPoint` keeps the resting `change` pill at rest but, while hovering, swaps it for the hovered point's change versus the previous point (hidden at the first point).
+- `changeTooltip` shows a styled hover tooltip on the change pill, using the host's tooltip surface tokens with chart-surface fallbacks.
+
+The composable form is `Metric` in `@posthog/quill-components` (it needs `Card` and `Badge` from primitives, which charts cannot depend on).
+It is built on `Sparkline` plus the headless helpers this package exports: `resolveDelta` and `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell), and the `MetricChange` and `ResolvedDelta` types.
+Reach for `Metric` for a custom layout; use `MetricCard` for the default self-contained tile.
diff --git a/packages/quill/packages/charts/src/docs/interactions.md b/packages/quill/packages/charts/src/docs/interactions.md
new file mode 100644
index 000000000000..9b2672b5eaa7
--- /dev/null
+++ b/packages/quill/packages/charts/src/docs/interactions.md
@@ -0,0 +1,54 @@
+# Interactions
+
+## `onPointClick`
+
+Fires with `PointClickData` (see `core/types.ts`): the primary `series`, `seriesIndex`, `dataIndex`, `label`, `value`, `crossSeriesData` for every visible series at that index, the `cursor` position, and `inTrackArea` on grouped bars.
+Read the domain object back from `series.meta`, not from array position.
+
+On a `pinnable` multi-series chart, a click pins the tooltip first and the user then clicks a row (`DefaultTooltip.onRowClick`).
+`config.tooltip.resolveClickToNearestSeries` skips the pin and fires `onPointClick` for the nearest series directly; see [tooltips.md](./tooltips.md) for when that is safe.
+
+Chart-specific variants: `FunnelChart.onStepClick` reports `{ stepIndex, converted }`, where `converted: false` means the hatched drop-off track was clicked; `PieChart.onSliceClick`; `BoxPlot.onBoxClick`; `Heatmap.onCellClick` reports `{ xIndex, yIndex, value }`; `ScatterChart.onPointClick` receives the resolved `ScatterPointDatum`.
+
+## Drag-to-zoom: `onDateRangeZoom`
+
+On `LineChart`, `TimeSeriesLineChart`, `BarChart`, `TimeSeriesBarChart`, and the base `Chart`.
+The user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }`.
+The chart does not manage zoom state; the parent decides what to do with the range, usually updating a date filter.
+
+- Despite the name it is label-generic: it resolves the drag against label positions, so it works on categorical labels (weekdays, duration buckets) as on dates.
+- A drag whose edges both snap to the same label (common on sparse charts, a three-bar monthly chart) selects that single bucket, provided the drag spans enough distance to read as intentional.
+- The cursor switches to a crosshair when set, except over an actionable point (`onPointClick` set), where it stays a pointer. A plain click without movement still pins the tooltip or fires `onPointClick`.
+- X-axis only. No effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars), where the core disables the gesture.
+- Both emitted values are bucket starts. Widening the end to the last bucket's end is the host's job.
+
+`HighlightedRange` takes the same indices to draw the selection back onto the chart.
+
+## 2D brush: `onAreaSelect`
+
+On the base `Chart`, for chart-type adapters.
+The drag tracks both axes, the selection rect clamps to the dragged vertical range, and the completed gesture reports the x label range plus the raw x and y pixel spans with the committed scales, so the adapter maps pixels onto its own bands.
+Each edge is clamped to its axis first, so a drag that overshoots the plot reports the rectangle the user saw rather than an extrapolated one.
+Takes precedence over `onDateRangeZoom` when both are set.
+
+- `Heatmap` exposes it as `onBrush` with row and column index ranges; a near-horizontal drag (under 8px vertical) spans every row.
+- `ScatterChart` exposes it as its own `onAreaSelect`, inverting the pixel spans through its continuous scales. The label range is meaningless there.
+
+## Hover and touch
+
+Hover state lives in its own context so only `useChartHover()` consumers re-render on mousemove.
+Anything that needs layout only reads `useChartLayout()`.
+Touch devices are tap-driven; see [tooltips.md](./tooltips.md).
+
+## Legend clicks
+
+Plain click isolates, modifier click toggles, tap toggles.
+See [legend.md](./legend.md).
+
+## Testing interactions
+
+`hoverAtIndex`, `clickAtIndex`, `hoverUntilTooltip`, and `dragSelection` from `@posthog/quill-charts/testing` drive these gestures in jsdom.
+`hoverUntilTooltip` and `clickAtIndex` re-dispatch until the tooltip portal mounts, because the chart drops events fired before it commits its scales.
+Both default to a 3000ms budget.
+Pass an explicit `timeout` whenever the call sits behind another wait in the same test; two full-length waits chained together exceed Jest's 5000ms per-test budget, so give the pair one shared deadline.
+See [TESTING.md](./TESTING.md).
diff --git a/packages/quill/packages/charts/src/docs/legend.md b/packages/quill/packages/charts/src/docs/legend.md
new file mode 100644
index 000000000000..625878c39e3c
--- /dev/null
+++ b/packages/quill/packages/charts/src/docs/legend.md
@@ -0,0 +1,64 @@
+# Legend
+
+Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `TimeSeriesComboChart`, `SlopeChart`, `PieChart`) takes `config.legend: ChartLegendConfig`.
+Hidden by default; `show: true` renders the built-in legend.
+The fields are documented on `ChartLegendConfig` in `core/types.ts`.
+
+## Click model
+
+With `interactive` (the default when shown), the legend follows Grafana's model:
+
+- **A plain click isolates that series.** Every other row is hidden (no draw, no scale contribution, no tooltip, so the axes rescale into the freed space) while staying listed but dimmed. Clicking the isolated row again restores all.
+- **⌘/Ctrl-click or Shift-click toggles one series** in or out of the visible set, so a selection is built up a row at a time.
+
+Picking one series out of twenty is the common case, and it costs one click rather than nineteen.
+A legend with one visibility group has nothing to isolate, so a plain click toggles instead.
+On a coarse pointer (touch) there is no modifier key, so a plain tap toggles, and isolate stays reachable through the row menu.
+
+Set `interactive: false` for a static legend.
+
+## Controlled and uncontrolled
+
+By default the chart owns the toggled-off state.
+Pass `hiddenKeys` plus `onToggleSeries` to control it yourself.
+A controlled legend must also pass `onSetHiddenSeries(nextHiddenKeys)` for isolating and hide-all to work: they replace the whole hidden set at once, which the per-key `onToggleSeries` cannot express in one update.
+Without it a controlled legend degrades to plain toggling.
+
+`hiddenKeys` stays in row space either way.
+
+## Visibility groups
+
+`visibilityGroupKey(rowKey)` maps a row onto the identity its visibility is stored against.
+Rows sharing a group share one visibility bit: isolating keeps the whole group visible, "only this one is visible" is judged per group, and the group count decides `canIsolate`.
+It defaults to the row's own key, so a legend whose rows are independent needs nothing.
+
+Trends needs it because comparing to the previous period puts a series' current and previous rows on one `resultCustomizations` key.
+Without the hint the library would isolate a row, correctly leave its twin visible, and then never recognize the result as isolated, so the second click could not restore.
+
+## Row rendering
+
+`renderItem(defaultNode, item, controls)` wraps each rendered row.
+Return `defaultNode` to leave a row untouched, or wrap it (a right-click context menu) while keeping the default swatch, label, and toggle rendering.
+`controls` is that row's `LegendItemControls`: state (`isHidden`, `isOnlyVisible`, `areAllVisible`, `canIsolate`) plus the actions (`toggle`, `isolate`, `toggleAll`) running the same paths as the clicks, so a row menu never re-derives visibility.
+
+"All" and "the others" mean the legend's rows, not `series`.
+Derived overlays (confidence bands, trend lines, moving averages) have no row and are never isolated against.
+On time-series charts the legend lists the user's series only, and hiding a series also hides everything derived from it, so no orphaned overlay floats over the gap.
+
+## Layout
+
+- The legend slot in `ChartLegendLayout` is bounded and scrolls. A top or bottom legend caps at about 40% of the chart height; a left or right legend stretches to full chart height and caps at 45% width but never more than 240px. A many-series legend scrolls instead of squeezing the plot.
+- The top and bottom cap is a percentage, so it only resolves when the chart container has an explicit `height`. A flex-derived size (`flex: 1` with only `min-height`) does not count and the cap silently no-ops. Pin a real `height` on the container.
+- A left or right legend uses `align-self: stretch`, which resolves against the container's used height, so it works without an explicit `height`.
+- Long labels clip with an ellipsis only when they run out of available space. A vertical legend truncates at the column edge. A horizontal legend caps each row at an equal share of the line floored at 180px, because flexbox wraps before it shrinks and one long label would otherwise take a whole line. The full text is always in a native `title` tooltip.
+- `LegendItem.secondaryLabel` shows muted trailing text (a slope chart's per-series change).
+
+## Lower-level primitives
+
+`Legend` (and `ChartLegend` for layout) is the presentational primitive: pass `items`, `onItemClick`, `hiddenKeys`; filtering series is the caller's state.
+`onItemClick(key, { additive })` reports whether the click carried a modifier; deciding what each gesture means is the caller's job.
+Use it directly when `config.legend` cannot express what you need (custom item order or labels, the legend rendered outside the chart slot).
+
+`useChartLegend(series, theme, config, items?)` is the shared hook the charts use.
+It returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`.
+`applyHiddenSeries` is the underlying helper, and `legendItemsFromSeries(series, theme)` builds the item list.
diff --git a/packages/quill/packages/charts/src/docs/overlays.md b/packages/quill/packages/charts/src/docs/overlays.md
new file mode 100644
index 000000000000..63a5f104e271
--- /dev/null
+++ b/packages/quill/packages/charts/src/docs/overlays.md
@@ -0,0 +1,97 @@
+# Overlays
+
+Overlays are React DOM (or SVG) rendered on top of the canvas, positioned from the chart's scales.
+They compose as children of a chart:
+
+```tsx
+<TimeSeriesLineChart series={series} labels={isoLabels} theme={theme} config={config}>
+ <ReferenceLine value={100} orientation="horizontal" variant="goal" label="Target" />
+ <ValueLabels mode="stack-total" offset={8} />
+</TimeSeriesLineChart>
+```
+
+Trend lines, moving averages, and confidence bands are not overlays.
+They are derived `Series` entries (`overlay: true` for the first two), so the legend, the tooltip, and the axis already know about them.
+
+## Built-in overlays
+
+Prop docs live on each component's props interface under `overlays/`.
+
+### `ReferenceLine` / `ReferenceLines`
+
+Variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
+A numeric line reveals its value on hover of the line itself (via a wider invisible hit area) or of its label, appended as `label: value` when it has a label and shown alone when it does not.
+`showValueOnHover: false` turns that off and removes the hit area, for a line whose caption already states the number or that should not react to the pointer.
+A vertical line resolves x through `scales.x(label)`, so it can only sit on a label.
+`axisOrientation: 'horizontal'` flips a numeric line into a vertical stripe for horizontal bar charts; it defaults from context, so callers rarely pass it.
+A line whose value falls outside a pinned axis range hides itself.
+
+Time-series charts also take `config.goalLines: GoalLineConfig[]`, which builds these lines for you and stretches the value axis so an off-scale target stays on the plot.
+`buildGoalLineReferenceLines` is the helper behind it.
+
+### `ValueLabels`
+
+The formatter gets `(value, seriesIndex, dataIndex, context)`.
+In percent layouts `value` is a 0..1 fraction; `context.rawValue` holds the original.
+`context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band.
+`mode="stack-total"` labels only the stack top.
+`series.visibility.valueLabel: false` skips a series.
+On the time-series charts, prefer `config.valueLabels` so the chart sizes its margins for the labels.
+
+### `AxisTitles`
+
+Renders axis titles in the gutters computed by `computeYAxisGutters`.
+The time-series charts render it from `xAxis.label` and `yAxis.label`; compose it yourself only on the base charts.
+
+### `TrendLineOverlay`
+
+Regression lines on vertical bar and combo charts. See [bars.md](./bars.md).
+
+### `HighlightedRange`
+
+A translucent box spanning an x-axis range.
+Pass `start` and `end` as data indices or labels, straight from `onDateRangeZoom`'s `startIndex` and `endIndex`.
+Use it to mirror an external selection (the rows visible in a paired virtualized list, a picked time window) onto the chart.
+On band (bar) charts the box covers the endpoints' full bands; on point (line) charts it runs point to point.
+`color`, `fillOpacity`, and `borderOpacity` tune the look (`borderOpacity: 0` drops the edge border).
+It clamps to the plot area and renders null when an endpoint does not resolve.
+
+### `AnomalyPointsLayer`
+
+Small filled dots at `{ dataIndex, value, yAxisId, color }`.
+DOM rather than a series, because a sparse series would make `drawLine` stitch a line through the `NaN` gaps.
+`radius` defaults to 3.
+
+## Custom overlays
+
+Any React child can read layout and hover state through the context hooks:
+
+- `useChartLayout()`: `scales`, `dimensions`, `labels`, `series` (colors resolved), `theme`, `axis` (`orientation`, `xTickFormatter`, `isPercent`), `yGutters`, `resolvePositionValue`, and `canvasBounds()`. Does not re-render on hover.
+- `useChartHover()`: `hoverIndex`. Re-renders on every mousemove.
+- `useChart()`: both, kept for back-compat. Use the granular hooks unless an overlay needs both.
+- `useRadialLayout()` for `PieChart` children: `layout.slices`, radii, `cx`, `cy`.
+
+```tsx
+function GoalLine() {
+ const { scales, dimensions } = useChartLayout()
+ const y = scales.y(100)
+ if (y < dimensions.plotTop || y > dimensions.plotTop + dimensions.plotHeight) {
+ return null
+ }
+ return <div data-attr="goal-line" className="absolute left-0 right-0 border-t border-dashed" style={{ top: y }} />
+}
+```
+
+Rules:
+
+- Position from the scales. `scales.x(label, seriesKey?)` returns the band or point center, or a specific series' bar in grouped layouts. `scales.y(value)` uses the primary axis; `scales.yAxes[id].scale(value)` for another axis. `scales.extent(label)` is the band width on bar charts. `resolvePositionValue(seriesIndex, dataIndex)` is the stacked top when the chart stacks.
+- Between-label positions need interpolation between the two bracketing labels. Band and point scales only resolve whole labels.
+- `computeVisibleXLabels(labels, scales.x, axis.xTickFormatter)` returns the tick set the axis actually drew, for overlays that must align with it.
+- Hide anything outside `dimensions.plotLeft/Top/Width/Height`.
+- The overlay layer is `pointer-events: none`. Opt in only on the element the user interacts with.
+- An overlay with its own click or hover behavior (a clickable marker) marks its interactive root with `data-hog-charts-interactive-overlay`. It bubbles inside the same wrapper the chart's mousemove tracking listens on, so without the attribute the chart's nearest-point tooltip fights the overlay's own tooltip for the cursor. Stop propagation on click so `onPointClick` does not also fire.
+- Give it a `data-attr` and, if it lives in the library, an accessor method in `testing/accessor.ts`.
+- Memoize anything derived from `labels` and `scales.x`, keyed on `scales.x` rather than `scales`.
+
+App-specific overlays (annotations, alert thresholds, billing markers) stay in the app next to their consumer.
+The library ships only overlays that any host could use.
diff --git a/packages/quill/packages/charts/src/docs/tooltips.md b/packages/quill/packages/charts/src/docs/tooltips.md
new file mode 100644
index 000000000000..717c3a94e486
--- /dev/null
+++ b/packages/quill/packages/charts/src/docs/tooltips.md
@@ -0,0 +1,70 @@
+# Tooltips
+
+Prefer each chart's built-in tooltip before supplying a `tooltip` render prop.
+This guide covers the shared `DefaultTooltip` used by line, bar, and combo charts.
+Other charts, such as scatter and pie, provide specialized tooltips; check their props and [chart-type docs](./chart-types.md) for supported options.
+
+## Behavior: `config.tooltip`
+
+`TooltipConfig` (see the JSDoc in `core/types.ts`) sets `enabled`, `pinnable`, `placement`, `resolveClickToNearestSeries`, and `hitArea`.
+
+- `placement: 'cursor'` is the library default through `DEFAULT_CHART_CONFIG`; `follow-data` tracks the highest point at the hovered x and `top` pins the panel to the top edge.
+- `pinnable` lets a click pin the panel. An unpinned tooltip is `pointer-events: none`, so row clicks only land once it is pinned.
+- `resolveClickToNearestSeries` (default false) makes a click on a pinnable multi-series chart resolve the series nearest the cursor and fire `onPointClick` directly instead of pinning first. Use it only where the target series is visually unambiguous by position (funnel breakdown areas, one per breakdown value). Leave it off where series overlap and a wrong guess is costly (trend lines).
+- `hitArea` applies to bar charts. `bar` (default) needs the cursor over the painted bar, so the empty space above a short bar shows nothing. `band` accepts anywhere in the hovered band. `Sparkline` uses `band` because a sparkline bar can be one pixel tall and a zero bucket has no bar to aim at.
+
+## Formatting without a render prop
+
+`config.tooltip` also forwards `valueFormatter`, `labelFormatter`, `showTotal`, `totalLabel`, `totalFormatter`, and `sortedByValue` into `DefaultTooltip`.
+Prefer this for "format each row" and "add a total" cases (SQL insights pass per-column formatters this way).
+A render prop, if given, owns the content and these fields are ignored.
+
+## `DefaultTooltip` props
+
+Usable from a custom `tooltip` render prop by spreading the context: `<DefaultTooltip {...ctx} footer="..." />`.
+
+- `valueFormatter(value, entry)` gets the row's `seriesData` entry as the second argument, so each row can format with its own `series.meta` (per-column currency or duration). It may return a node, not only a string. A formatter that takes only `value` stays compatible. Defaults to `toLocaleString`.
+- `labelFormatter(label)` transforms the raw x-axis label in the header. On time-series charts with `xAxis.timezone` and `interval` set, it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"); week and month buckets span days, so "Jun 1, 2026", "Jun 2026". An explicit `labelFormatter` still wins.
+- `labelRenderer(entry)` overrides how each row's label renders (default: the series label). Use it for richer labels such as breakdown-value pills. Rows share one grid (swatch, label, value), so a renderer that pushes part of its label right lines up as a column down the tooltip.
+- `showHeader` (default true) toggles the header row. Pass false where there is no meaningful header (pie slices, aggregated single-column bars).
+- `showTotal` appends a row summing the visible series. It excludes `overlay` series (goal lines) and series with `visibility.total: false` (a percentage column beside counts; the row itself still renders), and is suppressed when fewer than two summable series remain. `totalFormatter` defaults to `valueFormatter` applied with the first summable row's entry; `totalLabel` defaults to `'Total'`.
+- `sortedByValue` sorts rows by value descending.
+- `hideZeroRows` drops rows whose value is exactly `0` (lifecycle statuses absent for a period).
+- `onRowClick(entry)` makes each row clickable. The tooltip must be pinned for clicks to land. Use it for a per-series drill-down (the persons modal).
+- `footer` renders arbitrary content below all rows, after a divider. Useful for "click to inspect" hints.
+
+Pinned tooltips are copy-friendly.
+Outside dismissal keys off where the press started (pointer-down outside the tooltip or chart, or Escape), so a text-selection drag that releases outside the tooltip does not dismiss it, and a click that completes a selection inside a row does not fire `onRowClick`.
+
+## Custom tooltip pieces
+
+A render prop that is not a list of series rows composes the exported pieces so it keeps the built-in look:
+
+- `TooltipSurface` is the floating panel.
+- `TooltipSwatch` is the series-color dot.
+- `TooltipFooter` is the divider plus muted row, the same slot `DefaultTooltip.footer` renders into.
+
+## Reading `TooltipContext`
+
+- `seriesData` holds one entry per visible series at `dataIndex`, in declaration order. Series with `visibility.tooltip: false` are absent. Look rows up by `entry.series.key`, not by position.
+- `BarChart` sets `hoveredSeriesKey`: the bar or segment under the cursor (stacked: the visible segment; grouped: the band-slot hit). A tooltip that describes a single segment (a funnel breakdown) must select by it, not by `seriesData[0]`. It may reference a series hidden from `seriesData` via `visibility.tooltip: false` (a drop-off filler), and is `undefined` on other chart types and on pinned rebuilds without a cursor.
+- Grouped layouts also set `inTrackArea`: `true` when the cursor is in the hovered bar's band slot but beyond its filled extent. It is measured on the same laid-out rects as click routing (`minBarSize` flooring included), so a tooltip's converted or drop-off framing always matches what a click at that position resolves to.
+- In percent layouts, `value` is a 0..1 fraction.
+- `onUnpin` is present only while pinned. Call it before opening a modal from a row click.
+
+## Touch
+
+Cartesian charts are tap-driven on touch devices.
+A tap on a data point reveals its tooltip, pinned when `config.tooltip.pinnable`, so its rows are tappable for `onRowClick` drill-downs.
+A tap on a different point moves it there.
+A tap on the point whose tooltip is already showing runs the click action: dismiss a pinned tooltip, or fire `onPointClick` on non-pinnable charts.
+Tapping outside the chart, scrolling, or Escape dismisses.
+Mouse hover and click behavior is unchanged; the split lives in `useChartInteraction`, keyed off the pointerdown's `pointerType`.
+
+## Testing
+
+For a chart mounted through `renderHogChart`, `chart.waitForTooltip()` returns a structured `TooltipSnapshot`.
+For a chart rendered anywhere else (a product scene), read the tooltip from the DOM: `getHogChartTooltip()` and `waitForHogChartTooltip()` return the portal element, and `createHogChartTooltip(el)` wraps it as `{ element, isPinned }`.
+`createDefaultTooltipAccessor(el)` reads a rendered `DefaultTooltip` through its `data-attr="hog-chart-tooltip-*"` hooks: `label()`, `rows()`, `value(seriesLabel)`, `swatchColors()`, `total()`.
+Those attributes are a testing contract; keep the accessor and the component in sync.
+All helpers come from `@posthog/quill-charts/testing`.