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.

fix(charts): tooltip the whole band on sparkline bars (#88001)

Sam Pennington8e44a3b1163b
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 07f3a6993ffd..14e33f1bc553 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -87,7 +87,7 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the
- 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.
-- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, resolveClickToNearestSeries, placement, 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). `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).
+- 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.
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
index 454961273c2c..6e2bad6dea6b 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.test.tsx
@@ -2,7 +2,7 @@ import { fireEvent, waitFor } from '@testing-library/react'
import type { BarChartConfig, ChartTheme, PointClickData, Series } from '../../core/types'
import { ReferenceLine } from '../../overlays/ReferenceLine'
-import { getHogChart, getHogChartTooltip, renderHogChart } from '../../testing'
+import { getHogChart, getHogChartTooltip, renderHogChart, waitForHogChartTooltip } from '../../testing'
import { dimensions } from '../../testing/jsdom'
import { BarChart } from './BarChart'
@@ -421,6 +421,41 @@ describe('BarChart', () => {
await waitFor(() => expect(getHogChartTooltip()?.textContent ?? '').toBe(''))
})
+ const hoverBandCenter = async (hitArea: 'bar' | 'band', index: number): Promise<void> => {
+ const { chart } = renderHogChart(
+ <BarChart
+ series={[{ key: 'v', label: 'V', data: [100, 1, 0] }]}
+ labels={LABELS}
+ theme={THEME}
+ config={{ tooltip: { hitArea } }}
+ />
+ )
+ const bandCenterX = (i: number): number =>
+ dimensions.plotLeft + ((i + 0.5) * dimensions.plotWidth) / LABELS.length
+ const clientY = dimensions.plotTop + 4
+ // The first bar fills the plot, so this hover proves the chart is live.
+ await waitForHogChartTooltip(3000, () =>
+ fireEvent.mouseMove(chart.element, { clientX: bandCenterX(0), clientY })
+ )
+ fireEvent.mouseMove(chart.element, { clientX: bandCenterX(index), clientY })
+ }
+
+ it.each<[string, number, string]>([
+ ['a bar one unit tall', 1, 'Tue'],
+ ['an empty bucket', 2, 'Wed'],
+ ])('band hit-testing reaches %s', async (_name, index, expectedLabel) => {
+ await hoverBandCenter('band', index)
+ await waitFor(() => expect(getHogChartTooltip()?.textContent ?? '').toContain(expectedLabel))
+ })
+
+ it.each<[string, number]>([
+ ['a bar one unit tall', 1],
+ ['an empty bucket', 2],
+ ])('bar hit-testing leaves %s unreachable', async (_name, index) => {
+ await hoverBandCenter('bar', index)
+ await waitFor(() => expect(getHogChartTooltip()?.textContent ?? '').toBe(''))
+ })
+
describe('sparse-stacked horizontal (overlap layout)', () => {
// Mirrors `buildTrendsBarAggregatedSeries`: each series has one non-zero value at
// its own dataIndex, every label is the same band. Smallest bar paints on top, so
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
index 16e7027a84dd..099b4cf13302 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarTooltip.tsx
@@ -36,6 +36,7 @@ export function BarTooltip<Meta>({
tooltipConfig,
}: BarTooltipProps<Meta>): React.ReactElement | null {
const { scales, labels } = useChartLayout()
+ const { hitArea = 'bar', ...defaultTooltipConfig } = tooltipConfig ?? {}
const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
if (d3Scales && ctx.hoverPosition && ctx.dataIndex >= 0) {
const narrowed = narrowSeriesByCursor(
@@ -46,14 +47,15 @@ export function BarTooltip<Meta>({
stackedData,
topStackedKeyByAxis,
labels,
- allSeries
+ allSeries,
+ hitArea
)
if (!narrowed) {
return null
}
- return <>{userTooltip ? userTooltip(narrowed) : <DefaultTooltip {...narrowed} {...tooltipConfig} />}</>
+ return <>{userTooltip ? userTooltip(narrowed) : <DefaultTooltip {...narrowed} {...defaultTooltipConfig} />}</>
}
- return <>{userTooltip ? userTooltip(ctx) : <DefaultTooltip {...ctx} {...tooltipConfig} />}</>
+ return <>{userTooltip ? userTooltip(ctx) : <DefaultTooltip {...ctx} {...defaultTooltipConfig} />}</>
}
/** Filters seriesData to only the segments hit by the cursor, and (for sparse-stacked overlap)
@@ -66,7 +68,8 @@ function narrowSeriesByCursor<Meta>(
stackedData: Map<string, StackedBand> | undefined,
topStackedKeyByAxis: Map<string, string>,
labels: string[],
- allSeries: Series<Meta>[]
+ allSeries: Series<Meta>[],
+ hitArea: 'bar' | 'band'
): TooltipContext<Meta> | null {
const cursor = ctx.hoverPosition
if (!cursor) {
@@ -101,13 +104,13 @@ function narrowSeriesByCursor<Meta>(
stackedData,
topStackedKeyByAxis,
})
- // No filled segment under the cursor — it's in the empty track past the bar's value
- // extent (e.g. right of the longest horizontal bar). Suppress rather than show a tooltip.
- if (!visible) {
+ // Nothing filled under the cursor, so it sits in the empty track past the bar's value
+ // extent, such as right of the longest horizontal bar.
+ if (!visible && hitArea === 'bar') {
return null
}
- visibleKey = visible.series.key
- visibleDataIndex = visible.dataIndex
+ visibleKey = visible?.series.key ?? null
+ visibleDataIndex = visible?.dataIndex ?? null
}
// Surface the hovered identity so consumer tooltips can single out the segment/bar the
// cursor is actually over — stacked keeps every segment in seriesData, so index 0 is not it.
diff --git a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.test.tsx b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.test.tsx
index aa9ae5b46a84..4381814bee78 100644
--- a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.test.tsx
+++ b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.test.tsx
@@ -62,6 +62,20 @@ describe('Sparkline', () => {
expect(chart.seriesCount).toBe(2)
})
+ it('tooltips a bar the cursor is above, which a bar chart would not', async () => {
+ const { chart } = renderHogChart(
+ <Sparkline
+ type="bar"
+ data={[100, 1, 1, 1]}
+ labels={LABELS}
+ theme={THEME}
+ tooltip={(ctx: TooltipContext) => <DefaultTooltip {...ctx} />}
+ />
+ )
+ const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 2, LABELS.length))
+ expect(tooltip.label()).toBe('Mar')
+ })
+
it('enables the tooltip when a tooltip render prop is supplied', async () => {
const { chart } = renderHogChart(
<Sparkline
diff --git a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
index cd59c442d393..06342cb5d714 100644
--- a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
+++ b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
@@ -102,7 +102,13 @@ function SparklineInner({
() => ({
...BASE_CONFIG,
...(type === 'bar'
- ? { barCornerRadius: 2, margins: BAR_MARGINS, showCrosshair: false }
+ ? {
+ barCornerRadius: 2,
+ margins: BAR_MARGINS,
+ showCrosshair: false,
+ // Sparkline bars can be a pixel tall, or absent at a zero bucket.
+ tooltip: { hitArea: 'band' as const },
+ }
: { showCrosshair: true, margins: LINE_MARGINS }),
...(hasTooltip ? {} : { tooltip: { enabled: false } }),
}),
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index e278843046b6..43e57e8fe4f5 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -394,6 +394,9 @@ export interface TooltipConfig {
totalFormatter?: (value: number) => string
/** Sort series rows by value descending so the highest value appears at the top. */
sortedByValue?: boolean
+ /** Bar charts only. `bar` (the default) tooltips only inside a painted bar. `band` tooltips
+ * anywhere in the hovered band, so a one-pixel bar or a zero bucket still reports its value. */
+ hitArea?: 'bar' | 'band'
}
/** Value-axis domain control (y for vertical/line/area charts, x for horizontal bars). Omit for the