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.

docs(hog-charts): split README/CONTRIBUTING/TESTING by audience (#57952)

Sam Penningtond4d95584eae2
diff --git a/frontend/src/lib/hog-charts/README.md b/frontend/src/lib/hog-charts/README.md
index 5f7204c6ce75..48a799ee64b2 100644
--- a/frontend/src/lib/hog-charts/README.md
+++ b/frontend/src/lib/hog-charts/README.md
@@ -1,82 +1,21 @@
# hog-charts
-PostHog's canvas-based charting library built on D3.
-
-## Layers
-
-| Layer | What goes here |
-| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
-| **Chart types** (`charts/`) | Chart-specific logic — e.g. line vs bar. Provides `createScales` and `draw` to the base Chart. |
-| **Chart base** (`core/`) | Generic chart infrastructure shared by all types — canvas, draw loop, interaction, overlays, context. |
-| **Canvas rendering** (`core/canvas-renderer.ts`) | Stateless pure functions that draw to a canvas. All drawing code goes here. |
-| **Overlays** (`overlays/`) | React DOM components rendered on top of the canvas e.g. annotations |
-
-## Rules
-
-- **No kea, no PostHog imports.** Theme, colors, and data are passed in as
- props.
-- **`ChartScales` must not expose d3 types.** Public interface is
- `x(label) => px`, `y(value) => px`, `yTicks() => number[]`.
-- **Canvas functions are stateless.** Pure functions in `canvas-renderer.ts`, no
- React or side effects.
-- **Overlays use `useChartLayout()` / `useChartHover()` (or `useChart()` for both),
- not props from Chart.** Prefer the granular hooks: `useChartLayout()` doesn't
- re-render on hover, while `useChartHover()` does. Use `useChart()` only when an
- overlay needs both — it re-renders on every mousemove.
-- **Tests go through the accessor.** Chart-level tests use `renderHogChart` plus
- the `HogChart` accessor from `testing/`. The `data-attr` selectors are a
- stable contract. Drive interactions with `hoverAtIndex` / `clickAtIndex` /
- `waitForHogChartTooltip`. Don't mock `canvas-renderer` from chart tests —
- pure logic is tested at the `core/` layer. See [docs/TESTING.md](./docs/TESTING.md).
-
-## Adding a new chart type
-
-```tsx
-import { Chart } from '../core/Chart'
-import type { ChartDrawArgs, ChartScales, CreateScalesFn } from '../core/types'
-
-export function BarChart({ series, labels, config, theme, ...props }: BarChartProps) {
- const createScales: CreateScalesFn = useCallback((coloredSeries, scaleLabels, dimensions) => {
- // Use d3.scaleBand for x-axis instead of scalePoint
- return { x, y, yTicks: () => yScale.ticks() }
- }, [])
-
- const draw = useCallback(({ ctx, dimensions, scales, series, labels, hoverIndex }: ChartDrawArgs) => {
- // Draw bars using canvas-renderer primitives or custom drawing
- }, [])
-
- return (
- <Chart
- series={series}
- labels={labels}
- config={config}
- theme={theme}
- createScales={createScales}
- draw={draw}
- {...props}
- >
- {/* Bar-chart-specific overlays as children */}
- </Chart>
- )
-}
-```
-
-## Public API
+PostHog's canvas-based charting library, used for trends, dashboards, and any
+in-app chart that needs to render thousands of points smoothly. D3 powers the
+scales; the canvas does the drawing; React handles overlays.
```tsx
import { LineChart } from 'lib/hog-charts'
-import type { ChartTheme, LineChartConfig, Series } from 'lib/hog-charts'
-```
+import type { ChartTheme, Series } from 'lib/hog-charts'
-For custom overlays rendered as children, use `useChartLayout()` to read scales,
-dimensions, theme, and resolved values; use `useChartHover()` if the overlay
-reacts to the hovered data point. `useChart()` returns the merged shape and is
-kept for back-compat.
+const SERIES: Series[] = [{ key: 'a', label: 'A', data: [10, 20, 30] }]
+const LABELS = ['Mon', 'Tue', 'Wed']
+const THEME: ChartTheme = { colors: ['#1f77b4'], backgroundColor: '#ffffff' }
-For custom tooltip content, pass a component to the `tooltip` prop. It receives
-`TooltipContext` as props. Omit to use the built-in `DefaultTooltip`.
+;<LineChart series={SERIES} labels={LABELS} theme={THEME} />
+```
-### Series role and visibility
+## Series
- `series.overlay` (default `false`): marks an auxiliary series derived from
primary data — trend lines and moving averages. Excluded from stack
@@ -85,7 +24,7 @@ For custom tooltip content, pass a component to the `tooltip` prop. It receives
non-negative. (CI bands are not overlays — they represent real data
uncertainty whose range should still influence the axis.)
-The `series.visibility` object controls where a series appears:
+`series.visibility` controls where a series appears:
- `excluded` (default `false`): fully excludes the series — no rendering, no
scale contribution, no tooltip row, no hit-testing.
@@ -94,3 +33,48 @@ The `series.visibility` object controls where a series appears:
`TooltipContext.seriesData` so it doesn't appear as a tooltip row.
- `valueLabel` (default `true`): when `false`, the `ValueLabels` overlay
skips this series.
+
+## Custom tooltip
+
+Pass a render prop to `tooltip`. It receives `TooltipContext` — `seriesData`,
+`label`, `dataIndex`, `position`, etc. Omit to use the built-in
+`DefaultTooltip`.
+
+```tsx
+<LineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ tooltip={(ctx) => <MyTooltip label={ctx.label} rows={ctx.seriesData} />}
+/>
+```
+
+## Custom overlays
+
+Render any React component as a child of the chart and read layout / hover
+state through hooks:
+
+- `useChartLayout()` — scales, dimensions, theme, resolved values. Doesn't
+ re-render on hover.
+- `useChartHover()` — hovered data point. Re-renders on every mousemove.
+- `useChart()` — both, kept for back-compat. Use the granular hooks above
+ unless you genuinely need both shapes.
+
+```tsx
+function GoalLine() {
+ const { scales } = useChartLayout()
+ const y = scales.y(100)
+ return <div style={{ position: 'absolute', top: y, left: 0, right: 0, borderTop: '1px dashed' }} />
+}
+
+;<LineChart series={SERIES} labels={LABELS} theme={THEME}>
+ <GoalLine />
+</LineChart>
+```
+
+## More
+
+- 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/frontend/src/lib/hog-charts/docs/CONTRIBUTING.md b/frontend/src/lib/hog-charts/docs/CONTRIBUTING.md
new file mode 100644
index 000000000000..4aef732338cd
--- /dev/null
+++ b/frontend/src/lib/hog-charts/docs/CONTRIBUTING.md
@@ -0,0 +1,72 @@
+# Contributing to hog-charts
+
+For people working on the library itself — adding a chart type, adjusting the
+draw loop, extending overlays. If you're embedding a chart in product code,
+read the [README](../README.md) instead.
+
+## Layers
+
+| Layer | What goes here |
+| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
+| **Chart types** (`charts/`) | Chart-specific logic — e.g. line vs bar. Provides `createScales` and `draw` to the base Chart. |
+| **Chart base** (`core/`) | Generic chart infrastructure shared by all types — canvas, draw loop, interaction, overlays, context. |
+| **Canvas rendering** (`core/canvas-renderer.ts`) | Stateless pure functions that draw to a canvas. All drawing code goes here. |
+| **Overlays** (`overlays/`) | React DOM components rendered on top of the canvas, e.g. annotations, value labels, reference lines. |
+
+Where new code goes:
+
+- Pure geometry (scales, layouts) → `core/scales.ts`, `core/bar-layout.ts`,
+ or a sibling. Test these directly under `core/`.
+- Drawing primitives → `core/canvas-renderer.ts`. Stateless, no React.
+- Chart-type React → `charts/<name>/<Name>.tsx`.
+- DOM overlays → `overlays/<Name>.tsx`. Read context via `useChartLayout()`
+ / `useChartHover()`.
+
+## Conventions
+
+- **No kea, no PostHog imports.** Theme, colors, and data are passed in as
+ props. The library has no app dependencies — it's used by trends but
+ shouldn't know about them.
+- **`ChartScales` must not expose d3 types.** Public interface is
+ `x(label) => px`, `y(value) => px`, `yTicks() => number[]`. d3 stays
+ inside the chart-type's `createScales`.
+- **Canvas functions are stateless.** Pure functions in `canvas-renderer.ts`,
+ no React or side effects. State lives in React; drawing reads it.
+- **Overlays use the granular hooks.** `useChartLayout()` doesn't re-render
+ on hover; `useChartHover()` does. Use `useChart()` only when an overlay
+ genuinely needs both — it re-renders on every mousemove.
+- **Pure logic is tested at the `core/` layer.** Chart-level tests assert on
+ the rendered DOM through the `HogChart` accessor — see
+ [TESTING.md](./TESTING.md).
+
+## Adding a new chart type
+
+```tsx
+import { Chart } from '../core/Chart'
+import type { ChartDrawArgs, ChartScales, CreateScalesFn } from '../core/types'
+
+export function BarChart({ series, labels, config, theme, ...props }: BarChartProps) {
+ const createScales: CreateScalesFn = useCallback((coloredSeries, scaleLabels, dimensions) => {
+ // Use d3.scaleBand for x-axis instead of scalePoint
+ return { x, y, yTicks: () => yScale.ticks() }
+ }, [])
+
+ const draw = useCallback(({ ctx, dimensions, scales, series, labels, hoverIndex }: ChartDrawArgs) => {
+ // Draw bars using canvas-renderer primitives or custom drawing
+ }, [])
+
+ return (
+ <Chart
+ series={series}
+ labels={labels}
+ config={config}
+ theme={theme}
+ createScales={createScales}
+ draw={draw}
+ {...props}
+ >
+ {/* Bar-chart-specific overlays as children */}
+ </Chart>
+ )
+}
+```
diff --git a/frontend/src/lib/hog-charts/docs/TESTING.md b/frontend/src/lib/hog-charts/docs/TESTING.md
index cb7826d1ccfb..98b14727daaf 100644
--- a/frontend/src/lib/hog-charts/docs/TESTING.md
+++ b/frontend/src/lib/hog-charts/docs/TESTING.md
@@ -1,69 +1,81 @@
# Testing
-Render a chart, read the DOM through the `chart` accessor, drive interactions through `hoverAtIndex` / `clickAtIndex` and the tooltip helpers. Never reach into the canvas or `scales._private`. Pure logic is tested at the `core/` layer, not at the chart level.
+Two audiences:
-This file documents the conventions encoded in the `testing/` module. They apply to chart-level tests under `charts/` and to overlay tests under `overlays/`.
+- **Embedding hog-charts** in your own component or page and writing tests
+ for that surrounding code → [Testing code that uses hog-charts](#testing-code-that-uses-hog-charts).
+- **Working on the library itself** — chart types, overlays, the draw
+ loop → [Testing the library itself](#testing-the-library-itself).
-## The DOM is the testing contract
+The contract both sections rely on: the `data-attr` selectors and the
+`HogChart` accessor are stable. Renaming a `data-attr` is a breaking
+change — it breaks consumers' tests as much as renaming an exported type.
+JSdom's canvas is a stub, so canvas pixels aren't a viable test surface
+anyway — assertions go through the DOM.
-`data-attr` selectors and the `HogChart` accessor are the stable surface chart-level tests assert against. Renaming a `data-attr` is a breaking change — it breaks consumers' tests as much as renaming an exported type. JSdom's canvas is a stub (`getContext('2d')` returns a no-op context), so canvas pixels aren't a viable test surface anyway — assertions go through the DOM.
+## Testing code that uses hog-charts
-## Testing module API
-
-### `renderHogChart`
-
-Wraps `@testing-library/react`'s `render` and attaches a `chart` accessor. Throws if no hog-charts canvas mounted — use plain `render` for non-chart components.
+You've rendered a tree that contains a chart somewhere — a dashboard, an
+insight scene, a custom panel. Use your own `render` (or RTL wrappers like
+kea-test-utils) and read the chart with `getHogChart(scope)`:
```tsx
-const { chart, container } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)
-expect(chart.seriesCount).toBe(SERIES.length)
-```
+import { render } from '@testing-library/react'
+import { ensureJsdom, getHogChart, hoverAtIndex, waitForHogChartTooltip } from 'lib/hog-charts/testing'
-### The `HogChart` accessor
+ensureJsdom()
-Reads what the chart rendered without poking at internals or canvas pixels. Helpers below take a `wrapper` argument — that's `chart.element`.
-
-```tsx
-const { chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)
+it('renders the goal line on the dashboard chart', async () => {
+ const { container } = render(<Dashboard />)
+ const chart = getHogChart(container)
-chart.element // wrapper div for this chart
-chart.seriesCount // number of non-excluded series rendered
-chart.yTicks() // ['0', '10', '20', …]
-chart.yRightTicks() // right-axis ticks for multi-axis charts
-chart.xTicks() // post-collision-avoidance x ticks
-chart.hasRightAxis // boolean
+ expect(chart.referenceLines()).toHaveLength(1)
+ expect(chart.yTicks()).toContain('0')
-chart.referenceLines() // [{ label: 'Target', position: 142, color: 'rgb(...)', orientation: 'horizontal' }, …]
-chart.valueLabels() // [{ text: '50%', color: 'rgb(...)' }, …]
-chart.annotationBadges() // HTMLElement[]
+ hoverAtIndex(chart.element, 1, LABELS.length)
+ const tooltip = await waitForHogChartTooltip()
+ expect(tooltip.textContent).toContain('Tue')
+})
```
-### Interaction helpers
+`ensureJsdom()` installs the jsdom mocks (`ResizeObserver`,
+`getBoundingClientRect`) and a synchronous `requestAnimationFrame` shim.
+It's idempotent — call it once at the top of a file and forget about it.
-Map a label index to canvas coordinates and fire the right event. `clickAtIndex` is hover-then-click — the chart's click handler reads live tooltip context to choose between pinning and `onPointClick`, so a bare `fireEvent.click` without a prior hover takes the wrong branch.
+The accessor surface (full list in `testing/accessor.ts`):
-```tsx
-chart.hoverAtIndex(1) // mouseMove over labels[1]
-await chart.clickAtIndex(1) // hover then click
+```ts
+chart.element // wrapper div for the chart
+chart.seriesCount // visible series count, from the canvas's aria-label
+chart.yTicks() // ['0', '20', '40', …]
+chart.yRightTicks() // right-axis ticks (multi-axis charts)
+chart.xTicks() // post-collision-avoidance x ticks
+chart.hasRightAxis // boolean
+chart.referenceLines() // [{ label, position, color, orientation }, …]
+chart.valueLabels() // [{ text, color }, …]
+chart.anomalyPoints() // [{ element, color }, …] (TimeSeriesLineChart)
+chart.annotationBadges() // HTMLElement[]
```
-The label count comes from `ui.props.labels`, captured at `renderHogChart` time. Outside `renderHogChart` (e.g. when calling `getHogChart(scope)` on a custom render tree), use the module-level `hoverAtIndex(wrapper, i, totalLabels)` / `clickAtIndex(wrapper, i, totalLabels)` instead.
+For interactions, use the module-level helpers:
-### Tooltip helpers
+- `hoverAtIndex(wrapper, i, totalLabels)` — `mouseMove` over labels[i].
+- `clickAtIndex(wrapper, i, totalLabels)` — hover-then-click. Resolves
+ after the click handler runs.
+- `waitForHogChartTooltip()` — resolves with the rendered tooltip element
+ once it mounts in the `FloatingPortal`.
-`chart.waitForTooltip()` resolves once the tooltip mounts and returns a snapshot — the structured `TooltipContext` the chart computed plus the rendered portal element and an `isPinned` flag.
-
-```tsx
-const tooltip = await chart.waitForTooltip()
-expect(tooltip.label).toBe('Tue')
-expect(tooltip.seriesData).toHaveLength(2)
-expect(tooltip.element.textContent).toContain('Tue')
-expect(tooltip.isPinned).toBe(false)
-```
+`chart.hoverAtIndex(i)` and `chart.waitForTooltip()` (returning a
+structured `TooltipSnapshot` with `seriesData`, `isPinned`, etc.) need
+`renderHogChart` — they read label count and the captured `TooltipContext`
+that only the library's own render wrapper sets up. For most consumer
+tests, DOM assertions through the accessor are enough.
-The tooltip mounts in a `FloatingPortal` on the document root, so it isn't inside `chart.element`. Module-level `waitForHogChartTooltip()` / `getHogChartTooltip()` are still exported for cases where you don't have a `chart` accessor handy (e.g. an insight tree behind kea wrappers — see `frontend/src/test/insight-testing/`).
+## Testing the library itself
-## Boilerplate
+Chart-level tests live under `charts/<name>/<Name>.test.tsx` and overlay
+tests under `overlays/<Name>.test.tsx`. They render the chart at the top
+level via `renderHogChart` and assert through the `chart` accessor.
```tsx
import type { ChartTheme, Series } from '../core/types'
@@ -84,11 +96,31 @@ describe('LineChart', () => {
})
```
-`renderHogChart` installs the jsdom mocks (`ResizeObserver`, `getBoundingClientRect`) and a synchronous `requestAnimationFrame` shim on first call — without them the chart sees 0×0 and the static-layer draw doesn't flush before assertions. It also calls `cleanup()` and removes any leftover tooltip portal, so test files don't need a `beforeEach`/`afterEach` for those. Use the explicit `setupJsdom()` / `setupSyncRaf()` only when you need fine-grained teardown control.
+`renderHogChart` is `render` plus three things consumers don't need:
+auto-`ensureJsdom`, tooltip-context capture (so `chart.waitForTooltip()`
+returns the structured `TooltipContext`), and a cached `labels.length`
+(so `chart.hoverAtIndex(i)` doesn't take a `totalLabels` argument).
+
+### Interactions and tooltip context
+
+```tsx
+chart.hoverAtIndex(1)
+await chart.clickAtIndex(1)
+
+const tooltip = await chart.waitForTooltip()
+tooltip.label // 'Tue'
+tooltip.dataIndex // 1
+tooltip.seriesData // [{ series, value, color }, …] — same shape the tooltip render prop receives
+tooltip.element // rendered portal element
+tooltip.isPinned // true once the user has pinned via click
+```
+
+Prefer the structured fields. Reach for `tooltip.element.textContent` only
+when the test specifically asserts what the user sees rendered.
-## Recipes
+### Recipes
-### Hover and pin a tooltip
+#### Pin a tooltip on click
```tsx
it('pins the tooltip on click when pinnable', async () => {
@@ -102,25 +134,7 @@ it('pins the tooltip on click when pinnable', async () => {
})
```
-### Assert against the structured tooltip context
-
-The `chart.waitForTooltip()` snapshot includes the same `TooltipContext` the chart's `tooltip` render prop would receive — read `seriesData`, `label`, `dataIndex`, etc. directly without round-tripping through DOM.
-
-```tsx
-it('passes hovered seriesData to the tooltip', async () => {
- const { chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)
-
- chart.hoverAtIndex(1)
- const tooltip = await chart.waitForTooltip()
- expect(tooltip.seriesData.map((s) => s.value)).toEqual([2])
-})
-```
-
-When the test cares about what the user actually sees rendered, reach for `tooltip.element.textContent`.
-
-### Click a data point
-
-Use `chart.clickAtIndex` to fire a click on a specific column and assert that the chart's `onPointClick` callback received the expected `PointClickData` (`seriesIndex`, `dataIndex`, `series`, `value`, `label`, `crossSeriesData`). It resolves after the click handler runs.
+#### Click a data point
```tsx
it('invokes onPointClick with the clicked column', async () => {
@@ -134,9 +148,7 @@ it('invokes onPointClick with the clicked column', async () => {
})
```
-### Render a second y-axis
-
-When a series declares `yAxisId: 'right'`, the chart renders a right-side y-axis. Assert through the accessor's `hasRightAxis` and `yRightTicks()`.
+#### Render a second y-axis
```tsx
it('renders a right axis when a series opts in', () => {
@@ -151,9 +163,12 @@ it('renders a right axis when a series opts in', () => {
})
```
-### Catch a render error
+#### Catch a render error
-Each chart wraps its inner tree in `ChartErrorBoundary`, which surfaces render errors through the `onError` prop instead of unmounting the parent. To trigger one, force a throw during render — the simplest forcing function is a `tooltip` render prop that throws, since the boundary covers tooltip rendering during hover.
+Each chart wraps its inner tree in `ChartErrorBoundary`, which surfaces
+render errors through `onError` instead of unmounting the parent. The
+simplest forcing function is a `tooltip` render prop that throws, since
+the boundary covers tooltip rendering during hover.
```tsx
it('reports render errors through onError', () => {
@@ -170,24 +185,28 @@ it('reports render errors through onError', () => {
})
```
-## Anti-patterns
-
-**Don't mock `core/canvas-renderer`.** Reaching into draw-function call lists tests an internal contract through a side channel:
-
-```tsx
-// wrong
-jest.mock('../core/canvas-renderer', () => ({ ...jest.requireActual('../core/canvas-renderer'), drawBars: jest.fn() }))
-expect((drawBars as jest.Mock).mock.calls[0][2][0].corners.topLeft).toBe(true)
-```
+### Anti-patterns
-The geometry that produced those calls lives in `core/bar-layout.ts` — test it directly in `core/bar-layout.test.ts` against `computeSeriesBars`.
+**Don't mock `core/canvas-renderer`.** Reaching into draw-function call
+lists tests an internal contract through a side channel. The geometry
+that produced those calls lives in `core/bar-layout.ts` — test it
+directly in `core/bar-layout.test.ts` against `computeSeriesBars`.
-**Don't read `scales._private`.** It's an opaque chart-type-private slot. Anything reachable through it is reachable more cleanly at the chart type's pure-scale layer.
+**Don't read `scales._private`.** It's an opaque chart-type-private slot.
+Anything reachable through it is reachable more cleanly at the chart
+type's pure-scale layer.
-**Don't inspect canvas pixels.** No `getContext('2d')` spies, no pixel snapshots — JSdom's canvas is a stub anyway.
+**Don't inspect canvas pixels.** No `getContext('2d')` spies, no pixel
+snapshots — JSdom's canvas is a stub anyway.
-**Don't fall back to `container.querySelector('canvas')` for canvas presence.** `renderHogChart` already throws when the canvas is missing.
+**Don't fall back to `container.querySelector('canvas')` for canvas
+presence.** `renderHogChart` already throws when the canvas is missing.
-**Don't write `it.each` matrices that only assert "a canvas rendered".** Each row should read at least one observable property of that permutation — `chart.yTicks().some(t => t.endsWith('%'))` for a percent layout, `chart.hasRightAxis` for a multi-axis case.
+**Don't write `it.each` matrices that only assert "a canvas rendered".**
+Each row should read at least one observable property of that
+permutation — `chart.yTicks().some(t => t.endsWith('%'))` for percent
+layout, `chart.hasRightAxis` for a multi-axis case.
-**Don't reach into React internals.** `useRef` values, internal effects, and d3 scale objects are not test surface. The accessor and tooltip helpers are the entire surface.
+**Don't reach into React internals.** `useRef` values, internal effects,
+and d3 scale objects are not test surface. The accessor and tooltip
+helpers are the entire surface.