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(insights): correct hog-charts bar hover shading and grouped click routing (#60707)

Sam Pennington693a53dc21f2
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
index 4db189d15333..1bded1743b9a 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
@@ -455,6 +455,40 @@ describe('BarChart', () => {
expect(tooltip.seriesData.map((s) => s.series.key)).toEqual(['b'])
})
+ // Regression: grouped clicks always resolved to the first series, so a breakdown
+ // funnel opened the persons modal for breakdown 0 regardless of the bar clicked.
+ // The cursor is in the track *above* every bar (y near the plot top), so only the
+ // band-axis (column) hit-test can route it — full-rect containment would miss and
+ // fall back to the first series. This mirrors clicking the track over a short bar.
+ it.each<[string, number, string, number]>([
+ ['left sub-bar (a)', 1.3, 'a', 20],
+ ['right sub-bar (b)', 1.65, 'b', 15],
+ ])(
+ 'grouped onPointClick routes to the sub-bar column under the cursor, even above the bar — %s',
+ async (_name, stepMultiplier, key, value) => {
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <BarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ barLayout: 'grouped' }}
+ onPointClick={onPointClick}
+ />
+ )
+ const step = dimensions.plotWidth / LABELS.length
+ fireEvent.mouseMove(chart.element, {
+ clientX: dimensions.plotLeft + step * stepMultiplier,
+ clientY: dimensions.plotTop + 2,
+ })
+ fireEvent.click(chart.element)
+ const click: PointClickData = onPointClick.mock.calls[0][0]
+ expect(click.dataIndex).toBe(1)
+ expect(click.series.key).toBe(key)
+ expect(click.value).toBe(value)
+ }
+ )
+
it('pins the tooltip on click when tooltip.pinnable is true', async () => {
const { chart } = renderHogChart(
<BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ tooltip: { pinnable: true } }} />
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
index f3a15429023e..2820ac1a5589 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
@@ -493,8 +493,8 @@ function BarChartInner<Meta = unknown>({
const seriesRef = useLatest(series)
const labelsRef = useLatest(labels)
- // Stacked/percent segments share a band slot — rewrite the click payload to the
- // segment under the cursor so drop-off fillers and per-breakdown segments route correctly.
+ // Bars sharing a band slot — rewrite the click payload to the series actually under the
+ // cursor so drop-off fillers and per-breakdown segments route correctly.
const wrapClickData = useCallback(
(clickData: PointClickData<Meta>, scales: ChartScales): PointClickData<Meta> => {
const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
@@ -502,7 +502,7 @@ function BarChartInner<Meta = unknown>({
return clickData
}
return (
- resolveClickedStackedSegment({
+ resolveClickedBarSeries({
clickData,
d3Scales,
barLayout,
@@ -556,11 +556,15 @@ function BarChartInner<Meta = unknown>({
)
}
-/** Pure helper extracted so the click-rewrite is unit-testable and the component-level
- * callback has no logic of its own — it just plumbs in scales + refs. Returns `null`
- * when nothing in the layout/cursor configuration warrants rewriting, signalling the
- * caller to pass the original `clickData` through unchanged. */
-export function resolveClickedStackedSegment<Meta>({
+/** Rewrites the click payload to the bar series actually under the cursor. The base payload
+ * always points at the first series in the band; this picks the right one per layout:
+ * - grouped: the series whose sub-band column the cursor is over — band axis only, so a
+ * click above a short bar (or on its track) still resolves to that column.
+ * - stacked/percent: the segment whose rect contains the cursor on the value axis, walking
+ * every dataIndex in the band so sparse-overlap segments route correctly, and re-reading
+ * the value at that segment's own dataIndex.
+ * Pure so the routing is unit-testable; returns `null` to pass `clickData` through unchanged. */
+export function resolveClickedBarSeries<Meta>({
clickData,
d3Scales,
barLayout,
@@ -579,15 +583,37 @@ export function resolveClickedStackedSegment<Meta>({
series: Series<Meta>[]
labels: readonly string[]
}): PointClickData<Meta> | null {
- if (!isStackedLayout(barLayout)) {
+ const { cursor, label, dataIndex, crossSeriesData } = clickData
+ if (!cursor) {
return null
}
- const { cursor, label, crossSeriesData } = clickData
- if (!cursor) {
+ const rewrite = (hitSeries: Series<Meta>, value: number, hitDataIndex: number): PointClickData<Meta> => ({
+ ...clickData,
+ dataIndex: hitDataIndex,
+ series: hitSeries,
+ value,
+ seriesIndex: series.findIndex((s) => s.key === hitSeries.key),
+ })
+
+ if (barLayout === 'grouped') {
+ for (const { series: s, bar } of iterBarsAtCursor({
+ series: crossSeriesData.map((d) => d.series),
+ label,
+ dataIndex,
+ scales: d3Scales,
+ layout: barLayout,
+ isHorizontal,
+ topStackedKeyByAxis,
+ })) {
+ if (!barContainsPointOnBandAxis(bar, cursor, isHorizontal)) {
+ continue
+ }
+ const hit = crossSeriesData.find((d) => d.series.key === s.key)
+ return hit ? rewrite(hit.series, hit.value, dataIndex) : null
+ }
return null
}
- // Walk every dataIndex that maps to the clicked band — for sparse-stacked overlap the
- // visible segment lives at a different dataIndex than `clickData.dataIndex` (the band).
+
const visible = findVisibleStackedSegment({
series: crossSeriesData.map((d) => d.series),
labels,
@@ -610,11 +636,5 @@ export function resolveClickedStackedSegment<Meta>({
// band's dataIndex, which is a sparse-zero cell for the visible series.
const raw = hit.series.data[visible.dataIndex]
const resolvedValue = typeof raw === 'number' && Number.isFinite(raw) ? raw : hit.value
- return {
- ...clickData,
- dataIndex: visible.dataIndex,
- series: hit.series,
- value: resolvedValue,
- seriesIndex: series.findIndex((s) => s.key === hit.series.key),
- }
+ return rewrite(hit.series, resolvedValue, visible.dataIndex)
}
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.test.ts b/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.test.ts
index 8d7ed1363f79..f192602032b5 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.test.ts
+++ b/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.test.ts
@@ -1,5 +1,13 @@
import type { BarRect } from '../../../core/canvas-renderer'
-import { barContainsPoint, barContainsPointOnBandAxis, cursorOutsideBarFillExtent } from './bars-under-cursor'
+import { computeStackData, createBarScales } from '../../../core/scales'
+import type { Series } from '../../../core/types'
+import { dimensions } from '../../../testing/jsdom'
+import {
+ barContainsPoint,
+ barContainsPointOnBandAxis,
+ cursorOutsideBarFillExtent,
+ findVisibleStackedSegment,
+} from './bars-under-cursor'
const verticalBar: BarRect = { x: 100, y: 120, width: 50, height: 200, corners: {}, dataIndex: 0 }
const horizontalBar: BarRect = { x: 60, y: 100, width: 140, height: 40, corners: {}, dataIndex: 0 }
@@ -90,3 +98,69 @@ describe('barContainsPoint', () => {
})
})
})
+
+describe('findVisibleStackedSegment — overdraw clip', () => {
+ const bandCenterX = (scales: ReturnType<typeof createBarScales>, label: string): number =>
+ (scales.band(label) ?? 0) + scales.band.bandwidth() / 2
+
+ // Genuinely stacked segments are non-overlapping slices, so hovering any segment must
+ // highlight its whole rect — nextSmallerExtent must be 0 even when a sibling is shorter.
+ // Regression: the clip used to subtract the shortest sibling's height, leaving a tall
+ // bottom segment only partly shaded.
+ it('returns nextSmallerExtent 0 for a tall bottom segment with a shorter sibling above', () => {
+ const series: Series[] = [
+ { key: 'bottom', label: 'Bottom', data: [30] },
+ { key: 'top', label: 'Top', data: [10] },
+ ]
+ const labels = ['Mon']
+ const scales = createBarScales(series, labels, dimensions, {
+ barLayout: 'stacked',
+ axisOrientation: 'vertical',
+ })
+ const stackedData = computeStackData(series, labels)
+ const visible = findVisibleStackedSegment({
+ series,
+ labels,
+ hoveredLabel: 'Mon',
+ cursor: { x: bandCenterX(scales, 'Mon'), y: scales.value(15) },
+ scales,
+ layout: 'stacked',
+ isHorizontal: false,
+ stackedData,
+ topStackedKeyByAxis: new Map(),
+ })
+ expect(visible?.series.key).toBe('bottom')
+ expect(visible?.nextSmallerExtent).toBe(0)
+ })
+
+ // Sparse "overlap" layout: each series draws from value 0 in a shared band, smallest on
+ // top. Here the clip MUST subtract the next-smaller baseline-sharing segment so the
+ // highlight doesn't paint over the slice drawn in front of it.
+ it('returns the next-smaller baseline-sharing extent for the overlap layout', () => {
+ const series: Series[] = [
+ { key: 'big', label: 'Big', data: [100, 0] },
+ { key: 'small', label: 'Small', data: [0, 20] },
+ ]
+ const labels = ['band', 'band']
+ const scales = createBarScales(series, labels, dimensions, {
+ barLayout: 'stacked',
+ axisOrientation: 'horizontal',
+ })
+ const stackedData = computeStackData(series, labels)
+ const bandCenterY = (scales.band('band') ?? 0) + scales.band.bandwidth() / 2
+ const visible = findVisibleStackedSegment({
+ series,
+ labels,
+ hoveredLabel: 'band',
+ cursor: { x: scales.value(75), y: bandCenterY },
+ scales,
+ layout: 'stacked',
+ isHorizontal: true,
+ stackedData,
+ topStackedKeyByAxis: new Map(),
+ })
+ const smallWidth = Math.abs(scales.value(20) - scales.value(0))
+ expect(visible?.series.key).toBe('big')
+ expect(visible?.nextSmallerExtent).toBeCloseTo(smallWidth, 5)
+ })
+})
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.ts b/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.ts
index dedd4bc412be..af4539c57165 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.ts
+++ b/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.ts
@@ -119,9 +119,19 @@ export function resolveBarsAtCursor(
return { hits, strictHit }
}
+/** Pixel coordinate of a bar's baseline (value-0) edge — the side the bar grows from. */
+function barBaseline(bar: BarRect, isHorizontal: boolean): number {
+ return isHorizontal ? bar.x : bar.y + bar.height
+}
+
/** Visible stacked segment under the cursor — last-drawn bar whose rect contains it.
* Also returns the next-smaller extent (the far edge of the bar that overdraws this
- * segment's near side); callers clip the highlight rect there so hover preserves z-order. */
+ * segment's near side); callers clip the highlight rect there so hover preserves z-order.
+ *
+ * Overdraw only occurs in the sparse "overlap" layout where sibling segments share a
+ * baseline (each series drawn from value 0, smallest on top). Properly stacked segments
+ * each start where the previous ends, so no sibling shares the hovered segment's baseline
+ * and `nextSmallerExtent` is 0 — the segment's own rect is already the visible slice. */
export function findVisibleStackedSegment<S extends Pick<Series, 'key' | 'visibility' | 'yAxisId' | 'data'>>(
args: Omit<BarsAtCursorArgs, 'series' | 'label' | 'dataIndex'> & {
series: readonly S[]
@@ -131,8 +141,8 @@ export function findVisibleStackedSegment<S extends Pick<Series, 'key' | 'visibi
}
): { series: S; bar: BarRect; dataIndex: number; nextSmallerExtent: number } | null {
const { labels, hoveredLabel, cursor, isHorizontal } = args
- let visible: { series: S; bar: BarRect; dataIndex: number; extent: number } | null = null
- const allExtents: number[] = []
+ let visible: { series: S; bar: BarRect; dataIndex: number; extent: number; baseline: number } | null = null
+ const candidates: { extent: number; baseline: number }[] = []
for (let dataIndex = 0; dataIndex < labels.length; dataIndex++) {
if (labels[dataIndex] !== hoveredLabel) {
continue
@@ -142,17 +152,27 @@ export function findVisibleStackedSegment<S extends Pick<Series, 'key' | 'visibi
if (extent <= 0) {
continue
}
- allExtents.push(extent)
+ const baseline = barBaseline(bar, isHorizontal)
+ candidates.push({ extent, baseline })
if (!barContainsPoint(bar, cursor)) {
continue
}
// Overwrite so the last-drawn (smallest, painted on top) candidate wins.
- visible = { series: s, bar, dataIndex, extent }
+ visible = { series: s, bar, dataIndex, extent, baseline }
}
}
if (!visible) {
return null
}
- const nextSmallerExtent = allExtents.reduce((max, ext) => (ext < visible!.extent && ext > max ? ext : max), 0)
+ // Largest sibling that shares this baseline and is smaller — i.e. overdraws the
+ // segment's near side. Non-overlapping siblings sit on different baselines and are skipped.
+ const BASELINE_EPSILON = 0.5
+ const nextSmallerExtent = candidates.reduce(
+ (max, c) =>
+ Math.abs(c.baseline - visible!.baseline) <= BASELINE_EPSILON && c.extent < visible!.extent && c.extent > max
+ ? c.extent
+ : max,
+ 0
+ )
return { series: visible.series, bar: visible.bar, dataIndex: visible.dataIndex, nextSmallerExtent }
}