: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(hog-charts): per-bar hover & tooltip narrowing for grouped/compare (#57916)
Sam Penningtonb729f91f02ef
diff --git a/frontend/src/lib/hog-charts/charts/BarChart.test.tsx b/frontend/src/lib/hog-charts/charts/BarChart.test.tsxindex 636c1a88706b..c9e3d3631173 100644--- a/frontend/src/lib/hog-charts/charts/BarChart.test.tsx+++ b/frontend/src/lib/hog-charts/charts/BarChart.test.tsx@@ -1,16 +1,8 @@import { cleanup, waitFor } from '@testing-library/react'-import type { ChartTheme, Series, TooltipContext } from '../core/types'+import type { BarChartConfig, ChartTheme, Series } from '../core/types'import { ReferenceLine } from '../overlays/ReferenceLine'-import {- clickAtIndex,- getHogChartTooltip,- hoverAtIndex,- renderHogChart,- setupJsdom,- setupSyncRaf,- waitForHogChartTooltip,-} from '../testing'+import { clickAtIndex, hoverAtIndex, renderHogChart, setupJsdom, setupSyncRaf } from '../testing'import { BarChart } from './BarChart'const THEME: ChartTheme = {@@ -167,8 +159,8 @@ describe('BarChart', () => {it('mounts a tooltip on hover', async () => {const { chart } = renderHogChart(<BarChart series={SERIES} labels={LABELS} theme={THEME} />)hoverAtIndex(chart.element, 1, LABELS.length)- const tooltip = await waitForHogChartTooltip()- expect(tooltip.textContent).toContain('Tue')+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.element.textContent).toContain('Tue')})it('invokes onPointClick with the clicked column', async () => {@@ -180,16 +172,23 @@ describe('BarChart', () => {expect(onPointClick).toHaveBeenCalledWith(expect.objectContaining({ dataIndex: 1, label: 'Tue' }))})- it('passes hovered seriesData to a custom tooltip render prop', async () => {- const tooltip = (ctx: TooltipContext): React.ReactNode => (- <div data-attr="custom-tooltip">{ctx.seriesData.length}</div>- )- const { chart } = renderHogChart(- <BarChart series={SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} />- )+ it.each([+ {+ name: 'stacked layout carries every visible series in the tooltip',+ config: undefined as BarChartConfig | undefined,+ expectedKeys: ['a', 'b'],+ },+ {+ name: 'grouped layout narrows to the bar under the cursor',+ config: { barLayout: 'grouped' } as BarChartConfig,+ // hoverAtIndex puts the cursor at band-center / mid-plot, which lands in `b`'s sub-band.+ expectedKeys: ['b'],+ },+ ])('$name', async ({ config, expectedKeys }) => {+ const { chart } = renderHogChart(<BarChart series={SERIES} labels={LABELS} theme={THEME} config={config} />)hoverAtIndex(chart.element, 1, LABELS.length)- const node = await waitForHogChartTooltip()- expect(node.querySelector('[data-attr="custom-tooltip"]')?.textContent).toBe(String(SERIES.length))+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.seriesData.map((s) => s.series.key)).toEqual(expectedKeys)})it('pins the tooltip on click when tooltip.pinnable is true', async () => {@@ -197,9 +196,10 @@ describe('BarChart', () => {<BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ tooltip: { pinnable: true } }} />)hoverAtIndex(chart.element, 1, LABELS.length)- await waitForHogChartTooltip()+ await chart.waitForTooltip()await clickAtIndex(chart.element, 1, LABELS.length)- expect(getHogChartTooltip()?.classList.contains('hog-charts-tooltip--pinned')).toBe(true)+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.element.classList.contains('hog-charts-tooltip--pinned')).toBe(true)})it('omits a series from tooltip when visibility.tooltip is false', async () => {@@ -209,9 +209,9 @@ describe('BarChart', () => {]const { chart } = renderHogChart(<BarChart series={series} labels={LABELS} theme={THEME} />)hoverAtIndex(chart.element, 1, LABELS.length)- const tooltip = await waitForHogChartTooltip()- expect(tooltip.textContent).toContain('A')- expect(tooltip.textContent).not.toContain('B')+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.element.textContent).toContain('A')+ expect(tooltip.element.textContent).not.toContain('B')})})diff --git a/frontend/src/lib/hog-charts/charts/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart.tsxindex e184f94bee8b..775732396d14 100644--- a/frontend/src/lib/hog-charts/charts/BarChart.tsx+++ b/frontend/src/lib/hog-charts/charts/BarChart.tsx@@ -3,8 +3,10 @@ import React, { useCallback, useMemo } from 'react'import { type BarChartPrivate, computeBarAtIndex, computeSeriesBars } from '../core/bar-layout'import { type BarRect, drawBarHighlight, drawBars, drawGrid, type DrawContext } from '../core/canvas-renderer'import { Chart } from '../core/Chart'+import { useChartLayout } from '../core/chart-context'import { ChartErrorBoundary } from '../core/ChartErrorBoundary'import {+ type BarScaleSet,computePercentStackData,computeStackData,createBarScales,@@ -25,12 +27,57 @@ import type {} from '../core/types'import { DEFAULT_Y_AXIS_ID } from '../core/types'import { computeVisibleXLabels } from '../overlays/AxisLabels'+import { DefaultTooltip } from '../overlays/DefaultTooltip'function bandCenter(scales: BarChartPrivate['__barChart'], label: string): number | undefined {const start = scales.band(label)return start == null ? undefined : start + scales.band.bandwidth() / 2}+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+}++interface BarHitTestArgs {+ series: readonly Pick<Series, 'key' | 'visibility' | 'yAxisId' | 'data'>[]+ label: string+ dataIndex: number+ cursor: { x: number; y: number }+ scales: BarScaleSet+ layout: 'stacked' | 'grouped' | 'percent'+ isHorizontal: boolean+ stackedData?: Map<string, StackedBand>+ topStackedKeyByAxis: Map<string, string>+}++/** Shared by drawHover and the tooltip wrapper so they can't drift. */+function seriesKeysAtCursor(args: BarHitTestArgs): Set<string> {+ const { series, label, dataIndex, cursor, scales, layout, isHorizontal, stackedData, topStackedKeyByAxis } = args+ const hits = new Set<string>()+ for (const s of series) {+ if (s.visibility?.excluded) {+ continue+ }+ const stackedBand = stackedData?.get(s.key)+ const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID+ const isTopOfStack = topStackedKeyByAxis.get(axisId) === s.key+ const bar = computeBarAtIndex({+ series: s as Series,+ label,+ dataIndex,+ scales,+ layout,+ isHorizontal,+ stackedBand,+ isTopOfStack,+ })+ if (bar && barContainsPoint(bar, cursor)) {+ hits.add(s.key)+ }+ }+ return hits+}+export interface BarChartProps<Meta = unknown> {series: Series<Meta>[]labels: string[]@@ -170,8 +217,7 @@ function BarChartInner<Meta = unknown>({}if (showGrid) {- // Square grid: draw cross-axis lines at the same coords as visible category labels- // so the grid aligns with the labels the user sees, not at every band.+ // Align cross-axis grid with visible category labels, not every band.let categoryTicks: number[] = []if (isHorizontal) {for (const label of drawLabels) {@@ -222,19 +268,48 @@ function BarChartInner<Meta = unknown>({)const drawHover = useCallback(- ({ ctx, scales, series: coloredSeries, labels: drawLabels, hoverIndex }: ChartDrawArgs) => {+ ({+ ctx,+ scales,+ series: coloredSeries,+ labels: drawLabels,+ hoverIndex,+ hoverPosition,+ theme,+ }: ChartDrawArgs) => {const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChartif (!d3Scales || hoverIndex < 0) {return}- // Translucent dark overlay layered on top of the static bar — composites with the- // bar pixel underneath to produce the "darker on hover" effect for any series color.- const highlightColor = 'rgba(0, 0, 0, 0.2)'+ const highlightColor = theme.crosshairColor ?? 'rgba(0, 0, 0, 0.2)'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".+ let hitKeys: Set<string> | null = null+ if (barLayout === 'grouped' && hoverPosition) {+ const hits = seriesKeysAtCursor({+ series: coloredSeries,+ label: hoveredLabel,+ dataIndex: hoverIndex,+ cursor: hoverPosition,+ scales: d3Scales,+ layout: barLayout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ })+ if (hits.size > 0) {+ hitKeys = hits+ }+ }for (const s of coloredSeries) {if (s.visibility?.excluded) {continue}+ if (hitKeys && !hitKeys.has(s.key)) {+ continue+ }const stackedBand = stackedData?.get(s.key)const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_IDconst isTop = topStackedKeyByAxis.get(axisId) === s.key@@ -256,6 +331,20 @@ function BarChartInner<Meta = unknown>({[stackedData, barLayout, isHorizontal, topStackedKeyByAxis, barCornerRadius])+ const wrappedTooltip = useCallback(+ (ctx: TooltipContext<Meta>): React.ReactNode => (+ <BarTooltipShell<Meta>+ ctx={ctx}+ userTooltip={tooltip}+ stackedData={stackedData}+ topStackedKeyByAxis={topStackedKeyByAxis}+ layout={barLayout}+ isHorizontal={isHorizontal}+ />+ ),+ [tooltip, stackedData, topStackedKeyByAxis, barLayout, isHorizontal]+ )+const resolveValue = useMemo(() => {if (!stackedData) {return undefined@@ -280,7 +369,7 @@ function BarChartInner<Meta = unknown>({createScales={createScales}drawStatic={drawStatic}drawHover={drawHover}- tooltip={tooltip}+ tooltip={wrappedTooltip}onPointClick={onPointClick}className={className}dataAttr={dataAttr}@@ -290,3 +379,60 @@ function BarChartInner<Meta = unknown>({</Chart>)}++interface BarTooltipShellProps<Meta> {+ ctx: TooltipContext<Meta>+ userTooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode+ stackedData: Map<string, StackedBand> | undefined+ topStackedKeyByAxis: Map<string, string>+ layout: 'stacked' | 'grouped' | 'percent'+ isHorizontal: boolean+}++function BarTooltipShell<Meta>({+ ctx,+ userTooltip,+ stackedData,+ topStackedKeyByAxis,+ layout,+ isHorizontal,+}: BarTooltipShellProps<Meta>): React.ReactElement {+ const { scales } = useChartLayout()+ const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart+ // Stacked/percent: keep all rows so the tooltip mirrors the whole hovered column —+ // matches the legacy chart.js bar tooltip's default `mode: 'nearest'` for stacked bars.+ const narrowed =+ layout === 'grouped' && d3Scales && ctx.hoverPosition && ctx.dataIndex >= 0+ ? narrowSeriesByCursor(ctx, d3Scales, layout, isHorizontal, stackedData, topStackedKeyByAxis)+ : ctx+ return <>{userTooltip ? userTooltip(narrowed) : DefaultTooltip(narrowed)}</>+}++function narrowSeriesByCursor<Meta>(+ ctx: TooltipContext<Meta>,+ scales: BarScaleSet,+ layout: 'stacked' | 'grouped' | 'percent',+ isHorizontal: boolean,+ stackedData: Map<string, StackedBand> | undefined,+ topStackedKeyByAxis: Map<string, string>+): TooltipContext<Meta> {+ const cursor = ctx.hoverPosition+ if (!cursor) {+ return ctx+ }+ const hits = seriesKeysAtCursor({+ series: ctx.seriesData.map((entry) => entry.series),+ label: ctx.label,+ dataIndex: ctx.dataIndex,+ cursor,+ scales,+ layout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ })+ if (hits.size === 0) {+ return ctx+ }+ return { ...ctx, seriesData: ctx.seriesData.filter((entry) => hits.has(entry.series.key)) }+}diff --git a/frontend/src/lib/hog-charts/charts/LineChart.test.tsx b/frontend/src/lib/hog-charts/charts/LineChart.test.tsxindex c463a784ddb9..8891eab90835 100644--- a/frontend/src/lib/hog-charts/charts/LineChart.test.tsx+++ b/frontend/src/lib/hog-charts/charts/LineChart.test.tsx@@ -1,16 +1,8 @@import { cleanup } from '@testing-library/react'-import type { ChartTheme, Series, TooltipContext } from '../core/types'+import type { ChartTheme, Series } from '../core/types'import { ReferenceLine } from '../overlays/ReferenceLine'-import {- clickAtIndex,- getHogChartTooltip,- hoverAtIndex,- renderHogChart,- setupJsdom,- setupSyncRaf,- waitForHogChartTooltip,-} from '../testing'+import { clickAtIndex, hoverAtIndex, renderHogChart, setupJsdom, setupSyncRaf } from '../testing'import { LineChart } from './LineChart'const THEME: ChartTheme = {@@ -150,8 +142,8 @@ describe('LineChart', () => {it('mounts a tooltip on hover', async () => {const { chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)hoverAtIndex(chart.element, 1, LABELS.length)- const tooltip = await waitForHogChartTooltip()- expect(tooltip.textContent).toContain('Tue')+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.element.textContent).toContain('Tue')})it('invokes onPointClick with the clicked column', async () => {@@ -165,16 +157,11 @@ describe('LineChart', () => {)})- it('passes hovered seriesData to a custom tooltip render prop', async () => {- const tooltip = (ctx: TooltipContext): React.ReactNode => (- <div data-attr="custom-tooltip">{ctx.seriesData.length}</div>- )- const { chart } = renderHogChart(- <LineChart series={SERIES} labels={LABELS} theme={THEME} tooltip={tooltip} />- )+ it('passes hovered seriesData to the tooltip render prop', async () => {+ const { chart } = renderHogChart(<LineChart series={SERIES} labels={LABELS} theme={THEME} />)hoverAtIndex(chart.element, 1, LABELS.length)- const node = await waitForHogChartTooltip()- expect(node.querySelector('[data-attr="custom-tooltip"]')?.textContent).toBe(String(SERIES.length))+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.seriesData).toHaveLength(SERIES.length)})it('pins the tooltip on click when tooltip.pinnable is true', async () => {@@ -182,9 +169,10 @@ describe('LineChart', () => {<LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ tooltip: { pinnable: true } }} />)hoverAtIndex(chart.element, 1, LABELS.length)- await waitForHogChartTooltip()+ await chart.waitForTooltip()await clickAtIndex(chart.element, 1, LABELS.length)- expect(getHogChartTooltip()?.classList.contains('hog-charts-tooltip--pinned')).toBe(true)+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.element.classList.contains('hog-charts-tooltip--pinned')).toBe(true)})it('does not crash on hover for overlay series', async () => {@@ -194,8 +182,8 @@ describe('LineChart', () => {]const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)hoverAtIndex(chart.element, 1, LABELS.length)- const tooltip = await waitForHogChartTooltip()- expect(tooltip.textContent).toContain('Tue')+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.element.textContent).toContain('Tue')})it('omits a series from tooltip when visibility.tooltip is false', async () => {@@ -205,9 +193,9 @@ describe('LineChart', () => {]const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)hoverAtIndex(chart.element, 1, LABELS.length)- const tooltip = await waitForHogChartTooltip()- expect(tooltip.textContent).toContain('A')- expect(tooltip.textContent).not.toContain('B')+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.element.textContent).toContain('A')+ expect(tooltip.element.textContent).not.toContain('B')})})diff --git a/frontend/src/lib/hog-charts/core/Chart.tsx b/frontend/src/lib/hog-charts/core/Chart.tsxindex 941f3b1534b6..a74d654c22d4 100644--- a/frontend/src/lib/hog-charts/core/Chart.tsx+++ b/frontend/src/lib/hog-charts/core/Chart.tsx@@ -148,7 +148,7 @@ export function Chart<Meta = unknown>({const { left: resolvedYFormatter, right: resolvedYRightFormatter } = useResolvedYFormatters(scales, yTickFormatter)- const { hoverIndex, tooltipCtx, handlers } = useChartInteraction<Meta>({+ const { hoverIndex, hoverPosition, tooltipCtx, handlers } = useChartInteraction<Meta>({scales,dimensions,labels,@@ -184,6 +184,7 @@ export function Chart<Meta = unknown>({series: coloredSeries,labels,hoverIndex,+ hoverPosition,theme,drawStatic,drawHover: composedDrawHover,diff --git a/frontend/src/lib/hog-charts/core/canvas-renderer.test.ts b/frontend/src/lib/hog-charts/core/canvas-renderer.test.tsindex 534caf6d7e6f..6a51221a54eb 100644--- a/frontend/src/lib/hog-charts/core/canvas-renderer.test.ts+++ b/frontend/src/lib/hog-charts/core/canvas-renderer.test.ts@@ -498,8 +498,6 @@ describe('hog-charts canvas-renderer', () => {})describe('categoryTicks', () => {- // Helper: count strokes whose direction matches the requested axis. A "vertical"- // stroke moves only on y (moveX === lineX); a "horizontal" stroke moves only on x.function countAxisAlignedStrokes(ctx: jest.Mocked<CanvasRenderingContext2D>,axis: 'vertical' | 'horizontal'@@ -544,7 +542,6 @@ describe('hog-charts canvas-renderer', () => {drawGrid(drawCtx, { orientation, categoryTicks: ticks })expect(countAxisAlignedStrokes(ctx, expectedAxis)).toBe(baselineCrossAxis + ticks.length)- // Value-axis strokes should be unaffected by categoryTicks.expect(countAxisAlignedStrokes(ctx, valueAxis)).toBe(countAxisAlignedStrokes(baseline, valueAxis))})@@ -613,6 +610,7 @@ describe('hog-charts canvas-renderer', () => {series: [],labels: ['Mon', 'Tue', 'Wed'],hoverIndex,+ hoverPosition: null,theme: {} as ChartTheme,}}diff --git a/frontend/src/lib/hog-charts/core/canvas-renderer.ts b/frontend/src/lib/hog-charts/core/canvas-renderer.tsindex 0aae2ef3cfbb..3b3204a2cadf 100644--- a/frontend/src/lib/hog-charts/core/canvas-renderer.ts+++ b/frontend/src/lib/hog-charts/core/canvas-renderer.ts@@ -293,10 +293,7 @@ export function drawPoints(drawCtx: DrawContext, series: ResolvedSeries, yValuesexport interface DrawGridOptions {gridColor?: stringorientation?: 'vertical' | 'horizontal'- /** Pixel positions on the categorical axis at which to draw cross-axis grid lines, producing- * a square grid. In `'vertical'` mode these are x-pixel positions (vertical lines); in- * `'horizontal'` mode they are y-pixel positions (horizontal lines). Empty/undefined keeps- * the value-axis-only grid. */+ /** Cross-axis grid line positions (x-pixels in vertical mode, y-pixels in horizontal). */categoryTicks?: number[]}@@ -484,9 +481,7 @@ export function drawBars(}}-/** Hover highlight is a translucent fill on the *overlay* canvas, layered over the static bar.- * The overlay's alpha composites with the bar pixel underneath, darkening it without us- * having to know how to darken every possible color string the consumer passes. */+/** Translucent fill on the overlay canvas, alpha-composited over the static bar. */export function drawBarHighlight(ctx: CanvasRenderingContext2D,bar: BarRect,diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartDraw.ts b/frontend/src/lib/hog-charts/core/hooks/useChartDraw.tsindex c3c345417ab3..cdd7a9d408a8 100644--- a/frontend/src/lib/hog-charts/core/hooks/useChartDraw.ts+++ b/frontend/src/lib/hog-charts/core/hooks/useChartDraw.ts@@ -12,6 +12,7 @@ interface UseChartDrawOptions {series: ResolvedSeries[]labels: string[]hoverIndex: number+ hoverPosition: { x: number; y: number } | nulltheme: ChartThemedrawStatic: (args: ChartDrawArgs) => voiddrawHover: (args: ChartDrawArgs) => void@@ -32,6 +33,7 @@ export function useChartDraw({series,labels,hoverIndex,+ hoverPosition,theme,drawStatic,drawHover,@@ -55,7 +57,7 @@ export function useChartDraw({staticRafRef.current = requestAnimationFrame(() => {staticRafRef.current = nullclearAndPrepare(ctx, dimensions)- drawStatic({ ctx, dimensions, scales, series, labels, hoverIndex: -1, theme })+ drawStatic({ ctx, dimensions, scales, series, labels, hoverIndex: -1, hoverPosition: null, theme })ctx.restore()})return () => {@@ -81,7 +83,7 @@ export function useChartDraw({hoverRafRef.current = requestAnimationFrame(() => {hoverRafRef.current = nullclearAndPrepare(overlayCtx, dimensions)- drawHover({ ctx: overlayCtx, dimensions, scales, series, labels, hoverIndex, theme })+ drawHover({ ctx: overlayCtx, dimensions, scales, series, labels, hoverIndex, hoverPosition, theme })overlayCtx.restore()})return () => {@@ -90,5 +92,5 @@ export function useChartDraw({hoverRafRef.current = null}}- }, [overlayCtx, dimensions, scales, series, labels, hoverIndex, theme, drawHover])+ }, [overlayCtx, dimensions, scales, series, labels, hoverIndex, hoverPosition, theme, drawHover])}diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts b/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.tsindex 40d45be7dfa2..f951cc601bd8 100644--- a/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts+++ b/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts@@ -64,6 +64,7 @@ interface UseChartInteractionOptions<Meta> {interface UseChartInteractionResult<Meta> {hoverIndex: number+ hoverPosition: { x: number; y: number } | nulltooltipCtx: TooltipContext<Meta> | nullhandlers: {onMouseMove: (e: React.MouseEvent<HTMLDivElement>) => void@@ -87,6 +88,7 @@ export function useChartInteraction<Meta = unknown>({labelToCoord,}: UseChartInteractionOptions<Meta>): UseChartInteractionResult<Meta> {const [hoverIndex, setHoverIndex] = useState<number>(-1)+ const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null)const [tooltipCtx, setTooltipCtx] = useState<TooltipContext<Meta> | null>(null)// Read by onClick to decide pin/unpin/passthrough. Event handlers fire after the// most recent commit, so an effect-deferred ref is correct here.@@ -94,6 +96,7 @@ export function useChartInteraction<Meta = unknown>({const clearTooltip = useCallback(() => {setHoverIndex(-1)+ setHoverPosition(null)setTooltipCtx(null)}, [])@@ -137,7 +140,8 @@ export function useChartInteraction<Meta = unknown>({canvasBounds,resolveValueRef.current,scales.yAxes,- interactionAxis+ interactionAxis,+ prev.hoverPosition)if (!fresh) {return null@@ -237,6 +241,7 @@ export function useChartInteraction<Meta = unknown>({const probe = interactionAxis === 'y' ? mouseY : mouseXconst index = findNearestIndexFromPositions(probe, labelPositions)setHoverIndex(index)+ setHoverPosition({ x: mouseX, y: mouseY })if (index >= 0 && showTooltip) {const canvasBounds = canvasRef.current?.getBoundingClientRect() ?? new DOMRect()@@ -251,7 +256,8 @@ export function useChartInteraction<Meta = unknown>({canvasBounds,resolveValue,scales.yAxes,- interactionAxis+ interactionAxis,+ { x: mouseX, y: mouseY }))}@@ -309,5 +315,5 @@ export function useChartInteraction<Meta = unknown>({const handlers = useMemo(() => ({ onMouseMove, onMouseLeave, onClick }), [onMouseMove, onMouseLeave, onClick])- return { hoverIndex, tooltipCtx, handlers }+ return { hoverIndex, hoverPosition, tooltipCtx, handlers }}diff --git a/frontend/src/lib/hog-charts/core/interaction.ts b/frontend/src/lib/hog-charts/core/interaction.tsindex 7c62a9626afb..7236ea897cc1 100644--- a/frontend/src/lib/hog-charts/core/interaction.ts+++ b/frontend/src/lib/hog-charts/core/interaction.ts@@ -69,7 +69,8 @@ export function buildTooltipContext<Meta = unknown>(resolveValue: ResolveValueFn,yAxes?: Record<string, YAxisScale>,/** Returned `position.{x,y}` are canvas-pixel coordinates regardless of orientation. */- interactionAxis: 'x' | 'y' = 'x'+ interactionAxis: 'x' | 'y' = 'x',+ hoverPosition: { x: number; y: number } | null = null): TooltipContext<Meta> | null {if (dataIndex < 0 || dataIndex >= labels.length) {return null@@ -112,6 +113,7 @@ export function buildTooltipContext<Meta = unknown>(label,seriesData,position,+ hoverPosition,canvasBounds,isPinned: false,}diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.tsindex 3384e25820dd..ded8cfd2d52d 100644--- a/frontend/src/lib/hog-charts/core/types.ts+++ b/frontend/src/lib/hog-charts/core/types.ts@@ -99,6 +99,8 @@ export interface TooltipContext<Meta = unknown> {seriesData: { series: Series<Meta>; value: number; color: string }[]/** Pixel position (relative to the chart container) for anchoring the tooltip. */position: { x: number; y: number }+ /** Cursor position in canvas pixels, or `null` for non-mousemove snapshots (e.g. pinned rebuild). */+ hoverPosition: { x: number; y: number } | null/** Bounding rect of the canvas element, useful for portal-based tooltip positioning. */canvasBounds: DOMRect/** Whether the tooltip is pinned (clicked). When pinned, the tooltip stays visible@@ -200,6 +202,8 @@ export interface ChartDrawArgs {labels: string[]/** Index of the currently hovered data point, or -1. */hoverIndex: number+ /** Cursor position in canvas pixels, or `null` for non-hover redraws (static layer / post-mouseleave). */+ hoverPosition: { x: number; y: number } | null/** Chart theme colors. */theme: ChartTheme}diff --git a/frontend/src/lib/hog-charts/testing/accessor.ts b/frontend/src/lib/hog-charts/testing/accessor.tsindex 82ed1e768076..8940a2d73b88 100644--- a/frontend/src/lib/hog-charts/testing/accessor.ts+++ b/frontend/src/lib/hog-charts/testing/accessor.ts@@ -6,6 +6,13 @@// contract — renaming them breaks consumers' tests. Keep in sync with the// overlay components that emit them.+import type { TooltipContext } from '../core/types'+import { waitForHogChartTooltip } from './tooltip'++/** Tooltip handle returned by `chart.waitForTooltip()` — every field of the structured+ * `TooltipContext` plus the rendered portal element, so tests can assert on either. */+export type TooltipSnapshot<Meta = unknown> = TooltipContext<Meta> & { element: HTMLElement }+interface ReferenceLineSummary {label: string | null/** Pixel position of the line — top px for horizontal, left px for vertical. */@@ -28,7 +35,7 @@ interface AnomalyPointSummary {color: string}-export interface HogChart {+export interface HogChart<Meta = unknown> {/** The wrapper div of this chart. */element: HTMLElement/** Number of non-excluded data series rendered (read from the chart's aria-label). */@@ -49,6 +56,10 @@ export interface HogChart {anomalyPoints(): AnomalyPointSummary[]/** Annotation badges currently rendered. */annotationBadges(): HTMLElement[]+ /** Wait for the tooltip to mount, then return a snapshot of both the structured+ * `TooltipContext` the chart computed and the rendered portal element. Only available+ * when the chart was rendered via `renderHogChart`; throws otherwise. */+ waitForTooltip(timeout?: number): Promise<TooltipSnapshot<Meta>>}const SERIES_COUNT_RE = /Chart with (\d+) data series/i@@ -89,7 +100,10 @@ function readReferenceLine(el: HTMLElement): ReferenceLineSummary {return { color, orientation, position, label }}-export function getHogChart(scope: HTMLElement = document.body): HogChart {+export function getHogChart<Meta = unknown>(+ scope: HTMLElement = document.body,+ getLastTooltipContext: () => TooltipContext<Meta> | null = () => null+): HogChart<Meta> {const canvas = findCanvas(scope)if (!canvas) {throw new Error('No hog-chart canvas found in scope')@@ -138,5 +152,15 @@ export function getHogChart(scope: HTMLElement = document.body): HogChart {color: el.style.backgroundColor,})),annotationBadges: () => Array.from(wrapper.querySelectorAll<HTMLElement>('.AnnotationsBadge')),+ async waitForTooltip(timeout?: number): Promise<TooltipSnapshot<Meta>> {+ const element = await waitForHogChartTooltip(timeout)+ const ctx = getLastTooltipContext()+ if (!ctx) {+ throw new Error(+ 'TooltipContext not captured. Render the chart via `renderHogChart` to enable tooltip context capture.'+ )+ }+ return { ...ctx, element }+ },}}diff --git a/frontend/src/lib/hog-charts/testing/index.ts b/frontend/src/lib/hog-charts/testing/index.tsindex 7a2682067a0d..7019947b3c67 100644--- a/frontend/src/lib/hog-charts/testing/index.ts+++ b/frontend/src/lib/hog-charts/testing/index.ts@@ -1,7 +1,7 @@export { dimensions, makeSeries, mockRect, setupJsdom, setupSyncRaf } from './jsdom'export { clickAtIndex, hoverAtIndex } from './interactions'export { getHogChart } from './accessor'-export type { HogChart } from './accessor'+export type { HogChart, TooltipSnapshot } from './accessor'export { renderHogChart } from './render'export { makeOverlayContext, renderOverlayInChart } from './overlay'export type { OverlayContextOverrides } from './overlay'diff --git a/frontend/src/lib/hog-charts/testing/render.ts b/frontend/src/lib/hog-charts/testing/render.tsindex 200347f04bd7..0f9813c66a13 100644--- a/frontend/src/lib/hog-charts/testing/render.ts+++ b/frontend/src/lib/hog-charts/testing/render.ts@@ -1,12 +1,28 @@import { render, type RenderResult } from '@testing-library/react'-import type { ReactElement } from 'react'+import React, { type ReactElement, type ReactNode } from 'react'+import type { TooltipContext } from '../core/types'+import { DefaultTooltip } from '../overlays/DefaultTooltip'import { getHogChart, type HogChart } from './accessor'/** Render a hog-charts component and return Testing Library's `RenderResult`* with a `chart` accessor attached. Throws if the rendered component doesn't- * emit a hog-charts canvas — use plain `render` for non-chart components. */-export function renderHogChart(ui: ReactElement): RenderResult & { chart: HogChart } {- const result = render(ui)- return { ...result, chart: getHogChart(result.container) }+ * emit a hog-charts canvas — use plain `render` for non-chart components.+ *+ * The `tooltip` render prop is intercepted so `chart.waitForTooltip()` can+ * return the structured `TooltipContext` the chart computed; any user-supplied+ * tooltip prop is still invoked for its rendered DOM. */+export function renderHogChart<Meta = unknown>(ui: ReactElement): RenderResult & { chart: HogChart<Meta> } {+ let lastTooltipContext: TooltipContext<Meta> | null = null+ const userTooltip = (ui.props as { tooltip?: (ctx: TooltipContext<Meta>) => ReactNode }).tooltip+ const captureTooltip = (ctx: TooltipContext<Meta>): ReactNode => {+ lastTooltipContext = ctx+ return userTooltip ? userTooltip(ctx) : DefaultTooltip(ctx as TooltipContext)+ }+ const wrapped = React.cloneElement(ui, { tooltip: captureTooltip })+ const result = render(wrapped)+ return {+ ...result,+ chart: getHogChart<Meta>(result.container, () => lastTooltipContext),+ }}diff --git a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.test.tsx b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.test.tsxindex 19fe32f4b620..bbd8f00bd674 100644--- a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.test.tsx+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.test.tsx@@ -91,9 +91,6 @@ describe('TrendsBarChart (ActionsBar)', () => {const tooltip = await chart.hoverTooltip(2)- // Stacked bars surface stacked-top values in tooltip rows, not raw series values, so we- // only assert that both compare rows are present — the dimming is enforced by the- // transforms unit test.expect(tooltip.row('Current')).toBeTruthy()expect(tooltip.row('Previous')).toBeTruthy()})