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(hog-charts): only highlight bar under cursor (#58160)

Sam Pennington940ee1e57bd3
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 2382f3eb619b..d03e6c6d6aff 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
@@ -1,8 +1,9 @@
-import { waitFor } from '@testing-library/react'
+import { fireEvent, waitFor } from '@testing-library/react'
import type { BarChartConfig, ChartTheme, Series } from '../../core/types'
import { ReferenceLine } from '../../overlays/ReferenceLine'
import { renderHogChart } from '../../testing'
+import { dimensions } from '../../testing/jsdom'
import { BarChart } from './BarChart'
const THEME: ChartTheme = {
@@ -206,6 +207,40 @@ describe('BarChart', () => {
expect(tooltip.seriesData.map((s) => s.series.key)).toEqual(expectedKeys)
})
+ it.each<[string, BarChartConfig]>([
+ ['grouped', { barLayout: 'grouped' } as BarChartConfig],
+ ['stacked', { barLayout: 'stacked' } as BarChartConfig],
+ ])('%s layout suppresses tooltip in the gap between band groups', async (_name, config) => {
+ const { chart } = renderHogChart(<BarChart series={SERIES} labels={LABELS} theme={THEME} config={config} />)
+ // d3.scaleBand with paddingInner=0.2 and paddingOuter=0.1 yields step = plotWidth / 3
+ // for 3 labels. Bands occupy [0.1*step, 0.9*step], [1.1*step, 1.9*step], [2.1*step, 2.9*step]
+ // — so x = plotLeft + 1.0*step is centred in the between-group gap.
+ const d3Step = dimensions.plotWidth / LABELS.length
+ fireEvent.mouseMove(chart.element, {
+ clientX: dimensions.plotLeft + d3Step,
+ clientY: dimensions.plotTop + dimensions.plotHeight / 2,
+ })
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ const tooltipEl = document.querySelector('[data-hog-charts-tooltip]') as HTMLElement | null
+ expect(tooltipEl?.textContent ?? '').toBe('')
+ })
+
+ it('grouped layout still narrows when the cursor is above every bar (value-axis miss)', async () => {
+ const { chart } = renderHogChart(
+ <BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ barLayout: 'grouped' }} />
+ )
+ // Same x as `hoverAtIndex(1)` (which lands inside `b`'s sub-band) but a y above
+ // every bar's top. Without the band-axis-only hit-test this would fail per-bar
+ // intersection and fall back to highlighting both `a` and `b`.
+ const step = dimensions.plotWidth / (LABELS.length - 1)
+ fireEvent.mouseMove(chart.element, {
+ clientX: dimensions.plotLeft + step * 1,
+ clientY: dimensions.plotTop + 1,
+ })
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.seriesData.map((s) => s.series.key)).toEqual(['b'])
+ })
+
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 5d449fd96f38..d574e26476e5 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
@@ -251,11 +251,10 @@ function BarChartInner<Meta = unknown>({
return
}
const hoveredLabel = drawLabels[hoverIndex]
- // For grouped, narrow to the bars under the cursor. If the cursor sits in a gap
- // (no hits), fall back to highlighting all — matches the tooltip narrower's
- // gap-fallback so highlight and tooltip don't disagree about what's "active".
+ // Narrow to bars whose band-axis extent contains the cursor; an empty hit set
+ // means the cursor is in a gap, so draw nothing.
let hitKeys: Set<string> | null = null
- if (barLayout === 'grouped' && hoverPosition) {
+ if (hoverPosition) {
const hits = seriesKeysAtCursor({
series: coloredSeries,
label: hoveredLabel,
@@ -267,9 +266,10 @@ function BarChartInner<Meta = unknown>({
stackedData,
topStackedKeyByAxis,
})
- if (hits.size > 0) {
- hitKeys = hits
+ if (hits.size === 0) {
+ return
}
+ hitKeys = hits
}
for (const s of coloredSeries) {
if (s.visibility?.excluded) {
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx
index fb279a3db43e..d01b58e48803 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx
@@ -23,16 +23,21 @@ export function BarTooltip<Meta>({
topStackedKeyByAxis,
layout,
isHorizontal,
-}: BarTooltipProps<Meta>): React.ReactElement {
+}: BarTooltipProps<Meta>): React.ReactElement | null {
const { scales } = useChartLayout()
const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
- const narrowed =
- layout === 'grouped' && d3Scales && ctx.hoverPosition && ctx.dataIndex >= 0
- ? narrowSeriesByCursor(ctx, d3Scales, layout, isHorizontal, stackedData, topStackedKeyByAxis)
- : ctx
- return <>{userTooltip ? userTooltip(narrowed) : DefaultTooltip(narrowed)}</>
+ if (d3Scales && ctx.hoverPosition && ctx.dataIndex >= 0) {
+ const narrowed = narrowSeriesByCursor(ctx, d3Scales, layout, isHorizontal, stackedData, topStackedKeyByAxis)
+ if (!narrowed) {
+ return null
+ }
+ return <>{userTooltip ? userTooltip(narrowed) : DefaultTooltip(narrowed)}</>
+ }
+ return <>{userTooltip ? userTooltip(ctx) : DefaultTooltip(ctx)}</>
}
+/** Returns null when the cursor is in a gap (no bar under it on the band axis) so the
+ * tooltip frame doesn't render around an empty body. */
function narrowSeriesByCursor<Meta>(
ctx: TooltipContext<Meta>,
scales: BarScaleSet,
@@ -40,7 +45,7 @@ function narrowSeriesByCursor<Meta>(
isHorizontal: boolean,
stackedData: Map<string, StackedBand> | undefined,
topStackedKeyByAxis: Map<string, string>
-): TooltipContext<Meta> {
+): TooltipContext<Meta> | null {
const cursor = ctx.hoverPosition
if (!cursor) {
return ctx
@@ -57,7 +62,7 @@ function narrowSeriesByCursor<Meta>(
topStackedKeyByAxis,
})
if (hits.size === 0) {
- return ctx
+ return null
}
return { ...ctx, seriesData: ctx.seriesData.filter((entry) => hits.has(entry.series.key)) }
}
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 a02ef4979080..8be924ecbac0 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
@@ -4,8 +4,18 @@ import type { BarScaleSet, StackedBand } from '../../../core/scales'
import type { Series } from '../../../core/types'
import { DEFAULT_Y_AXIS_ID } from '../../../core/types'
-export function barContainsPoint(bar: BarRect, point: { x: number; y: number }): boolean {
- return point.x >= bar.x && point.x <= bar.x + bar.width && point.y >= bar.y && point.y <= bar.y + bar.height
+/** Grouped-layout hit-test that ignores the value axis so a cursor above (or below) a bar still
+ * selects the bar whose band-slot it lines up with. Matches chart.js's `mode: 'point', axis: 'x'`
+ * behaviour — without this, hovering above a short bar in a grouped pair would fail every
+ * per-bar check, fall back to "highlight all", and visually flag both group-mates at once. */
+export function barContainsPointOnBandAxis(
+ bar: BarRect,
+ point: { x: number; y: number },
+ isHorizontal: boolean
+): boolean {
+ return isHorizontal
+ ? point.y >= bar.y && point.y <= bar.y + bar.height
+ : point.x >= bar.x && point.x <= bar.x + bar.width
}
export interface SeriesKeysAtCursorArgs {
@@ -41,7 +51,7 @@ export function seriesKeysAtCursor(args: SeriesKeysAtCursorArgs): Set<string> {
stackedBand,
isTopOfStack,
})
- if (bar && barContainsPoint(bar, cursor)) {
+ if (bar && barContainsPointOnBandAxis(bar, cursor, isHorizontal)) {
hits.add(s.key)
}
}