: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
feat(hog-charts): route stacked bar tooltip and click to cursor segment (#60398)
Sam Pennington2b5b80b493ce
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsxindex baaf4a7576b5..96ac6c872652 100644--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx@@ -221,7 +221,8 @@ describe('BarChart', () => {const { chart } = renderHogChart(<BarChart series={SERIES} labels={LABELS} theme={THEME} config={config} />)chart.hoverAtIndex(1)const tooltip = await chart.waitForTooltip()- expect(tooltip.seriesData.map((s) => s.series.key)).toEqual(expectedKeys)+ // Stacked/percent order is cursor-resolved, so assert membership not declaration order.+ expect(new Set(tooltip.seriesData.map((s) => s.series.key))).toEqual(new Set(expectedKeys))})it('stacked tooltip shows each series own value, not the cumulative stack total', async () => {@@ -236,6 +237,60 @@ describe('BarChart', () => {expect(tooltip.series.b.value).toBe(15)})+ it('stacked tooltip bubbles the cursor-resolved segment to seriesData[0]', async () => {+ // At index 1: a=20 (bottom of stack), b=15 (on top). Mid-plot lands in b's range.+ const { chart } = renderHogChart(+ <BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ barLayout: 'stacked' }} />+ )+ chart.hoverAtIndex(1)+ const tipB = await chart.waitForTooltip()+ expect(tipB.seriesData[0].series.key).toBe('b')+ const step = dimensions.plotWidth / LABELS.length+ // Just inside the bottom edge of the plot, well below b's top to land in a's segment.+ const NEAR_BOTTOM_OFFSET_PX = 8+ fireEvent.mouseMove(chart.element, {+ clientX: dimensions.plotLeft + step * 1.5,+ clientY: dimensions.plotTop + dimensions.plotHeight - NEAR_BOTTOM_OFFSET_PX,+ })+ const tipA = await chart.waitForTooltip()+ expect(tipA.seriesData[0].series.key).toBe('a')+ })++ it('stacked onPointClick routes to the segment whose rect contains the cursor', async () => {+ const onPointClick = jest.fn()+ const { chart } = renderHogChart(+ <BarChart+ series={SERIES}+ labels={LABELS}+ theme={THEME}+ config={{ barLayout: 'stacked' }}+ onPointClick={onPointClick}+ />+ )+ const step = dimensions.plotWidth / LABELS.length+ fireEvent.mouseMove(chart.element, {+ clientX: dimensions.plotLeft + step * 1.5,+ clientY: dimensions.plotTop + dimensions.plotHeight / 2,+ })+ fireEvent.click(chart.element)+ const clickB: PointClickData = onPointClick.mock.calls[0][0]+ expect(clickB.series.key).toBe('b')+ expect(clickB.value).toBe(15)+ expect(clickB.seriesIndex).toBe(1)++ onPointClick.mockClear()+ const NEAR_BOTTOM_OFFSET_PX = 8+ fireEvent.mouseMove(chart.element, {+ clientX: dimensions.plotLeft + step * 1.5,+ clientY: dimensions.plotTop + dimensions.plotHeight - NEAR_BOTTOM_OFFSET_PX,+ })+ fireEvent.click(chart.element)+ const clickA: PointClickData = onPointClick.mock.calls[0][0]+ expect(clickA.series.key).toBe('a')+ expect(clickA.value).toBe(20)+ expect(clickA.seriesIndex).toBe(0)+ })+it('percent tooltip shows each series own fraction, not the cumulative fraction', async () => {// At index 1: a=20, b=15 → total 35. b sits on top of a, so b's cumulative top is 1.0,// but the tooltip must report b's own 15/35 fraction — the segment, not the running total.diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsxindex d0d6f501adb5..7e6269363b2d 100644--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx@@ -1,7 +1,7 @@import * as d3 from 'd3'import React, { useCallback, useMemo, useRef } from 'react'-import { type BarChartPrivate, computeBarAtIndex, computeBarTrackRect, computeSeriesBars } from '../../core/bar-layout'+import { type BarChartPrivate, computeBarTrackRect, computeSeriesBars } from '../../core/bar-layout'import {BAR_TRACK_HOVER_ALPHA,type BarRect,@@ -14,9 +14,11 @@ import {} from '../../core/canvas-renderer'import { Chart } from '../../core/Chart'import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'+import { useLatest } from '../../core/hooks/useLatest'import {buildSegmentResolveValue,buildStackedPositionValue,+ type BarScaleSet,computeDivergingStackData,computePercentStackData,computeStackData,@@ -40,7 +42,15 @@ import type {import { DEFAULT_Y_AXIS_ID } from '../../core/types'import { computeVisibleXLabels } from '../../overlays/AxisLabels'import { BarTooltip } from './BarTooltip'-import { cursorOutsideBarFillExtent, seriesKeysAtCursor } from './utils/bars-under-cursor'+import {+ type BarLayout,+ type BarsAtCursorArgs,+ barContainsPointOnBandAxis,+ cursorOutsideBarFillExtent,+ iterBarsAtCursor,+ isStackedLayout,+ resolveBarsAtCursor,+} from './utils/bars-under-cursor'function bandCenter(scales: BarChartPrivate['__barChart'], label: string): number | undefined {const start = scales.band(label)@@ -115,6 +125,7 @@ function BarChartInner<Meta = unknown>({xTickFormatter,divergingStack = false,maxBandRange,+ bandPadding,barShadow,} = config ?? {}const isHorizontal = axisOrientation === 'horizontal'@@ -188,15 +199,15 @@ function BarChartInner<Meta = unknown>({axisOrientation,stackedSeries,maxBandRange,+ bandPadding,})const tickAxisLength = isHorizontal ? dimensions.plotWidth : dimensions.plotHeightconst yTickCount = yTickCountForHeight(tickAxisLength)- // Stash the raw d3 scales in the private slot so drawStatic/drawHover can read them- // without a side-channel ref — every render gets a self-contained ChartScales object,- // which avoids strict-mode / concurrent-rendering races between createScales and the- // static-draw effect. See LineChart.tsx and ARCHITECTURE.md for the canonical pattern.+ // Stash the raw d3 scales in the private slot so drawStatic/drawHover/click routing+ // can read them from the committed ChartScales — every render gets a self-contained+ // object, which avoids strict-mode / concurrent-rendering races.const barChartPrivate: BarChartPrivate = { __barChart: d3Scales }// For horizontal, expose the value scale as `y` (since AxisLabels horizontal mode@@ -238,7 +249,7 @@ function BarChartInner<Meta = unknown>({_private: barChartPrivate,}},- [yScaleType, barLayout, axisOrientation, stackedData, isHorizontal, divergingStack, maxBandRange]+ [yScaleType, barLayout, axisOrientation, stackedData, isHorizontal, divergingStack, maxBandRange, bandPadding])const drawStatic = useCallback(@@ -361,51 +372,22 @@ function BarChartInner<Meta = unknown>({}const hoveredLabel = drawLabels[hoverIndex]const [trackAxisStart = 0, trackAxisEnd = 0] = barTrack ? d3Scales.value.range() : []- let hitKeys: Set<string> | null = null- if (hoverPosition) {- const hits = seriesKeysAtCursor({- series: coloredSeries,- label: hoveredLabel,- dataIndex: hoverIndex,- cursor: hoverPosition,- scales: d3Scales,- layout: barLayout,- isHorizontal,- stackedData,- topStackedKeyByAxis,- })- if (hits.size === 0) {- lastHoverKeyRef.current = null- return false- }- hitKeys = hits- }// Key includes bar-vs-track per series so bar → track moves at the same// hoverIndex still trigger a fade restart.type DrawItem = { series: ResolvedSeries; bar: BarRect; isTrackHighlight: boolean }const items: DrawItem[] = []let composition = ''- 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_ID- const isTop = topStackedKeyByAxis.get(axisId) === s.key- const bar = computeBarAtIndex({- series: s,- label: hoveredLabel,- dataIndex: hoverIndex,- scales: d3Scales,- layout: barLayout,- isHorizontal,- stackedBand,- isTopOfStack: isTop,- })- if (!bar) {+ for (const { series: s, bar } of iterBarsAtCursor<ResolvedSeries>({+ series: coloredSeries,+ label: hoveredLabel,+ dataIndex: hoverIndex,+ scales: d3Scales,+ layout: barLayout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ })) {+ if (hoverPosition && !barContainsPointOnBandAxis(bar, hoverPosition, isHorizontal)) {continue}const isTrackHighlight =@@ -462,6 +444,31 @@ function BarChartInner<Meta = unknown>({const resolveValue = useMemo(() => buildSegmentResolveValue(stackedData), [stackedData])const resolvePositionValue = useMemo(() => buildStackedPositionValue(stackedData), [stackedData])+ const seriesRef = useLatest(series)++ // 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.+ const wrapClickData = useCallback(+ (clickData: PointClickData<Meta>, scales: ChartScales): PointClickData<Meta> => {+ const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart+ if (!d3Scales) {+ return clickData+ }+ return (+ resolveClickedStackedSegment({+ clickData,+ d3Scales,+ barLayout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ series: seriesRef.current,+ }) ?? clickData+ )+ },+ [barLayout, isHorizontal, stackedData, topStackedKeyByAxis, seriesRef]+ )+return (<Chartseries={series}@@ -482,6 +489,7 @@ function BarChartInner<Meta = unknown>({/>)}onPointClick={onPointClick}+ wrapClickData={onPointClick ? wrapClickData : undefined}className={className}dataAttr={dataAttr}resolveValue={resolveValue}@@ -491,3 +499,58 @@ function BarChartInner<Meta = unknown>({</Chart>)}++/** 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>({+ clickData,+ d3Scales,+ barLayout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ series,+}: {+ clickData: PointClickData<Meta>+ d3Scales: BarScaleSet+ barLayout: BarLayout+ isHorizontal: boolean+ stackedData: Map<string, StackedBand> | undefined+ topStackedKeyByAxis: Map<string, string>+ series: Series<Meta>[]+}): PointClickData<Meta> | null {+ if (!isStackedLayout(barLayout)) {+ return null+ }+ const { cursor, label, dataIndex, crossSeriesData } = clickData+ if (!cursor) {+ return null+ }+ const cursorArgs: BarsAtCursorArgs & { cursor: { x: number; y: number } } = {+ series: crossSeriesData.map((d) => d.series),+ label,+ dataIndex,+ cursor,+ scales: d3Scales,+ layout: barLayout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ }+ const { strictHit } = resolveBarsAtCursor(cursorArgs)+ if (!strictHit) {+ return null+ }+ const hit = crossSeriesData.find((d) => d.series.key === strictHit)+ if (!hit) {+ return null+ }+ return {+ ...clickData,+ series: hit.series,+ value: hit.value,+ seriesIndex: series.findIndex((s) => s.key === hit.series.key),+ }+}diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsxindex d01b58e48803..f52cfb7cad62 100644--- a/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx@@ -5,14 +5,14 @@ import { useChartLayout } from '../../core/chart-context'import type { BarScaleSet, StackedBand } from '../../core/scales'import type { TooltipContext } from '../../core/types'import { DefaultTooltip } from '../../overlays/DefaultTooltip'-import { seriesKeysAtCursor } from './utils/bars-under-cursor'+import { type BarLayout, isStackedLayout, resolveBarsAtCursor } from './utils/bars-under-cursor'export interface BarTooltipProps<Meta> {ctx: TooltipContext<Meta>userTooltip?: (ctx: TooltipContext<Meta>) => React.ReactNodestackedData: Map<string, StackedBand> | undefinedtopStackedKeyByAxis: Map<string, string>- layout: 'stacked' | 'grouped' | 'percent'+ layout: BarLayoutisHorizontal: boolean}@@ -36,12 +36,11 @@ export function BarTooltip<Meta>({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. */+/** Stacked/percent: cursor-resolved segment is moved to seriesData[0]. */function narrowSeriesByCursor<Meta>(ctx: TooltipContext<Meta>,scales: BarScaleSet,- layout: 'stacked' | 'grouped' | 'percent',+ layout: BarLayout,isHorizontal: boolean,stackedData: Map<string, StackedBand> | undefined,topStackedKeyByAxis: Map<string, string>@@ -50,8 +49,9 @@ function narrowSeriesByCursor<Meta>(if (!cursor) {return ctx}- const hits = seriesKeysAtCursor({- series: ctx.seriesData.map((entry) => entry.series),+ const seriesList = ctx.seriesData.map((entry) => entry.series)+ const { hits, strictHit } = resolveBarsAtCursor({+ series: seriesList,label: ctx.label,dataIndex: ctx.dataIndex,cursor,@@ -64,5 +64,12 @@ function narrowSeriesByCursor<Meta>(if (hits.size === 0) {return null}- return { ...ctx, seriesData: ctx.seriesData.filter((entry) => hits.has(entry.series.key)) }+ let filtered = ctx.seriesData.filter((entry) => hits.has(entry.series.key))+ if (isStackedLayout(layout) && filtered.length > 1 && strictHit) {+ const idx = filtered.findIndex((entry) => entry.series.key === strictHit)+ if (idx > 0) {+ filtered = [filtered[idx], ...filtered.filter((_, i) => i !== idx)]+ }+ }+ return { ...ctx, seriesData: filtered }}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.tsindex be80feaf13d6..8d7ed1363f79 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,5 @@import type { BarRect } from '../../../core/canvas-renderer'-import { cursorOutsideBarFillExtent } from './bars-under-cursor'+import { barContainsPoint, barContainsPointOnBandAxis, cursorOutsideBarFillExtent } 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 }@@ -22,3 +22,71 @@ describe('cursorOutsideBarFillExtent', () => {expect(cursorOutsideBarFillExtent(horizontalBar, { x, y: 110 }, true)).toBe(expected)})})++describe('barContainsPointOnBandAxis', () => {+ it.each([+ { desc: 'inside band', y: 110, expected: true },+ { desc: 'outside band above', y: 80, expected: false },+ { desc: 'outside band below', y: 160, expected: false },+ ])('horizontal bar — ignores x, checks band (y) axis only: $desc -> $expected', ({ y, expected }) => {+ expect(barContainsPointOnBandAxis(horizontalBar, { x: -9999, y }, true)).toBe(expected)+ })++ it.each([+ { desc: 'inside band', x: 110, expected: true },+ { desc: 'outside band left', x: 80, expected: false },+ { desc: 'outside band right', x: 200, expected: false },+ ])('vertical bar — ignores y, checks band (x) axis only: $desc -> $expected', ({ x, expected }) => {+ expect(barContainsPointOnBandAxis(verticalBar, { x, y: -9999 }, false)).toBe(expected)+ })+})++describe('barContainsPoint', () => {+ it.each([+ { desc: 'inside the segment', x: 120, y: 110, expected: true },+ { desc: 'left of the segment', x: 40, y: 110, expected: false },+ { desc: 'right of the segment', x: 300, y: 110, expected: false },+ { desc: 'inside x but outside band', x: 120, y: 80, expected: false },+ ])('horizontal bar — $desc -> $expected', ({ x, y, expected }) => {+ expect(barContainsPoint(horizontalBar, { x, y })).toBe(expected)+ })++ it.each([+ { desc: 'inside the segment', x: 110, y: 220, expected: true },+ { desc: 'above the segment', x: 110, y: 80, expected: false },+ { desc: 'below the segment', x: 110, y: 360, expected: false },+ { desc: 'inside y but outside band', x: 80, y: 220, expected: false },+ ])('vertical bar — $desc -> $expected', ({ x, y, expected }) => {+ expect(barContainsPoint(verticalBar, { x, y })).toBe(expected)+ })++ // Half-open semantics on the trailing edge: matches d3 band-scale `[start, start + size)`,+ // so adjacent bars sharing a pixel boundary never both report a hit at that pixel.+ describe('boundary pixels (half-open trailing edge)', () => {+ it('vertical bar — leading edge (x=bar.x, y=bar.y) is inside', () => {+ expect(barContainsPoint(verticalBar, { x: verticalBar.x, y: verticalBar.y })).toBe(true)+ })++ it('vertical bar — trailing edge (x=bar.x+width, y=bar.y+height) is outside', () => {+ expect(+ barContainsPoint(verticalBar, {+ x: verticalBar.x + verticalBar.width,+ y: verticalBar.y + verticalBar.height,+ })+ ).toBe(false)+ })++ it('horizontal bar — leading edge (x=bar.x, y=bar.y) is inside', () => {+ expect(barContainsPoint(horizontalBar, { x: horizontalBar.x, y: horizontalBar.y })).toBe(true)+ })++ it('horizontal bar — trailing edge (x=bar.x+width, y=bar.y+height) is outside', () => {+ expect(+ barContainsPoint(horizontalBar, {+ x: horizontalBar.x + horizontalBar.width,+ y: horizontalBar.y + horizontalBar.height,+ })+ ).toBe(false)+ })+ })+})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.tsindex fedc51bae8b8..19cf46082e01 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,18 +4,32 @@ import type { BarScaleSet, StackedBand } from '../../../core/scales'import type { Series } from '../../../core/types'import { DEFAULT_Y_AXIS_ID } from '../../../core/types'+export type BarLayout = 'stacked' | 'grouped' | 'percent'++export function isStackedLayout(layout: BarLayout): boolean {+ return layout !== 'grouped'+}+/** 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. */+ * per-bar check, fall back to "highlight all", and visually flag both group-mates at once.+ * Half-open on the trailing edge — matches d3 band-scale slots `[start, start + size)`. */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+ ? point.y >= bar.y && point.y < bar.y + bar.height+ : point.x >= bar.x && point.x < bar.x + bar.width+}++/** Full-rect (both axes) hit-test. Stacked segments share a band slot; the value axis is+ * what distinguishes them. Half-open on the trailing edge — matches d3 band-scale slots+ * `[start, start + size)`. */+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}/** True when the cursor is in the bar's band slot but outside its filled value extent —@@ -32,22 +46,29 @@ export function cursorOutsideBarFillExtent(: point.y < bar.y || point.y > bar.y + bar.height}-export interface SeriesKeysAtCursorArgs {+export interface BarsAtCursorArgs {series: readonly Pick<Series, 'key' | 'visibility' | 'yAxisId' | 'data'>[]label: stringdataIndex: number- cursor: { x: number; y: number }scales: BarScaleSet- layout: 'stacked' | 'grouped' | 'percent'+ layout: BarLayoutisHorizontal: booleanstackedData?: Map<string, StackedBand>topStackedKeyByAxis: Map<string, string>}-/** Shared by drawHover and the tooltip wrapper so they can't drift. */-export function seriesKeysAtCursor(args: SeriesKeysAtCursorArgs): Set<string> {- const { series, label, dataIndex, cursor, scales, layout, isHorizontal, stackedData, topStackedKeyByAxis } = args- const hits = new Set<string>()+export interface BarAtCursor<S> {+ series: S+ bar: BarRect+}++/** Yields the renderable `{ series, bar }` for every visible series at `(label, dataIndex)`.+ * Single source of truth shared by drawHover, tooltip narrowing, and click routing —+ * encapsulates visibility skip, stacked-band lookup, and `computeBarAtIndex`. */+export function* iterBarsAtCursor<S extends Pick<Series, 'key' | 'visibility' | 'yAxisId' | 'data'>>(+ args: Omit<BarsAtCursorArgs, 'series'> & { series: readonly S[] }+): Generator<BarAtCursor<S>> {+ const { series, label, dataIndex, scales, layout, isHorizontal, stackedData, topStackedKeyByAxis } = argsfor (const s of series) {if (s.visibility?.excluded) {continue@@ -56,7 +77,7 @@ export function seriesKeysAtCursor(args: SeriesKeysAtCursorArgs): Set<string> {const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_IDconst isTopOfStack = topStackedKeyByAxis.get(axisId) === s.keyconst bar = computeBarAtIndex({- series: s as Series,+ series: s as unknown as Series,label,dataIndex,scales,@@ -65,9 +86,35 @@ export function seriesKeysAtCursor(args: SeriesKeysAtCursorArgs): Set<string> {stackedBand,isTopOfStack,})- if (bar && barContainsPointOnBandAxis(bar, cursor, isHorizontal)) {+ if (bar) {+ yield { series: s, bar }+ }+ }+}++export interface ResolveBarsAtCursorResult {+ /** Series keys whose bar slot contains the cursor on the band axis (every stacked segment). */+ hits: Set<string>+ /** Series key whose full rect contains the cursor, or `null`. Used to single out a+ * stacked segment for tooltip ordering and click routing. */+ strictHit: string | null+}++/** Single pass that does both band-axis containment (used by stacked tooltips to list every+ * segment sharing the slot) and full-rect containment (the one segment under the cursor). */+export function resolveBarsAtCursor(+ args: BarsAtCursorArgs & { cursor: { x: number; y: number } }+): ResolveBarsAtCursorResult {+ const { cursor, isHorizontal } = args+ const hits = new Set<string>()+ let strictHit: string | null = null+ for (const { series: s, bar } of iterBarsAtCursor(args)) {+ if (barContainsPointOnBandAxis(bar, cursor, isHorizontal)) {hits.add(s.key)}+ if (strictHit == null && barContainsPoint(bar, cursor)) {+ strictHit = s.key+ }}- return hits+ return { hits, strictHit }}diff --git a/frontend/src/lib/hog-charts/core/Chart.tsx b/frontend/src/lib/hog-charts/core/Chart.tsxindex 1ffe962c5915..aca74efc2210 100644--- a/frontend/src/lib/hog-charts/core/Chart.tsx+++ b/frontend/src/lib/hog-charts/core/Chart.tsx@@ -109,6 +109,10 @@ export interface ChartProps<Meta = unknown> {* whisker min/max samples so the y-tick column fits the real value range, not just the* medians it draws on `series.data`. */valueRangeSeries?: Series[]+ /** Chart-type seam: rewrite the click payload (e.g. resolve the stacked segment under the+ * cursor) before it reaches `onPointClick`, using the committed `scales` from this render.+ * Chart-type adapters provide this; consumers do not. */+ wrapClickData?: (data: PointClickData<Meta>, scales: ChartScales) => PointClickData<Meta>}export function Chart<Meta = unknown>({@@ -128,6 +132,7 @@ export function Chart<Meta = unknown>({resolvePositionValue,labelToCoord,valueRangeSeries,+ wrapClickData,}: ChartProps<Meta>): React.ReactElement {const {xTickFormatter,@@ -199,6 +204,7 @@ export function Chart<Meta = unknown>({resolvePositionValue,interactionAxis,labelToCoord,+ wrapClickData,})// ref keeps composedDrawHover stable across drawHover identity changesdiff --git a/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts b/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.tsindex 8243cf74dfee..9ac1b30b6ac0 100644--- a/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts+++ b/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts@@ -36,6 +36,10 @@ interface UseChartInteractionOptions<Meta> {resolvePositionValue?: ResolveValueFninteractionAxis?: 'x' | 'y'labelToCoord?: (label: string) => number | undefined+ /** Chart-type seam: rewrite the click payload (e.g. resolve the stacked segment under the+ * cursor) before it reaches `onPointClick`, using the committed `scales` from this render.+ * Chart-type adapters provide this; consumers do not. */+ wrapClickData?: (data: PointClickData<Meta>, scales: ChartScales) => PointClickData<Meta>}interface UseChartInteractionResult<Meta> {@@ -63,6 +67,7 @@ export function useChartInteraction<Meta = unknown>({resolvePositionValue,interactionAxis = 'x',labelToCoord,+ wrapClickData,}: UseChartInteractionOptions<Meta>): UseChartInteractionResult<Meta> {// Falls back to the value resolver when the chart doesn't distinguish position from// value (i.e. non-stacked charts, where the two are identical).@@ -122,6 +127,7 @@ export function useChartInteraction<Meta = unknown>({// Read by onClick to decide pin/unpin/passthrough. Event handlers fire after the most// recent commit, so an effect-deferred ref is correct here.const hoverIndexRef = useLatest(hoverIndex)+ const hoverPositionRef = useLatest(hoverPosition)// Precompute the (coord, index) lookup table once per (labels, scale) change.const labelPositions = useMemo(@@ -216,12 +222,26 @@ export function useChartInteraction<Meta = unknown>({}if (onPointClick) {- const clickData = buildPointClickData(currentIndex, series, labels, resolveValue)+ const clickData = buildPointClickData(currentIndex, series, labels, resolveValue, hoverPositionRef.current)if (clickData) {- onPointClick(clickData)+ onPointClick(wrapClickData && scales ? wrapClickData(clickData, scales) : clickData)}}- }, [onPointClick, series, labels, resolveValue, pinnable, tooltipCtx, isPinned, clearTooltip, pin, hoverIndexRef])+ }, [+ onPointClick,+ series,+ labels,+ resolveValue,+ pinnable,+ tooltipCtx,+ isPinned,+ clearTooltip,+ pin,+ hoverIndexRef,+ hoverPositionRef,+ wrapClickData,+ scales,+ ])const handlers = useMemo(() => ({ onMouseMove, onMouseLeave, onClick }), [onMouseMove, onMouseLeave, onClick])diff --git a/frontend/src/lib/hog-charts/core/interaction.test.ts b/frontend/src/lib/hog-charts/core/interaction.test.tsindex ea2eb40acce5..7ce28caa80b9 100644--- a/frontend/src/lib/hog-charts/core/interaction.test.ts+++ b/frontend/src/lib/hog-charts/core/interaction.test.ts@@ -277,17 +277,17 @@ describe('hog-charts interaction', () => {{ index: 1, desc: 'dataIndex equal to labels.length' },])('returns null for $desc', ({ index }) => {const series = [makeSeries({ key: 's1', data: [10] })]- expect(buildPointClickData(index, series, ['a'], defaultResolveValue)).toBeNull()+ expect(buildPointClickData(index, series, ['a'], defaultResolveValue, null)).toBeNull()})it('returns null when all series have visibility.excluded', () => {const series = [makeSeries({ key: 's1', data: [10], visibility: { excluded: true } })]- expect(buildPointClickData(0, series, ['a'], defaultResolveValue)).toBeNull()+ expect(buildPointClickData(0, series, ['a'], defaultResolveValue, null)).toBeNull()})it('returns click data for a valid index with a single visible series', () => {const series = [makeSeries({ key: 's1', data: [42] })]- const result = buildPointClickData(0, series, ['a'], defaultResolveValue)+ const result = buildPointClickData(0, series, ['a'], defaultResolveValue, null)expect(result).not.toBeNull()expect(result?.label).toBe('a')expect(result?.dataIndex).toBe(0)@@ -299,7 +299,7 @@ describe('hog-charts interaction', () => {it('uses the first visible series when multiple series are present', () => {const hidden = makeSeries({ key: 'h', data: [1], visibility: { excluded: true } })const visible = makeSeries({ key: 'v', data: [2] })- const result = buildPointClickData(0, [hidden, visible], ['a'], defaultResolveValue)+ const result = buildPointClickData(0, [hidden, visible], ['a'], defaultResolveValue, null)expect(result?.series.key).toBe('v')expect(result?.seriesIndex).toBe(1)})@@ -308,7 +308,7 @@ describe('hog-charts interaction', () => {const s1 = makeSeries({ key: 's1', data: [10] })const s2 = makeSeries({ key: 's2', data: [20] })const hidden = makeSeries({ key: 'h', data: [30], visibility: { excluded: true } })- const result = buildPointClickData(0, [s1, s2, hidden], ['a'], defaultResolveValue)+ const result = buildPointClickData(0, [s1, s2, hidden], ['a'], defaultResolveValue, null)expect(result?.crossSeriesData.length).toBe(2)expect(result?.crossSeriesData.map((d) => d.series.key)).toEqual(['s1', 's2'])})@@ -317,7 +317,7 @@ describe('hog-charts interaction', () => {const s1 = makeSeries({ key: 's1', data: [0] })const s2 = makeSeries({ key: 's2', data: [0] })const customResolve: ResolveValueFn = (s) => (s.key === 's1' ? 111 : 222)- const result = buildPointClickData(0, [s1, s2], ['a'], customResolve)+ const result = buildPointClickData(0, [s1, s2], ['a'], customResolve, null)expect(result?.value).toBe(111)expect(result?.crossSeriesData[0].value).toBe(111)expect(result?.crossSeriesData[1].value).toBe(222)@@ -325,7 +325,7 @@ describe('hog-charts interaction', () => {it('returns the correct label for a non-zero dataIndex', () => {const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]- const result = buildPointClickData(2, series, ['x', 'y', 'z'], defaultResolveValue)+ const result = buildPointClickData(2, series, ['x', 'y', 'z'], defaultResolveValue, null)expect(result?.label).toBe('z')expect(result?.value).toBe(30)})diff --git a/frontend/src/lib/hog-charts/core/interaction.ts b/frontend/src/lib/hog-charts/core/interaction.tsindex 942d25c7e30f..d1aaebc5acb6 100644--- a/frontend/src/lib/hog-charts/core/interaction.ts+++ b/frontend/src/lib/hog-charts/core/interaction.ts@@ -135,7 +135,10 @@ export function buildPointClickData<Meta = unknown>(dataIndex: number,series: ResolvedSeries<Meta>[],labels: string[],- resolveValue: ResolveValueFn+ resolveValue: ResolveValueFn,+ // Required — callers pass `null` explicitly when cursor isn't available. No implicit default+ // because losing the cursor silently breaks downstream click routing.+ cursor: { x: number; y: number } | null): PointClickData<Meta> | null {if (dataIndex < 0 || dataIndex >= labels.length) {return null@@ -158,5 +161,6 @@ export function buildPointClickData<Meta = unknown>(series: s,value: resolveValue(s, dataIndex),})),+ cursor,}}diff --git a/frontend/src/lib/hog-charts/core/scales.ts b/frontend/src/lib/hog-charts/core/scales.tsindex f62830a80302..3bd1e5d31d3f 100644--- a/frontend/src/lib/hog-charts/core/scales.ts+++ b/frontend/src/lib/hog-charts/core/scales.ts@@ -3,6 +3,9 @@ import * as d3 from 'd3'import type { ChartDimensions, ChartScales, ResolveValueFn, Series } from './types'import { DEFAULT_Y_AXIS_ID } from './types'+/** Inner padding fraction applied to the band scale when `BarChartConfig.bandPadding` is unset. */+export const DEFAULT_BAND_PADDING = 0.2+type D3YScale = d3.ScaleLinear<number, number> | d3.ScaleLogarithmic<number, number>export interface ScaleSet {@@ -327,7 +330,7 @@ export function createBarScales(scaleType = 'linear',barLayout = 'stacked',axisOrientation = 'vertical',- bandPadding = 0.2,+ bandPadding = DEFAULT_BAND_PADDING,groupPadding = 0.1,stackedSeries,maxBandRange,diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.tsindex a444ec6d5628..96a07abb4b9c 100644--- a/frontend/src/lib/hog-charts/core/types.ts+++ b/frontend/src/lib/hog-charts/core/types.ts@@ -100,6 +100,9 @@ export interface PointClickData<Meta = unknown> {label: string/** Values from all visible series at this x-axis index, for cross-series comparisons. */crossSeriesData: { series: Series<Meta>; value: number }[]+ /** Cursor position in pixels relative to the chart wrapper at click time, or `null`+ * when unavailable. Same origin as `TooltipContext.hoverPosition`. */+ cursor: { x: number; y: number } | null}/** Context object passed to the `renderTooltip` render prop and tooltip event callbacks. */@@ -218,6 +221,9 @@ export interface BarChartConfig extends ChartConfig {/** Cap (px) on the band-axis range. Clusters bars at the start of the plot while* gridlines still span the full width — useful for few-category funnel-style charts. */maxBandRange?: number+ /** Inner gap between bars as a fraction of the band slot (0–1). Outer padding is half+ * this value, so `step = range / N`. Defaults to `DEFAULT_BAND_PADDING` in `scales.ts`. */+ bandPadding?: number/** Drop shadow under each bar so it reads as layered over a `barTrack`. */barShadow?: boolean | { color: string; blur: number; offsetX?: number; offsetY?: number }}