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.

feat(hog-charts): add barTrack option to BarChart (#59754)

Sam Pennington5b56adf2cf64
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a95843947efe..5ef3ad61f4b7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -488,6 +488,10 @@ snapshots:
hash: v1.k794b7964.78ae65df47f38a1591d7e7ea98143d1d52148505cc30d7aa15e41267ab7069ae.8ZZW5wd0CsmrQSjirpj1kpZjse2ii8F263u0owKxSWM
components-hogcharts-barchart--stacked-mixed-sign--light:
hash: v1.k794b7964.f85427c86ddf715de891c55aa499119ea88cbb161b2b37e8d4c943e07b6eeb27.UnBe38l0a2kG3Ney_67dJ5zTBSD-qHIUF3JWMBep2-k
+ components-hogcharts-barchart--with-bar-track--dark:
+ hash: v1.k794b7964.49e4f9e7974839dbbb64a6e5e7970eb2b271803e5e8b8146198bd12ad044503e.YL87xuLIFcqnRXLLqk_7gtCJGQyNcd76k2Kda0xhFZs
+ components-hogcharts-barchart--with-bar-track--light:
+ hash: v1.k794b7964.38ac4a98dead12b49e1727bdd93240f6ea0066adff611a97c6c5e3e307fc8e62.Fg389h17t2lWX9lR9CffIAX1jEZRri29prNfW7egOCE
components-hogcharts-barchart--with-reference-line--dark:
hash: v1.k794b7964.b0c3c06250da7f04cb51a3044d2f6f54c9d6508e7aed6473bfd3f86991c9c358.pJc_WoUpP1J_PwVo6h-h_cXVue1gUJnph4-m95Xsd0I
components-hogcharts-barchart--with-reference-line--light:
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.stories.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.stories.tsx
index ded038788711..469ef3ef3102 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.stories.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.stories.tsx
@@ -47,6 +47,18 @@ export const Grouped: Story = {
},
}
+export const WithBarTrack: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const config: BarChartConfig = { barLayout: 'grouped', showGrid: true, barTrack: true, barCornerRadius: 6 }
+ return (
+ <Stage>
+ <BarChart series={THREE_SERIES} labels={DAYS} config={config} theme={theme} />
+ </Stage>
+ )
+ },
+}
+
export const Percent: Story = {
render: () => {
const theme = useReactiveTheme()
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
index 030dd17c5704..c9248a6e9483 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
@@ -1,8 +1,16 @@
import * as d3 from 'd3'
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 { type BarChartPrivate, computeBarAtIndex, computeBarTrackRect, computeSeriesBars } from '../../core/bar-layout'
+import {
+ BAR_TRACK_HOVER_ALPHA,
+ type BarRect,
+ drawBarHighlight,
+ drawBars,
+ drawBarTracks,
+ drawGrid,
+ type DrawContext,
+} from '../../core/canvas-renderer'
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import {
@@ -29,7 +37,7 @@ import type {
import { DEFAULT_Y_AXIS_ID } from '../../core/types'
import { computeVisibleXLabels } from '../../overlays/AxisLabels'
import { BarTooltip } from './BarTooltip'
-import { seriesKeysAtCursor } from './utils/bars-under-cursor'
+import { cursorOutsideBarFillExtent, seriesKeysAtCursor } from './utils/bars-under-cursor'
function bandCenter(scales: BarChartPrivate['__barChart'], label: string): number | undefined {
const start = scales.band(label)
@@ -86,6 +94,7 @@ function BarChartInner<Meta = unknown>({
showGrid = false,
barLayout = 'stacked',
barCornerRadius = 0,
+ barTrack = false,
axisOrientation = 'vertical',
xTickFormatter,
} = config ?? {}
@@ -218,31 +227,39 @@ function BarChartInner<Meta = unknown>({
})
}
- for (const s of coloredSeries) {
- if (s.visibility?.excluded) {
- continue
- }
- const stackedBand = stackedData?.get(s.key)
- const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID
- const isTop = topStackedKeyByAxis.get(axisId) === s.key
- const bars = computeSeriesBars({
- series: s,
- labels: drawLabels,
- scales: d3Scales,
- layout: barLayout,
- isHorizontal,
- stackedBand,
- isTopOfStack: isTop,
+ const seriesBars = coloredSeries
+ .filter((s) => !s.visibility?.excluded)
+ .map((s) => {
+ const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID
+ const bars = computeSeriesBars({
+ series: s,
+ labels: drawLabels,
+ scales: d3Scales,
+ layout: barLayout,
+ isHorizontal,
+ stackedBand: stackedData?.get(s.key),
+ isTopOfStack: topStackedKeyByAxis.get(axisId) === s.key,
+ }).filter((b): b is BarRect => b !== null)
+ return { series: s, bars }
})
- drawBars(
- baseDrawCtx,
- s,
- bars.filter((b): b is BarRect => b !== null),
- barCornerRadius
- )
+
+ // Tracks are a separate pass so a later series' full-height track can't paint
+ // over an earlier series' bar. Track is "share of a whole" semantics — only
+ // meaningful for grouped layouts; in stacked/percent every layer would paint
+ // a full-height track over the same band with the wrong corners.
+ if (barTrack && barLayout === 'grouped') {
+ const [axisStart = 0, axisEnd = 0] = d3Scales.value.range()
+ for (const { series: s, bars } of seriesBars) {
+ const tracks = bars.map((b) => computeBarTrackRect(b, axisStart, axisEnd, isHorizontal))
+ drawBarTracks(baseDrawCtx, s, tracks, barCornerRadius)
+ }
+ }
+
+ for (const { series: s, bars } of seriesBars) {
+ drawBars(baseDrawCtx, s, bars, barCornerRadius)
}
},
- [showGrid, stackedData, barLayout, isHorizontal, topStackedKeyByAxis, barCornerRadius, xTickFormatter]
+ [showGrid, stackedData, barLayout, isHorizontal, topStackedKeyByAxis, barCornerRadius, barTrack, xTickFormatter]
)
const drawHover = useCallback(
@@ -252,6 +269,9 @@ function BarChartInner<Meta = unknown>({
return
}
const hoveredLabel = drawLabels[hoverIndex]
+ // Hoisted out of the per-series loop below — the value-axis range doesn't
+ // depend on which series the cursor is over.
+ const [trackAxisStart = 0, trackAxisEnd = 0] = barTrack ? d3Scales.value.range() : []
// Narrow to bars whose band-axis extent contains the cursor; an empty hit set
// means the cursor is in a gap, so draw nothing.
let hitKeys: Set<string> | null = null
@@ -292,13 +312,41 @@ function BarChartInner<Meta = unknown>({
stackedBand,
isTopOfStack: isTop,
})
- if (bar) {
+ if (!bar) {
+ continue
+ }
+ // Over the track region above the bar: highlight the track instead of the bar.
+ // A translucent series-color fill leaves the opaque bar unchanged but tints
+ // the faint hatched track.
+ if (
+ barTrack &&
+ barLayout === 'grouped' &&
+ hoverPosition &&
+ cursorOutsideBarFillExtent(bar, hoverPosition, isHorizontal)
+ ) {
+ const parsed = d3.color(s.color)
+ // Always translucent — falling back to `s.color` directly would paint
+ // an opaque full-plot-height block if d3 can't parse the series color.
+ let trackColor: string
+ if (parsed) {
+ parsed.opacity = BAR_TRACK_HOVER_ALPHA
+ trackColor = parsed.toString()
+ } else {
+ trackColor = `rgba(0,0,0,${BAR_TRACK_HOVER_ALPHA})`
+ }
+ drawBarHighlight(
+ ctx,
+ computeBarTrackRect(bar, trackAxisStart, trackAxisEnd, isHorizontal),
+ trackColor,
+ barCornerRadius
+ )
+ } else {
const highlightColor = d3.color(s.color)?.darker(0.6).toString() ?? s.color
drawBarHighlight(ctx, bar, highlightColor, barCornerRadius)
}
}
},
- [stackedData, barLayout, isHorizontal, topStackedKeyByAxis, barCornerRadius]
+ [stackedData, barLayout, isHorizontal, topStackedKeyByAxis, barCornerRadius, barTrack]
)
// Show each series's own segment value (resolveValue) but anchor the tooltip/value labels
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.test.ts b/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.test.ts
new file mode 100644
index 000000000000..be80feaf13d6
--- /dev/null
+++ b/frontend/src/lib/hog-charts/charts/BarChart/utils/bars-under-cursor.test.ts
@@ -0,0 +1,24 @@
+import type { BarRect } from '../../../core/canvas-renderer'
+import { 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 }
+
+describe('cursorOutsideBarFillExtent', () => {
+ it.each([
+ { desc: 'above the fill', y: 80, expected: true },
+ { desc: 'on the fill cap', y: 120, expected: false },
+ { desc: 'inside the fill', y: 220, expected: false },
+ { desc: 'below the fill', y: 360, expected: true },
+ ])('vertical bar — cursor $desc is over the track: $expected', ({ y, expected }) => {
+ expect(cursorOutsideBarFillExtent(verticalBar, { x: 110, y }, false)).toBe(expected)
+ })
+
+ it.each([
+ { desc: 'left of the fill', x: 40, expected: true },
+ { desc: 'inside the fill', x: 120, expected: false },
+ { desc: 'right of the fill', x: 300, expected: true },
+ ])('horizontal bar — cursor $desc is over the track: $expected', ({ x, expected }) => {
+ expect(cursorOutsideBarFillExtent(horizontalBar, { x, y: 110 }, true)).toBe(expected)
+ })
+})
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 8be924ecbac0..fedc51bae8b8 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
@@ -18,6 +18,20 @@ export function barContainsPointOnBandAxis(
: point.x >= bar.x && point.x <= bar.x + bar.width
}
+/** True when the cursor is in the bar's band slot but outside its filled value extent —
+ * the strict complement of {@link barContainsPointOnBandAxis} on the value axis. Used
+ * to distinguish track-region hover from bar-region hover. Caller is expected to have
+ * already established band-axis containment. */
+export function cursorOutsideBarFillExtent(
+ bar: BarRect,
+ point: { x: number; y: number },
+ isHorizontal: boolean
+): boolean {
+ return isHorizontal
+ ? point.x < bar.x || point.x > bar.x + bar.width
+ : point.y < bar.y || point.y > bar.y + bar.height
+}
+
export interface SeriesKeysAtCursorArgs {
series: readonly Pick<Series, 'key' | 'visibility' | 'yAxisId' | 'data'>[]
label: string
diff --git a/frontend/src/lib/hog-charts/core/bar-canvas-renderer.test.ts b/frontend/src/lib/hog-charts/core/bar-canvas-renderer.test.ts
index 67624fd7a21e..740cfaae2017 100644
--- a/frontend/src/lib/hog-charts/core/bar-canvas-renderer.test.ts
+++ b/frontend/src/lib/hog-charts/core/bar-canvas-renderer.test.ts
@@ -1,7 +1,14 @@
import * as d3 from 'd3'
import { dimensions, makeSeries } from '../testing'
-import { type BarRect, drawBarHighlight, drawBars, type DrawContext, traceRoundedBarPath } from './canvas-renderer'
+import {
+ type BarRect,
+ drawBarHighlight,
+ drawBars,
+ drawBarTracks,
+ type DrawContext,
+ traceRoundedBarPath,
+} from './canvas-renderer'
function mockCanvasContext(): jest.Mocked<CanvasRenderingContext2D> {
return {
@@ -13,10 +20,13 @@ function mockCanvasContext(): jest.Mocked<CanvasRenderingContext2D> {
fill: jest.fn(),
closePath: jest.fn(),
setLineDash: jest.fn(),
+ save: jest.fn(),
+ restore: jest.fn(),
createPattern: jest.fn(() => ({}) as CanvasPattern),
strokeStyle: '',
fillStyle: '',
lineWidth: 0,
+ globalAlpha: 1,
} as unknown as jest.Mocked<CanvasRenderingContext2D>
}
@@ -240,4 +250,39 @@ describe('hog-charts canvas-renderer (bars)', () => {
expect(ctx.fillStyle).toBe('rgba(1,2,3,0.4)')
})
})
+
+ describe('drawBarTracks', () => {
+ const series = makeSeries({ key: 's', data: [40, 70] })
+
+ it('paints a tinted base and hatched stripes per track', () => {
+ const ctx = mockCanvasContext()
+ const drawCtx = makeDrawContext(ctx, ['a', 'b'])
+ drawBarTracks(drawCtx, series, [bar({ dataIndex: 0 }), bar({ dataIndex: 1, x: 200 })], 6)
+ // Two passes (base + hatch) per track => 2 fills × 2 tracks.
+ expect(ctx.fill).toHaveBeenCalledTimes(4)
+ })
+
+ it('wraps drawing in save/restore so the track alpha does not leak', () => {
+ const ctx = mockCanvasContext()
+ const drawCtx = makeDrawContext(ctx, ['a'])
+ drawBarTracks(drawCtx, series, [bar({ dataIndex: 0 })], 6)
+ expect(ctx.save).toHaveBeenCalledTimes(1)
+ expect(ctx.restore).toHaveBeenCalledTimes(1)
+ })
+
+ it('skips degenerate track rects', () => {
+ const ctx = mockCanvasContext()
+ const drawCtx = makeDrawContext(ctx, ['a'])
+ drawBarTracks(drawCtx, series, [bar({ dataIndex: 0, width: 0 })], 6)
+ expect(ctx.fill).not.toHaveBeenCalled()
+ })
+
+ it('does nothing when there are no tracks', () => {
+ const ctx = mockCanvasContext()
+ const drawCtx = makeDrawContext(ctx, ['a'])
+ drawBarTracks(drawCtx, series, [], 6)
+ expect(ctx.fill).not.toHaveBeenCalled()
+ expect(ctx.save).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/frontend/src/lib/hog-charts/core/bar-layout.test.ts b/frontend/src/lib/hog-charts/core/bar-layout.test.ts
index d21e3435e464..5d577b1b0d6c 100644
--- a/frontend/src/lib/hog-charts/core/bar-layout.test.ts
+++ b/frontend/src/lib/hog-charts/core/bar-layout.test.ts
@@ -1,5 +1,5 @@
import { dimensions, makeSeries } from '../testing'
-import { type ComputeSeriesBarsOptions, computeSeriesBars, cornersFor } from './bar-layout'
+import { type ComputeSeriesBarsOptions, computeBarTrackRect, computeSeriesBars, cornersFor } from './bar-layout'
import type { BarRect } from './canvas-renderer'
import { computeStackData, createBarScales } from './scales'
import type { ChartDimensions } from './types'
@@ -370,4 +370,38 @@ describe('hog-charts bar-layout', () => {
}
})
})
+
+ describe('computeBarTrackRect', () => {
+ const verticalBar: BarRect = {
+ x: 100,
+ y: 120,
+ width: 50,
+ height: 200,
+ corners: { topLeft: true },
+ dataIndex: 2,
+ }
+ const horizontalBar: BarRect = { x: 60, y: 100, width: 140, height: 40, corners: {}, dataIndex: 0 }
+
+ it('stretches a vertical bar across the full value axis, keeping its band slot', () => {
+ expect(computeBarTrackRect(verticalBar, 368, 16, false)).toEqual({
+ x: 100,
+ y: 16,
+ width: 50,
+ height: 352,
+ corners: { topLeft: true },
+ dataIndex: 2,
+ })
+ })
+
+ it('stretches a horizontal bar across the full value axis, keeping its band slot', () => {
+ expect(computeBarTrackRect(horizontalBar, 60, 540, true)).toEqual({
+ x: 60,
+ y: 100,
+ width: 480,
+ height: 40,
+ corners: {},
+ dataIndex: 0,
+ })
+ })
+ })
})
diff --git a/frontend/src/lib/hog-charts/core/bar-layout.ts b/frontend/src/lib/hog-charts/core/bar-layout.ts
index d8dd23db1323..de8d1c031995 100644
--- a/frontend/src/lib/hog-charts/core/bar-layout.ts
+++ b/frontend/src/lib/hog-charts/core/bar-layout.ts
@@ -135,3 +135,27 @@ export function computeBarAtIndex({
const corners = cornersFor(isHorizontal, isPositive, shouldRoundCap)
return makeBarRect(isHorizontal, bandStart, bandWidth, topPixel, bottomPixel, corners, dataIndex)
}
+
+/** The track rect behind a bar — the bar's band slot stretched across the whole value
+ * axis. `axisRangeA`/`axisRangeB` are the two endpoints of the value scale's pixel range
+ * (in either order — for a vertical Y scale d3 returns `[bottomPx, topPx]`). Used by
+ * funnel-style charts to draw and hit-test the faint "remainder to 100%" region. */
+export function computeBarTrackRect(
+ bar: BarRect,
+ axisRangeA: number,
+ axisRangeB: number,
+ isHorizontal: boolean
+): BarRect {
+ const valueMin = Math.min(axisRangeA, axisRangeB)
+ const valueSize = Math.abs(axisRangeB - axisRangeA)
+ return isHorizontal
+ ? {
+ x: valueMin,
+ y: bar.y,
+ width: valueSize,
+ height: bar.height,
+ corners: bar.corners,
+ dataIndex: bar.dataIndex,
+ }
+ : { x: bar.x, y: valueMin, width: bar.width, height: valueSize, corners: bar.corners, dataIndex: bar.dataIndex }
+}
diff --git a/frontend/src/lib/hog-charts/core/canvas-renderer.ts b/frontend/src/lib/hog-charts/core/canvas-renderer.ts
index 68fec0ecc8a5..8276ea52a71a 100644
--- a/frontend/src/lib/hog-charts/core/canvas-renderer.ts
+++ b/frontend/src/lib/hog-charts/core/canvas-renderer.ts
@@ -486,6 +486,48 @@ export function drawBars(
}
}
+// Tracks render as a tinted base under hatched stripes — same construction as the legacy
+// funnel backdrop (`var(--series-color)` behind `repeating-linear-gradient` stripes), so the
+// whole region reads as continuously filled rather than as bare stripes on the background.
+const BAR_TRACK_BASE_ALPHA = 0.14
+const BAR_TRACK_HATCH_ALPHA = 0.18
+/** Translucent overlay drawn over the track on hover. Exported so the chart-type's
+ * hover callback can match the resting track's tuning. */
+export const BAR_TRACK_HOVER_ALPHA = 0.2
+
+function fillTrackRects(ctx: CanvasRenderingContext2D, tracks: BarRect[], cornerRadius: number): void {
+ for (const track of tracks) {
+ ctx.beginPath()
+ traceRoundedBarPath(ctx, track.x, track.y, track.width, track.height, cornerRadius, track.corners)
+ ctx.fill()
+ }
+}
+
+/** Paints each track rect as a tinted base under hatched stripes. Takes laid-out rects
+ * from `computeBarTrackRect`, mirroring `drawBars`. */
+export function drawBarTracks(
+ drawCtx: DrawContext,
+ series: ResolvedSeries,
+ tracks: BarRect[],
+ cornerRadius: number
+): void {
+ const renderableTracks = tracks.filter((t) => t.width > 0 && t.height > 0)
+ if (renderableTracks.length === 0) {
+ return
+ }
+ const { ctx } = drawCtx
+ ctx.save()
+ // Solid base fill — what makes the region differ from the background, even between stripes.
+ ctx.globalAlpha = BAR_TRACK_BASE_ALPHA
+ ctx.fillStyle = series.color
+ fillTrackRects(ctx, renderableTracks, cornerRadius)
+ // Hatched stripes on top.
+ ctx.globalAlpha = BAR_TRACK_HATCH_ALPHA
+ ctx.fillStyle = getHatchPattern(ctx, series.color)
+ fillTrackRects(ctx, renderableTracks, cornerRadius)
+ ctx.restore()
+}
+
/** Translucent fill on the overlay canvas, alpha-composited over the static bar. */
export function drawBarHighlight(
ctx: CanvasRenderingContext2D,
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index 94b84fd047d6..68814b2ec210 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -191,6 +191,11 @@ export interface BarChartConfig extends ChartConfig {
barLayout?: 'stacked' | 'grouped' | 'percent'
/** Stacked bars only round the topmost segment. */
barCornerRadius?: number
+ /** Draw a faint hatched track behind each bar, spanning the full plot height — for
+ * funnel-style charts where every bar is a share of a whole. Only honored when
+ * `barLayout: 'grouped'`; ignored for stacked/percent (the "share of a whole"
+ * semantics don't apply when bars share a band). Defaults to `false`. */
+ barTrack?: boolean
}
export interface LineChartConfig extends ChartConfig {