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): split aggregated bar bands per series (#60488)

Sam Pennington73fa822ad8c3
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 96ac6c872652..4db189d15333 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
+++ b/frontend/src/lib/hog-charts/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 { renderHogChart } from '../../testing'
+import { getHogChartTooltip, renderHogChart } from '../../testing'
import { dimensions } from '../../testing/jsdom'
import { BarChart } from './BarChart'
@@ -340,6 +340,105 @@ describe('BarChart', () => {
expect(tooltipEl?.textContent ?? '').toBe('')
})
+ it('stacked horizontal suppresses tooltip past the bar value extent', async () => {
+ const { chart } = renderHogChart(
+ <BarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ barLayout: 'stacked', axisOrientation: 'horizontal' }}
+ />
+ )
+ // plotHeight/2 lands in the middle row (Tue), which stacks to 35 while the value axis
+ // runs to the global max (Wed = 55) — so the left of the plot is filled bar and the
+ // right is empty track.
+ const yMidRow = dimensions.plotTop + dimensions.plotHeight / 2
+ // Over the bar: tooltip shows.
+ fireEvent.mouseMove(chart.element, {
+ clientX: dimensions.plotLeft + dimensions.plotWidth * 0.2,
+ clientY: yMidRow,
+ })
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.element.textContent).toContain('Tue')
+ // Past the bar's value extent: tooltip must clear.
+ fireEvent.mouseMove(chart.element, {
+ clientX: dimensions.plotLeft + dimensions.plotWidth * 0.95,
+ clientY: yMidRow,
+ })
+ 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
+ // its colour wins at x=0..20, then mid at 20..50, then big at 50..100.
+ const SPARSE_LABELS = ['band', 'band', 'band']
+ const SPARSE_SERIES: Series[] = [
+ // DESC, matching how `trendsDataLogic` sorts ActionsBarValue results.
+ { key: 'big', label: 'Big', data: [100, 0, 0] },
+ { key: 'mid', label: 'Mid', data: [0, 50, 0] },
+ { key: 'small', label: 'Small', data: [0, 0, 20] },
+ ]
+ const HORIZONTAL_STACKED: BarChartConfig = { barLayout: 'stacked', axisOrientation: 'horizontal' }
+ // Value scale `[0, 100]` (already nice).
+ const xForValue = (value: number): number => dimensions.plotLeft + (value / 100) * dimensions.plotWidth
+ const yMidBand = dimensions.plotTop + dimensions.plotHeight / 2
+
+ it.each<[string, number, string, number]>([
+ ['small slice (0 < x < 20)', 10, 'small', 20],
+ ['mid slice (20 < x < 50)', 30, 'mid', 50],
+ ['big slice (50 < x < 100)', 75, 'big', 100],
+ ])(
+ 'tooltip narrows to the visible segment with its own value for cursor in the %s',
+ async (_name, valueAtCursor, key, expectedValue) => {
+ const { chart } = renderHogChart(
+ <BarChart
+ series={SPARSE_SERIES}
+ labels={SPARSE_LABELS}
+ theme={THEME}
+ config={HORIZONTAL_STACKED}
+ />
+ )
+ fireEvent.mouseMove(chart.element, {
+ clientX: xForValue(valueAtCursor),
+ clientY: yMidBand,
+ })
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.seriesData[0].series.key).toBe(key)
+ expect(tooltip.seriesData[0].value).toBe(expectedValue)
+ }
+ )
+
+ it.each<[string, number, string, number, number]>([
+ ['small slice', 10, 'small', 20, 2],
+ ['mid slice', 30, 'mid', 50, 1],
+ ['big slice', 75, 'big', 100, 0],
+ ])(
+ 'onPointClick routes to the visible segment for cursor in the %s',
+ async (_name, valueAtCursor, key, expectedValue, expectedSeriesIndex) => {
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <BarChart
+ series={SPARSE_SERIES}
+ labels={SPARSE_LABELS}
+ theme={THEME}
+ config={HORIZONTAL_STACKED}
+ onPointClick={onPointClick}
+ />
+ )
+ fireEvent.mouseMove(chart.element, {
+ clientX: xForValue(valueAtCursor),
+ clientY: yMidBand,
+ })
+ fireEvent.click(chart.element)
+ const click: PointClickData = onPointClick.mock.calls[0][0]
+ expect(click.series.key).toBe(key)
+ expect(click.value).toBe(expectedValue)
+ expect(click.seriesIndex).toBe(expectedSeriesIndex)
+ }
+ )
+ })
+
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' }} />
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
index 7e6269363b2d..f3a15429023e 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
@@ -14,6 +14,7 @@ import {
} from '../../core/canvas-renderer'
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
+import { DEFAULT_MARGINS, X_AXIS_TITLE_MARGIN } from '../../core/hooks/useChartMargins'
import { useLatest } from '../../core/hooks/useLatest'
import {
buildSegmentResolveValue,
@@ -44,12 +45,11 @@ import { computeVisibleXLabels } from '../../overlays/AxisLabels'
import { BarTooltip } from './BarTooltip'
import {
type BarLayout,
- type BarsAtCursorArgs,
barContainsPointOnBandAxis,
cursorOutsideBarFillExtent,
+ findVisibleStackedSegment,
iterBarsAtCursor,
isStackedLayout,
- resolveBarsAtCursor,
} from './utils/bars-under-cursor'
function bandCenter(scales: BarChartPrivate['__barChart'], label: string): number | undefined {
@@ -86,6 +86,11 @@ export interface BarChartProps<Meta = unknown> {
// Negative offsetY casts the shadow upward onto the visible track above the bar.
const DEFAULT_BAR_SHADOW: BarShadow = { color: 'rgba(0,0,0,0.30)', blur: 12, offsetY: -4 }
+// Horizontal floor: each row gets at least this much px so tick labels don't crush; wrapper scrolls.
+const HORIZONTAL_MIN_BAND_SIZE_DEFAULT = 24
+// Reserve room for chart-edge margins + worst-case x-axis title margin (matches useChartMargins).
+const HORIZONTAL_CHART_MARGIN_PX = DEFAULT_MARGINS.top + DEFAULT_MARGINS.bottom + X_AXIS_TITLE_MARGIN
+
function resolveBarShadow(barShadow: BarChartConfig['barShadow']): BarShadow | undefined {
if (barShadow === true) {
return DEFAULT_BAR_SHADOW
@@ -127,9 +132,22 @@ function BarChartInner<Meta = unknown>({
maxBandRange,
bandPadding,
barShadow,
+ minBandSize,
} = config ?? {}
const isHorizontal = axisOrientation === 'horizontal'
+ const resolvedMinBandSize = minBandSize ?? (isHorizontal ? HORIZONTAL_MIN_BAND_SIZE_DEFAULT : 0)
+ const wrapperMinHeight = useMemo(() => {
+ if (!isHorizontal || resolvedMinBandSize <= 0) {
+ return undefined
+ }
+ const uniqueBands = new Set(labels).size
+ if (uniqueBands === 0) {
+ return undefined
+ }
+ return uniqueBands * resolvedMinBandSize + HORIZONTAL_CHART_MARGIN_PX
+ }, [isHorizontal, resolvedMinBandSize, labels])
+
const stackedData = useMemo((): Map<string, StackedBand> | undefined => {
if (barLayout === 'percent') {
return computePercentStackData(series, labels)
@@ -377,26 +395,54 @@ function BarChartInner<Meta = unknown>({
type DrawItem = { series: ResolvedSeries; bar: BarRect; isTrackHighlight: boolean }
const items: DrawItem[] = []
let composition = ''
- 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
+ // Stacked: clip the highlight to the visible slice so hover only changes shade,
+ // never z-order. Grouped keeps band-axis containment for cursor-above-bar.
+ const stackedHighlight = isStackedLayout(barLayout)
+ if (stackedHighlight && hoverPosition) {
+ const visible = findVisibleStackedSegment({
+ series: coloredSeries,
+ labels: drawLabels,
+ hoveredLabel,
+ cursor: hoverPosition,
+ scales: d3Scales,
+ layout: barLayout,
+ isHorizontal,
+ stackedData,
+ topStackedKeyByAxis,
+ })
+ if (visible) {
+ const visibleExtent = isHorizontal ? visible.bar.width : visible.bar.height
+ const { nextSmallerExtent } = visible
+ const baselinePx = isHorizontal ? visible.bar.x : visible.bar.y + visible.bar.height
+ const clippedExtent = Math.max(0, visibleExtent - nextSmallerExtent)
+ const clipped: BarRect = isHorizontal
+ ? { ...visible.bar, x: baselinePx + nextSmallerExtent, width: clippedExtent }
+ : { ...visible.bar, y: baselinePx - visibleExtent, height: clippedExtent }
+ items.push({ series: visible.series, bar: clipped, isTrackHighlight: false })
+ composition += 'b'
+ }
+ } else {
+ 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 =
+ barTrack === true &&
+ barLayout === 'grouped' &&
+ hoverPosition != null &&
+ cursorOutsideBarFillExtent(bar, hoverPosition, isHorizontal)
+ items.push({ series: s, bar, isTrackHighlight })
+ composition += isTrackHighlight ? 't' : 'b'
}
- const isTrackHighlight =
- barTrack === true &&
- barLayout === 'grouped' &&
- hoverPosition != null &&
- cursorOutsideBarFillExtent(bar, hoverPosition, isHorizontal)
- items.push({ series: s, bar, isTrackHighlight })
- composition += isTrackHighlight ? 't' : 'b'
}
if (items.length === 0) {
lastHoverKeyRef.current = null
@@ -445,6 +491,7 @@ function BarChartInner<Meta = unknown>({
const resolvePositionValue = useMemo(() => buildStackedPositionValue(stackedData), [stackedData])
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.
@@ -463,13 +510,14 @@ function BarChartInner<Meta = unknown>({
stackedData,
topStackedKeyByAxis,
series: seriesRef.current,
+ labels: labelsRef.current,
}) ?? clickData
)
},
- [barLayout, isHorizontal, stackedData, topStackedKeyByAxis, seriesRef]
+ [barLayout, isHorizontal, stackedData, topStackedKeyByAxis, seriesRef, labelsRef]
)
- return (
+ const chart = (
<Chart
series={series}
labels={labels}
@@ -482,6 +530,7 @@ function BarChartInner<Meta = unknown>({
<BarTooltip<Meta>
ctx={ctx}
userTooltip={tooltip}
+ allSeries={series}
stackedData={stackedData}
topStackedKeyByAxis={topStackedKeyByAxis}
layout={barLayout}
@@ -498,6 +547,13 @@ function BarChartInner<Meta = unknown>({
{children}
</Chart>
)
+
+ // Always wrap — switching shape (axisOrientation, empty labels) would otherwise remount Chart.
+ return (
+ <div className="flex flex-col flex-1" style={{ minHeight: wrapperMinHeight }}>
+ {chart}
+ </div>
+ )
}
/** Pure helper extracted so the click-rewrite is unit-testable and the component-level
@@ -512,6 +568,7 @@ export function resolveClickedStackedSegment<Meta>({
stackedData,
topStackedKeyByAxis,
series,
+ labels,
}: {
clickData: PointClickData<Meta>
d3Scales: BarScaleSet
@@ -520,37 +577,44 @@ export function resolveClickedStackedSegment<Meta>({
stackedData: Map<string, StackedBand> | undefined
topStackedKeyByAxis: Map<string, string>
series: Series<Meta>[]
+ labels: readonly string[]
}): PointClickData<Meta> | null {
if (!isStackedLayout(barLayout)) {
return null
}
- const { cursor, label, dataIndex, crossSeriesData } = clickData
+ const { cursor, label, crossSeriesData } = clickData
if (!cursor) {
return null
}
- const cursorArgs: BarsAtCursorArgs & { cursor: { x: number; y: number } } = {
+ // 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),
- label,
- dataIndex,
+ labels,
+ hoveredLabel: label,
cursor,
scales: d3Scales,
layout: barLayout,
isHorizontal,
stackedData,
topStackedKeyByAxis,
- }
- const { strictHit } = resolveBarsAtCursor(cursorArgs)
- if (!strictHit) {
+ })
+ if (!visible) {
return null
}
- const hit = crossSeriesData.find((d) => d.series.key === strictHit)
+ const hit = crossSeriesData.find((d) => d.series.key === visible.series.key)
if (!hit) {
return null
}
+ // Re-read value at the visible segment's own dataIndex — `hit.value` was resolved at the
+ // 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: hit.value,
+ value: resolvedValue,
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.tsx
index f52cfb7cad62..87550e6363bf 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarTooltip.tsx
@@ -3,13 +3,21 @@ import React from 'react'
import type { BarChartPrivate } from '../../core/bar-layout'
import { useChartLayout } from '../../core/chart-context'
import type { BarScaleSet, StackedBand } from '../../core/scales'
-import type { TooltipContext } from '../../core/types'
+import type { Series, TooltipContext } from '../../core/types'
import { DefaultTooltip } from '../../overlays/DefaultTooltip'
-import { type BarLayout, isStackedLayout, resolveBarsAtCursor } from './utils/bars-under-cursor'
+import {
+ type BarLayout,
+ findVisibleStackedSegment,
+ isStackedLayout,
+ resolveBarsAtCursor,
+} from './utils/bars-under-cursor'
export interface BarTooltipProps<Meta> {
ctx: TooltipContext<Meta>
userTooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
+ /** Every drawn series, including those hidden from the tooltip — the visible-segment
+ * hit-test must see the full stack, not just the tooltip-visible subset. */
+ allSeries: Series<Meta>[]
stackedData: Map<string, StackedBand> | undefined
topStackedKeyByAxis: Map<string, string>
layout: BarLayout
@@ -19,15 +27,25 @@ export interface BarTooltipProps<Meta> {
export function BarTooltip<Meta>({
ctx,
userTooltip,
+ allSeries,
stackedData,
topStackedKeyByAxis,
layout,
isHorizontal,
}: BarTooltipProps<Meta>): React.ReactElement | null {
- const { scales } = useChartLayout()
+ const { scales, labels } = useChartLayout()
const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
if (d3Scales && ctx.hoverPosition && ctx.dataIndex >= 0) {
- const narrowed = narrowSeriesByCursor(ctx, d3Scales, layout, isHorizontal, stackedData, topStackedKeyByAxis)
+ const narrowed = narrowSeriesByCursor(
+ ctx,
+ d3Scales,
+ layout,
+ isHorizontal,
+ stackedData,
+ topStackedKeyByAxis,
+ labels,
+ allSeries
+ )
if (!narrowed) {
return null
}
@@ -36,21 +54,24 @@ export function BarTooltip<Meta>({
return <>{userTooltip ? userTooltip(ctx) : DefaultTooltip(ctx)}</>
}
-/** Stacked/percent: cursor-resolved segment is moved to seriesData[0]. */
+/** Moves the cursor-resolved segment to seriesData[0] and (for sparse-stacked overlap)
+ * re-reads its value at its own dataIndex so it isn't a zero from a band-collapsed cell. */
function narrowSeriesByCursor<Meta>(
ctx: TooltipContext<Meta>,
scales: BarScaleSet,
layout: BarLayout,
isHorizontal: boolean,
stackedData: Map<string, StackedBand> | undefined,
- topStackedKeyByAxis: Map<string, string>
+ topStackedKeyByAxis: Map<string, string>,
+ labels: string[],
+ allSeries: Series<Meta>[]
): TooltipContext<Meta> | null {
const cursor = ctx.hoverPosition
if (!cursor) {
return ctx
}
const seriesList = ctx.seriesData.map((entry) => entry.series)
- const { hits, strictHit } = resolveBarsAtCursor({
+ const { hits } = resolveBarsAtCursor({
series: seriesList,
label: ctx.label,
dataIndex: ctx.dataIndex,
@@ -64,12 +85,49 @@ function narrowSeriesByCursor<Meta>(
if (hits.size === 0) {
return null
}
+ let visibleKey: string | null = null
+ let visibleDataIndex: number | null = null
+ if (isStackedLayout(layout)) {
+ const visible = findVisibleStackedSegment({
+ series: allSeries,
+ labels,
+ hoveredLabel: ctx.label,
+ cursor,
+ scales,
+ layout,
+ isHorizontal,
+ 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) {
+ return null
+ }
+ visibleKey = visible.series.key
+ visibleDataIndex = visible.dataIndex
+ }
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 (isStackedLayout(layout) && filtered.length > 1 && visibleKey) {
+ const idx = filtered.findIndex((entry) => entry.series.key === visibleKey)
if (idx > 0) {
filtered = [filtered[idx], ...filtered.filter((_, i) => i !== idx)]
}
}
+ // For sparse-stacked overlap ctx.dataIndex is a zero cell for the visible series. Rewrite
+ // the entry's value (and ctx.dataIndex) to the segment's own index so row clicks route
+ // correctly downstream.
+ if (visibleKey != null && visibleDataIndex != null && visibleDataIndex !== ctx.dataIndex) {
+ const di = visibleDataIndex
+ filtered = filtered.map((entry) => {
+ if (entry.series.key !== visibleKey) {
+ return entry
+ }
+ const raw = entry.series.data[di]
+ const value = typeof raw === 'number' && Number.isFinite(raw) ? raw : entry.value
+ return { ...entry, value }
+ })
+ return { ...ctx, seriesData: filtered, dataIndex: di }
+ }
return { ...ctx, seriesData: filtered }
}
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 19cf46082e01..dedd4bc412be 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
@@ -118,3 +118,41 @@ export function resolveBarsAtCursor(
}
return { hits, strictHit }
}
+
+/** 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. */
+export function findVisibleStackedSegment<S extends Pick<Series, 'key' | 'visibility' | 'yAxisId' | 'data'>>(
+ args: Omit<BarsAtCursorArgs, 'series' | 'label' | 'dataIndex'> & {
+ series: readonly S[]
+ labels: readonly string[]
+ hoveredLabel: string
+ cursor: { x: number; y: number }
+ }
+): { 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[] = []
+ for (let dataIndex = 0; dataIndex < labels.length; dataIndex++) {
+ if (labels[dataIndex] !== hoveredLabel) {
+ continue
+ }
+ for (const { series: s, bar } of iterBarsAtCursor({ ...args, label: labels[dataIndex], dataIndex })) {
+ const extent = isHorizontal ? bar.width : bar.height
+ if (extent <= 0) {
+ continue
+ }
+ allExtents.push(extent)
+ if (!barContainsPoint(bar, cursor)) {
+ continue
+ }
+ // Overwrite so the last-drawn (smallest, painted on top) candidate wins.
+ visible = { series: s, bar, dataIndex, extent }
+ }
+ }
+ if (!visible) {
+ return null
+ }
+ const nextSmallerExtent = allExtents.reduce((max, ext) => (ext < visible!.extent && ext > max ? ext : max), 0)
+ return { series: visible.series, bar: visible.bar, dataIndex: visible.dataIndex, nextSmallerExtent }
+}
diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
index ecc34f27ec1c..739c40a31c5f 100644
--- a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
+++ b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
@@ -14,7 +14,7 @@ const MIN_LEFT_MARGIN = 20
const MIN_RIGHT_MARGIN_DUAL_AXIS = 48
const Y_LABEL_RIGHT_PADDING = 12
const X_LABEL_EDGE_PADDING = 4
-const X_AXIS_TITLE_MARGIN = 22
+export const X_AXIS_TITLE_MARGIN = 22
const Y_AXIS_TITLE_MARGIN = 24
interface UseChartMarginsOptions {
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index 96a07abb4b9c..0d71107921a6 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -226,6 +226,11 @@ export interface BarChartConfig extends ChartConfig {
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 }
+ /** Horizontal bar charts only — minimum px per row. When many rows would otherwise crush
+ * into an unreadable strip, the chart expands its container height so each row has at
+ * least this much vertical space (label height + breathing room). Defaults to `24`.
+ * Pass `0` to opt out. */
+ minBandSize?: number
}
export interface LineChartConfig extends ChartConfig {
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
index 0faa03dac48e..f41ae2a507cc 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
@@ -1,9 +1,9 @@
import '@testing-library/jest-dom'
-import { cleanup, screen, waitFor } from '@testing-library/react'
+import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'
import { FEATURE_FLAGS } from 'lib/constants'
-import { setupJsdom, setupSyncRaf } from 'lib/hog-charts/testing'
+import { dimensions, setupJsdom, setupSyncRaf } from 'lib/hog-charts/testing'
import { NodeKind } from '~/queries/schema/schema-general'
import { buildTrendsQuery, chart, getHogChart, personsModal, renderInsight } from '~/test/insight-testing'
@@ -354,6 +354,33 @@ describe('TrendsBarChart (ActionsBarValue)', () => {
expect(seriesArg.day).toBeUndefined()
})
+ it('tooltip on a breakdown shows that breakdown row with its own value', async () => {
+ // Regression: aggregated tooltip used to read the visible series's value at
+ // ctx.dataIndex, a sparse-zero cell, so the row showed `0` (or the wrong row).
+ renderInsight({
+ query: aggregatedBar({
+ series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],
+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },
+ }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+ await screen.findByRole('img', { name: /chart with 5 data series/i }, { timeout: 5000 })
+
+ // Spike has aggregated_value 11 — largest, so it's the topmost row in DESC layout.
+ const canvas = screen.getByRole('img', { name: /chart with/i })
+ const wrapper = canvas.parentElement!
+ fireEvent.mouseMove(wrapper, {
+ clientX: dimensions.plotLeft + 10,
+ clientY: dimensions.plotTop + 10,
+ })
+
+ const tooltip = chart.getTooltip()
+ expect(tooltip).not.toBeNull()
+ const rowText = tooltip!.textContent ?? ''
+ expect(rowText).toContain('Spike')
+ expect(rowText).toContain('11')
+ })
+
it('renders InsightEmptyState when every aggregated_value is zero', async () => {
renderInsight({
query: aggregatedBar({
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index c56c2cd467d1..d4b036bd0bcb 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -113,7 +113,7 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
)
: !!indexedResults[0].data && indexedResults.some((r: IndexedTrendResult) => r.count !== 0))
- const { series, labels } = useMemo(() => {
+ const { series, labels, displayLabels } = useMemo(() => {
if (isAggregated) {
return buildTrendsBarAggregatedSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {
getColor: getTrendsColor,
@@ -126,7 +126,11 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
getHidden: getTrendsHidden,
buildMeta: buildTrendsSeriesMeta,
})
- return { series: timeSeries, labels: currentPeriodResult?.labels ?? EMPTY_LABELS }
+ return {
+ series: timeSeries,
+ labels: currentPeriodResult?.labels ?? EMPTY_LABELS,
+ displayLabels: undefined,
+ }
}, [isAggregated, indexedResults, getTrendsColor, getTrendsHidden, currentPeriodResult?.labels])
const valueLabelFormatter = useCallback(
@@ -180,19 +184,39 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
[trendsFilter, isPercentStackView, baseCurrency]
)
- const aggregatedConfig: BarChartConfig = useMemo(
- () => ({
+ const aggregatedConfig: BarChartConfig = useMemo(() => {
+ // Band keys are synthetic per-series; render the human label via the categorical-axis
+ // formatter and skip repeats so band-shared breakdown rows don't double-paint.
+ let xTickFormatter: BarChartConfig['xTickFormatter']
+ if (displayLabels && labels) {
+ const firstIndexOf = new Map<string, number>()
+ labels.forEach((l, i) => {
+ if (!firstIndexOf.has(l)) {
+ firstIndexOf.set(l, i)
+ }
+ })
+ xTickFormatter = (label: string, i: number) =>
+ firstIndexOf.get(label) === i ? (displayLabels[i] ?? null) : null
+ }
+ return {
showGrid: true,
tooltip: AGGREGATED_TOOLTIP_CONFIG,
yScaleType: yAxisScaleType === 'log10' ? 'log' : 'linear',
axisOrientation: 'horizontal',
barLayout: 'stacked',
yTickFormatter: aggregatedYTickFormatter,
+ xTickFormatter,
xAxisLabel: trendsFilter?.xAxisLabel,
yAxisLabel: trendsFilter?.yAxisLabel,
- }),
- [yAxisScaleType, aggregatedYTickFormatter, trendsFilter?.xAxisLabel, trendsFilter?.yAxisLabel]
- )
+ }
+ }, [
+ yAxisScaleType,
+ aggregatedYTickFormatter,
+ trendsFilter?.xAxisLabel,
+ trendsFilter?.yAxisLabel,
+ displayLabels,
+ labels,
+ ])
const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal
@@ -242,14 +266,11 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
const renderTooltip = useCallback(
(ctx: TooltipContext<TrendsSeriesMeta>) => {
- // Sparse-stacked: drop sibling series with data=0 at this band so the tooltip shows one row.
+ // BarTooltip already put the cursor-visible segment at seriesData[0] — keep just that.
const tooltipCtx: TooltipContext<TrendsSeriesMeta> = isAggregated
? {
...ctx,
- seriesData: ctx.seriesData.filter((entry) => {
- const raw = entry.series.data[ctx.dataIndex]
- return typeof raw === 'number' && raw !== 0
- }),
+ seriesData: ctx.seriesData.slice(0, 1),
}
: ctx
const onRowClick = canHandleClick
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
index d5b86110f8a0..4d370aa32efb 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
@@ -72,14 +72,45 @@ describe('buildTrendsBarAggregatedSeries', () => {
...overrides,
})
- it('returns labels aligned with results, in the same order', () => {
+ it('returns display labels aligned with results, in the same order; band labels stay unique', () => {
const results = [
mkResult({ id: 'a', label: 'A', aggregated_value: 1 }),
mkResult({ id: 'b', label: 'B', aggregated_value: 2 }),
mkResult({ id: 'c', label: 'C', aggregated_value: 3 }),
]
- const { labels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })
- expect(labels).toEqual(['A', 'B', 'C'])
+ const { labels, displayLabels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })
+ expect(displayLabels).toEqual(['A', 'B', 'C'])
+ expect(new Set(labels).size).toBe(labels.length)
+ })
+
+ it('splits same-label results into separate bands when they come from different series (no breakdown)', () => {
+ // Four trends series of the same event surface label="$pageview" each but have
+ // distinct action.order — they should not collapse onto one band.
+ const results = [0, 1, 2, 3].map((order) =>
+ mkResult({ id: `r${order}`, label: '$pageview', action: { order } })
+ )
+ const { labels, displayLabels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })
+ expect(displayLabels).toEqual(['$pageview', '$pageview', '$pageview', '$pageview'])
+ expect(new Set(labels).size).toBe(4)
+ })
+
+ it('groups same-label breakdown rows of one series onto one band (overlap layout preserved)', () => {
+ // Formula+breakdown shape: each formula carries a top-level `order`; breakdown rows of
+ // the same formula share it, so they share a band and the overlap-on-top visual holds.
+ const spec: [string, number][] = [
+ ['Binary Size', 0],
+ ['Binary Size', 0],
+ ['Binary Size', 0],
+ ['Embedded Assets', 1],
+ ['Embedded Assets', 1],
+ ['Runtime & Code', 2],
+ ['Runtime & Code', 2],
+ ]
+ const results = spec.map(([label, order], i) => mkResult({ id: `r${i}`, label, order }))
+ const { labels, displayLabels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })
+ expect(displayLabels).toEqual(spec.map(([label]) => label))
+ // 7 results, but only 3 distinct band slots — one per formula.
+ expect(new Set(labels).size).toBe(3)
})
it('places each aggregated_value at the index matching its own band — zero everywhere else', () => {
@@ -113,7 +144,7 @@ describe('buildTrendsBarAggregatedSeries', () => {
it.each([
{
- name: 'suffixes labels with compare_label so compare-against-previous rows get distinct bands',
+ name: 'suffixes display labels with compare_label so compare-against-previous rows render distinctly',
results: [
{ id: 'a', label: 'Microsoft Edge', compare_label: 'current', aggregated_value: 100 },
{ id: 'b', label: 'Microsoft Edge', compare_label: 'previous', aggregated_value: 80 },
@@ -122,7 +153,7 @@ describe('buildTrendsBarAggregatedSeries', () => {
expected: ['Microsoft Edge - current', 'Microsoft Edge - previous', 'Safari - current'],
},
{
- name: 'leaves labels unchanged when compare_label is absent',
+ name: 'leaves display labels unchanged when compare_label is absent',
results: [
{ id: 'a', label: 'Chrome', aggregated_value: 1 },
{ id: 'b', label: 'Safari', aggregated_value: 2 },
@@ -130,9 +161,11 @@ describe('buildTrendsBarAggregatedSeries', () => {
expected: ['Chrome', 'Safari'],
},
])('$name', ({ results, expected }) => {
- const { labels } = buildTrendsBarAggregatedSeries(results.map(mkResult), { getColor: () => RED })
- expect(labels).toEqual(expected)
- // No duplicates — every band gets a unique d3 domain key.
+ const { labels, displayLabels } = buildTrendsBarAggregatedSeries(results.map(mkResult), {
+ getColor: () => RED,
+ })
+ expect(displayLabels).toEqual(expected)
+ // Distinct display labels → distinct band keys after the series-id suffix.
expect(new Set(labels).size).toBe(labels.length)
})
@@ -142,11 +175,11 @@ describe('buildTrendsBarAggregatedSeries', () => {
mkResult({ id: 'b', label: 'B', aggregated_value: 2 }),
mkResult({ id: 'c', label: 'C', aggregated_value: 3 }),
]
- const { series, labels } = buildTrendsBarAggregatedSeries(results, {
+ const { series, displayLabels } = buildTrendsBarAggregatedSeries(results, {
getColor: () => RED,
getHidden: (_r, i) => i === 1,
})
- expect(labels).toEqual(['A', 'C'])
+ expect(displayLabels).toEqual(['A', 'C'])
expect(series).toHaveLength(2)
expect(series[0].data).toEqual([1, 0])
expect(series[1].data).toEqual([0, 3])
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
index 280af74ee1ef..aea6bf0090d7 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
@@ -19,6 +19,8 @@ export interface TrendsBarResultLike {
compare?: boolean
compare_label?: string | null
action?: { order?: number } | null
+ // Formula rows carry a top-level `order` instead of `action.order`.
+ order?: number | null
breakdown_value?: unknown
filter?: unknown
}
@@ -96,21 +98,29 @@ export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesCon
}
}
+/** Separator between display label and series id in synthetic band keys. */
+const BAND_KEY_SEP = '\u001f'
+
// Sparse-stacked: hog-charts BarChart allows one color per series, so we emit N series with
// data=0 except at their own band — d3.stack reduces this to one visible segment per band.
// Trade-off: only the last series gets rounded-corner caps.
export function buildTrendsBarAggregatedSeries<R extends TrendsBarResultLike, M = unknown>(
results: R[],
opts: BuildTrendsBarSeriesOpts<R, M>
-): { series: Series<M>[]; labels: string[] } {
+): { series: Series<M>[]; labels: string[]; displayLabels: string[] } {
// Hidden results are dropped entirely — keeping them as `excluded` series would leave
// a phantom band on the category axis with no bar.
const visible = opts.getHidden ? results.filter((r, i) => !opts.getHidden!(r, i)) : results
- // d3.scaleBand collapses duplicate domain entries — suffix compare rows so each gets its own band.
- const labels = visible.map((r) => {
+ const displayLabels = visible.map((r) => {
const base = r.label ?? ''
return r.compare_label ? `${base} - ${r.compare_label}` : base
})
+ // Suffix the band key with the series identity so duplicate display labels from
+ // different series get distinct bands (breakdowns of one series still share a band).
+ const labels = visible.map((r, i) => {
+ const seriesId = r.action?.order ?? r.order ?? 0
+ return `${displayLabels[i]}${BAND_KEY_SEP}${seriesId}`
+ })
const n = visible.length
const series = visible.map((r, index) => {
const data = new Array<number>(n).fill(0)
@@ -120,5 +130,5 @@ export function buildTrendsBarAggregatedSeries<R extends TrendsBarResultLike, M
}
return buildMainTrendsBarSeries(r, index, opts, data)
})
- return { series, labels }
+ return { series, labels, displayLabels }
}