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): wire bar overlays + route grouped bars (#57492)

Sam Penningtonf7b42d03e69a
diff --git a/frontend/src/lib/hog-charts/charts/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart.tsx
index 0dd2ebd256e4..2cc3f7483e64 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart.tsx
@@ -67,8 +67,6 @@ function BarChartInner<Meta = unknown>({
yScaleType = 'linear',
showGrid = false,
barLayout = 'stacked',
- bandPadding = 0.2,
- groupPadding = 0.1,
barCornerRadius = 4,
axisOrientation = 'vertical',
} = config ?? {}
@@ -128,8 +126,6 @@ function BarChartInner<Meta = unknown>({
scaleType: yScaleType,
barLayout,
axisOrientation,
- bandPadding,
- groupPadding,
stackedSeries,
})
@@ -152,7 +148,7 @@ function BarChartInner<Meta = unknown>({
_private: barChartPrivate,
}
},
- [yScaleType, barLayout, axisOrientation, bandPadding, groupPadding, stackedData, isHorizontal]
+ [yScaleType, barLayout, axisOrientation, stackedData, isHorizontal]
)
const drawStatic = useCallback(
diff --git a/frontend/src/lib/hog-charts/core/bar-layout.ts b/frontend/src/lib/hog-charts/core/bar-layout.ts
index 0343dabb95bd..d8dd23db1323 100644
--- a/frontend/src/lib/hog-charts/core/bar-layout.ts
+++ b/frontend/src/lib/hog-charts/core/bar-layout.ts
@@ -1,18 +1,13 @@
import type { BarRect, BarRoundedCorners } from './canvas-renderer'
import type { BarScaleSet, StackedBand } from './scales'
-import type { ChartScales, Series } from './types'
+import type { Series } from './types'
-/** Brand for the BarChart `ChartScales._private` slot — populated by BarChart, narrowed
- * by its draw callbacks and by overlays that detect bar-chart presence (ValueLabels). */
+/** Brand for the BarChart `ChartScales._private` slot — populated by BarChart and
+ * narrowed by its draw callbacks. */
export interface BarChartPrivate {
__barChart: BarScaleSet
}
-export function getBarChartPrivate(scales: ChartScales): BarChartPrivate | undefined {
- const slot = scales._private as BarChartPrivate | undefined
- return slot && '__barChart' in slot ? slot : undefined
-}
-
export type SeriesBarLayout = (BarRect | null)[]
/** Cap is the side away from the value-axis baseline; pass `shouldRoundCap: false` for stacked
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index 0f60d25e8960..7015650ea61a 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -171,8 +171,6 @@ export interface TooltipConfig {
export interface BarChartConfig extends ChartConfig {
/** Defaults to `stacked`. */
barLayout?: 'stacked' | 'grouped' | 'percent'
- bandPadding?: number
- groupPadding?: number
/** Stacked bars only round the topmost segment. */
barCornerRadius?: number
}
diff --git a/frontend/src/lib/hog-charts/overlays/ReferenceLine.tsx b/frontend/src/lib/hog-charts/overlays/ReferenceLine.tsx
index e3056110f3f6..6192137be086 100644
--- a/frontend/src/lib/hog-charts/overlays/ReferenceLine.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ReferenceLine.tsx
@@ -41,6 +41,10 @@ export interface ReferenceLineProps {
variant?: ReferenceLineVariant
/** Which y-axis this line references. Only used for horizontal lines. Defaults to the primary axis. */
yAxisId?: string
+ /** Chart axis orientation. When `'horizontal'`, a `'horizontal'`-orientation reference
+ * line at a numeric value is drawn as a vertical stripe at `scales.y(value)` — matching
+ * the value axis of horizontal bar charts. Defaults to `'vertical'`. */
+ axisOrientation?: ReferenceLineOrientation
}
interface ResolvedStyle {
@@ -84,7 +88,7 @@ export function ReferenceLines({ lines }: { lines: ReferenceLineProps[] }): Reac
* type narrowing, scale lookup, and bounds check, then hands pre-computed styles to
* {@link ReferenceLineView}. */
export function ReferenceLine(props: ReferenceLineProps): React.ReactElement | null {
- const { orientation = 'horizontal', variant = 'goal', style } = props
+ const { orientation = 'horizontal', variant = 'goal', style, axisOrientation = 'vertical' } = props
const resolved = useMemo(
() => resolveStyle(variant, style),
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -101,9 +105,13 @@ export function ReferenceLine(props: ReferenceLineProps): React.ReactElement | n
}
if (orientation === 'horizontal') {
- return typeof props.value === 'number' ? (
- <HorizontalReferenceLine y={props.value} yAxisId={props.yAxisId} {...common} />
- ) : null
+ if (typeof props.value !== 'number') {
+ return null
+ }
+ if (axisOrientation === 'horizontal') {
+ return <HorizontalAxisValueReferenceLine value={props.value} {...common} />
+ }
+ return <HorizontalReferenceLine y={props.value} yAxisId={props.yAxisId} {...common} />
}
return typeof props.value === 'string' ? <VerticalReferenceLine xLabel={props.value} {...common} /> : null
}
@@ -174,22 +182,33 @@ function HorizontalReferenceLine({
)
}
-function VerticalReferenceLine({
- xLabel,
+// Renders a vertical stripe at a resolved x-pixel — used by both the categorical-x
+// reference line (string xLabel) and the horizontal-axis-chart numeric variant
+// (scales.y(value) returns an x-pixel in horizontal bar charts).
+//
+// `fillBefore` / `fillAfter` are direction-neutral: callers translate their own
+// fillSide enum into these so we don't have to know whether the half-plane is
+// "left/right" (categorical) or "below/above value threshold" (horizontal-axis).
+function VerticalStripe({
+ x,
resolved,
- fillSide,
+ fillBefore,
+ fillAfter,
fillColor,
fillOpacity,
label,
labelPosition,
-}: ResolvedProps & { xLabel: string }): React.ReactElement | null {
- const { scales, dimensions } = useChartLayout()
+}: Omit<ResolvedProps, 'fillSide'> & {
+ x: number
+ fillBefore: boolean
+ fillAfter: boolean
+}): React.ReactElement | null {
+ const { dimensions } = useChartLayout()
const { plotLeft, plotTop, plotWidth, plotHeight, height: containerHeight } = dimensions
const plotRight = plotLeft + plotWidth
const plotBottom = plotTop + plotHeight
- const x = scales.x(xLabel)
- if (x == null || !isFinite(x) || x < plotLeft || x > plotRight) {
+ if (!isFinite(x) || x < plotLeft || x > plotRight) {
return null
}
@@ -211,9 +230,9 @@ function VerticalReferenceLine({
}
let fillRect: React.CSSProperties | null = null
- if (fillSide === 'left') {
+ if (fillBefore) {
fillRect = { left: plotLeft, top: plotTop, width: x - plotLeft, height: plotHeight }
- } else if (fillSide === 'right') {
+ } else if (fillAfter) {
fillRect = { left: x, top: plotTop, width: plotRight - x, height: plotHeight }
}
@@ -229,6 +248,38 @@ function VerticalReferenceLine({
)
}
+function VerticalReferenceLine({
+ xLabel,
+ fillSide,
+ ...rest
+}: ResolvedProps & { xLabel: string }): React.ReactElement | null {
+ const { scales } = useChartLayout()
+ const x = scales.x(xLabel)
+ if (x == null) {
+ return null
+ }
+ return <VerticalStripe x={x} fillBefore={fillSide === 'left'} fillAfter={fillSide === 'right'} {...rest} />
+}
+
+// Horizontal-axis chart variant: numeric value, mapped through scales.y because
+// in horizontal bar charts scales.y is the value scale producing x-pixels.
+// `'above'` (value above the threshold) → right half-plane, `'below'` → left.
+function HorizontalAxisValueReferenceLine({
+ value,
+ fillSide,
+ ...rest
+}: ResolvedProps & { value: number }): React.ReactElement | null {
+ const { scales } = useChartLayout()
+ return (
+ <VerticalStripe
+ x={scales.y(value)}
+ fillBefore={fillSide === 'below'}
+ fillAfter={fillSide === 'above'}
+ {...rest}
+ />
+ )
+}
+
/** The shared shell: optional filled half-plane, the stroked line, and an optional label.
* Sub-components compute the pixel geometry; this just paints it. */
function ReferenceLineView({
diff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
index 6d87ce83969e..d35973d71102 100644
--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
@@ -125,35 +125,6 @@ describe('ValueLabels', () => {
})
})
- it('skips a series with more points than maxPointsPerSeries', () => {
- const longData = Array.from({ length: 150 }, (_, i) => i + 1)
- const longLabels = longData.map((_, i) => `L${i}`)
- const longXPositions: Record<string, number> = {}
- longData.forEach((_, i) => {
- longXPositions[`L${i}`] = 60 + (i / (longData.length - 1)) * 640
- })
- const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: longData }]
- const ctx = makeContext(series, {
- labels: longLabels,
- scales: {
- x: (label: string) => longXPositions[label],
- y: yScale,
- yTicks: () => [0, 50, 100],
- },
- })
- const { container } = renderInChart(ctx, <ValueLabels />)
- expect(labelDivs(container)).toHaveLength(0)
- })
-
- it('honours a custom maxPointsPerSeries override', () => {
- const data = Array.from({ length: 6 }, (_, i) => 10 + i * 10)
- const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data }]
- // default (100) renders all; override to 3 should render none
- const ctx = makeContext(series)
- const { container } = renderInChart(ctx, <ValueLabels maxPointsPerSeries={3} />)
- expect(labelDivs(container)).toHaveLength(0)
- })
-
it('drops overlapping labels via greedy collision avoidance', () => {
// Two points at the same x: only one should survive.
const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [50, 50] }]
@@ -276,15 +247,6 @@ describe('ValueLabels', () => {
})
describe('stack-total mode', () => {
- it('honours maxPointsPerSeries against the number of bands', () => {
- const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [10, 20, 30, 40, 50] }]
- const { container } = renderInChart(
- makeContext(series),
- <ValueLabels mode="stack-total" maxPointsPerSeries={3} />
- )
- expect(labelDivs(container)).toHaveLength(0)
- })
-
it('skips mixed-sign bands (no single visual stack apex)', () => {
const series: ResolvedSeries[] = [
{ key: 'a', label: 'A', color: '#a00', data: [30, 30] },
@@ -310,33 +272,6 @@ describe('ValueLabels', () => {
})
})
- describe('minBarSize', () => {
- const barPrivate = { __barChart: { band: () => 0, value: () => 0 } as unknown }
- const barScales = { x: xScale, y: yScale, yTicks: () => [0, 50, 100], _private: barPrivate }
-
- it.each<[string, number[], string[], { minBarSize?: number; bar?: boolean; mode?: 'stack-total' }]>([
- ['filters narrow segments by default on bar charts', [1, 2, 50, 1, 2], ['50'], { bar: true }],
- ['minBarSize=0 keeps everything', [1, 50], ['1', '50'], { minBarSize: 0, bar: true }],
- ['ignored on non-bar charts', [1, 2], ['1', '2'], {}],
- ])('%s', (_name, data, expected, { minBarSize, bar }) => {
- const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data }]
- const labels = data.length === 5 ? LABELS : ['Mon', 'Tue']
- const ctx = makeContext(series, bar ? { labels, scales: barScales } : { labels })
- const { container } = renderInChart(ctx, <ValueLabels minBarSize={minBarSize} />)
- expect(labelDivs(container).map((d) => d.textContent)).toEqual(expected)
- })
-
- it('drops bands whose stack-total size is below minBarSize', () => {
- const series: ResolvedSeries[] = [
- { key: 'a', label: 'A', color: '#a00', data: [1, 50] },
- { key: 'b', label: 'B', color: '#0a0', data: [1, 5] },
- ]
- const ctx = makeContext(series, { labels: ['Mon', 'Tue'], scales: barScales })
- const divs = labelDivs(renderInChart(ctx, <ValueLabels mode="stack-total" />).container)
- expect(divs.map((d) => d.textContent)).toEqual(['55'])
- })
- })
-
it('isPercent on context is informational — consumers supply their own formatter', () => {
const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [0.25, 0.5, 0.75] }]
const ctx = makeContext(series, { isPercent: true, labels: ['Mon', 'Tue', 'Wed'] })
diff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
index 3133b4ace0ee..b381678167c8 100644
--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
@@ -1,6 +1,5 @@
import React, { useMemo } from 'react'
-import { getBarChartPrivate } from '../core/bar-layout'
import { useChartLayout } from '../core/chart-context'
import { DEFAULT_Y_AXIS_ID } from '../core/types'
import type { ChartScales, ResolvedSeries, ResolveValueFn } from '../core/types'
@@ -11,17 +10,13 @@ export interface ValueLabelsProps {
/** `seriesIndex` is `-1` for stack-total labels. */
valueFormatter?: (value: number, seriesIndex: number, dataIndex: number) => string
minGap?: number
- maxPointsPerSeries?: number
mode?: ValueLabelsMode
- /** Bar charts only; CSS pixels. Defaults to 16. */
- minBarSize?: number
}
const LABEL_FONT =
'600 12px -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif'
const LABEL_HEIGHT = 22
const STACK_TOTAL_KEY = '__stack_total__'
-const DEFAULT_MIN_BAR_SIZE = 16
let measureCtx: CanvasRenderingContext2D | null = null
function getMeasureCtx(): CanvasRenderingContext2D | null {
@@ -57,11 +52,8 @@ interface BuildCandidatesArgs {
scales: ChartScales
resolveValue: ResolveValueFn
valueFormatter: NonNullable<ValueLabelsProps['valueFormatter']>
- maxPointsPerSeries: number
isHorizontal: boolean
mode: ValueLabelsMode
- minBarSize: number
- isBarChart: boolean
isPercent: boolean
}
@@ -122,9 +114,9 @@ function bandTotal(visible: ResolvedSeries[], dIdx: number): number | null {
}
function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2D | null): Candidate[] {
- const { series, labels, scales, valueFormatter, isHorizontal, isBarChart, minBarSize, isPercent } = args
+ const { series, labels, scales, valueFormatter, isHorizontal, isPercent } = args
const out: Candidate[] = []
- if (isPercent || labels.length > args.maxPointsPerSeries) {
+ if (isPercent) {
return out
}
const visible = series.filter((s) => !s.visibility?.excluded && !s.visibility?.fromValueLabels)
@@ -134,7 +126,6 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
const topSeries = visible[visible.length - 1]
const yScale = resolveYScale(topSeries, scales)
const topColor = topSeries.color
- const baseline = isBarChart && minBarSize > 0 ? yScale(0) : NaN
for (let dIdx = 0; dIdx < labels.length; dIdx++) {
const total = bandTotal(visible, dIdx)
@@ -146,9 +137,6 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
if (categoricalCoord == null || !isFinite(categoricalCoord) || !isFinite(valueCoord)) {
continue
}
- if (isFinite(baseline) && Math.abs(valueCoord - baseline) < minBarSize) {
- continue
- }
pushCandidate(
out,
ctx,
@@ -166,14 +154,12 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
}
function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2D | null): Candidate[] {
- const { series, labels, scales, resolveValue, valueFormatter, isHorizontal, isBarChart, minBarSize, isPercent } =
- args
+ const { series, labels, scales, resolveValue, valueFormatter, isHorizontal } = args
const out: Candidate[] = []
- const filterNarrow = isBarChart && minBarSize > 0 && !isPercent
for (let sIdx = 0; sIdx < series.length; sIdx++) {
const s = series[sIdx]
- if (s.visibility?.excluded || s.visibility?.fromValueLabels || s.data.length > args.maxPointsPerSeries) {
+ if (s.visibility?.excluded || s.visibility?.fromValueLabels) {
continue
}
const yScale = resolveYScale(s, scales)
@@ -191,12 +177,6 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
if (categoricalCoord == null || !isFinite(categoricalCoord) || !isFinite(valueCoord)) {
continue
}
- if (filterNarrow) {
- const segmentBottom = yScale(yValue - rawValue)
- if (isFinite(segmentBottom) && Math.abs(valueCoord - segmentBottom) < minBarSize) {
- continue
- }
- }
pushCandidate(
out,
ctx,
@@ -311,13 +291,10 @@ function transformFor(c: Candidate, isHorizontal: boolean): string {
export function ValueLabels({
valueFormatter,
minGap = 4,
- maxPointsPerSeries = 100,
mode = 'per-segment',
- minBarSize = DEFAULT_MIN_BAR_SIZE,
}: ValueLabelsProps): React.ReactElement | null {
const { series, scales, labels, theme, resolveValue, axisOrientation, isPercent } = useChartLayout()
const isHorizontal = axisOrientation === 'horizontal'
- const isBarChart = !!getBarChartPrivate(scales)
const formatter = valueFormatter ?? defaultLocaleFormatter
@@ -330,30 +307,14 @@ export function ValueLabels({
scales,
resolveValue,
valueFormatter: formatter,
- maxPointsPerSeries,
isHorizontal,
mode,
- minBarSize,
- isBarChart,
isPercent,
}),
minGap,
isHorizontal
),
- [
- series,
- labels,
- scales,
- resolveValue,
- formatter,
- minGap,
- maxPointsPerSeries,
- isHorizontal,
- mode,
- minBarSize,
- isBarChart,
- isPercent,
- ]
+ [series, labels, scales, resolveValue, formatter, minGap, isHorizontal, mode, isPercent]
)
if (visible.length === 0) {
diff --git a/frontend/src/scenes/trends/Trends.tsx b/frontend/src/scenes/trends/Trends.tsx
index df4485c2710c..5737fbc896b2 100644
--- a/frontend/src/scenes/trends/Trends.tsx
+++ b/frontend/src/scenes/trends/Trends.tsx
@@ -43,16 +43,8 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
const showPersonsModal = insightLogicShowPersonsModal && !inSharedMode
const { featureFlags } = useValues(featureFlagLogic)
- const {
- display,
- series,
- breakdownFilter,
- trendsFilter,
- hasBreakdownMore,
- breakdownValuesLoading,
- isLifecycle,
- isStickiness,
- } = useValues(trendsDataLogic(insightProps))
+ const { display, series, breakdownFilter, hasBreakdownMore, breakdownValuesLoading, isLifecycle, isStickiness } =
+ useValues(trendsDataLogic(insightProps))
const { updateBreakdownFilter } = useActions(trendsDataLogic(insightProps))
const commonProps = {
@@ -62,14 +54,8 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
inSharedMode,
}
- // TrendsBarChart does not yet wire up showValuesOnSeries, goal lines, alert
- // thresholds, or annotations — fall back to legacy when the insight needs them.
- const canRouteThroughHogChartsBar =
- featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_BAR] &&
- !isLifecycle &&
- !isStickiness &&
- !trendsFilter?.showValuesOnSeries &&
- !trendsFilter?.goalLines?.length
+ const showHogChartsBar =
+ featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_BAR] && !isLifecycle && !isStickiness
const renderViz = (): JSX.Element | undefined => {
if (
@@ -84,8 +70,8 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
return <ActionsLineGraph {...commonProps} />
}
if (display === ChartDisplayType.ActionsBar || display === ChartDisplayType.ActionsUnstackedBar) {
- if (canRouteThroughHogChartsBar && display === ChartDisplayType.ActionsBar) {
- return <TrendsBarChart context={context} />
+ if (showHogChartsBar) {
+ return <TrendsBarChart context={context} inSharedMode={inSharedMode} />
}
return <ActionsLineGraph {...commonProps} />
}
@@ -107,8 +93,8 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
return <ActionsPie {...commonProps} />
}
if (display === ChartDisplayType.ActionsBarValue) {
- if (canRouteThroughHogChartsBar) {
- return <TrendsBarChart context={context} />
+ if (showHogChartsBar) {
+ return <TrendsBarChart context={context} inSharedMode={inSharedMode} />
}
return <ActionsHorizontalBar {...commonProps} />
}
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.tsx
index d73176d1cbc8..19fe32f4b620 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
@@ -6,8 +6,9 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { setupJsdom } from 'lib/hog-charts/testing'
import { NodeKind } from '~/queries/schema/schema-general'
-import { buildTrendsQuery, chart, personsModal, renderInsight } from '~/test/insight-testing'
-import { ChartDisplayType } from '~/types'
+import { buildTrendsQuery, chart, getHogChart, personsModal, renderInsight } from '~/test/insight-testing'
+import { buildAnnotation } from '~/test/insight-testing/test-data'
+import { AnnotationScope, ChartDisplayType } from '~/types'
let cleanupJsdom: () => void
@@ -188,26 +189,95 @@ describe('TrendsBarChart (ActionsBarValue)', () => {
})
})
-describe('TrendsBarChart gate', () => {
- it.each([
- { name: 'showValuesOnSeries', filter: { display: ChartDisplayType.ActionsBar, showValuesOnSeries: true } },
- {
- name: 'goalLines',
- filter: {
- display: ChartDisplayType.ActionsBar,
- goalLines: [{ label: 'Target', value: 150, displayIfCrossed: true }],
- },
- },
- ])('falls back to the legacy renderer when the insight needs $name', async ({ filter }) => {
+describe('TrendsBarChart (ActionsUnstackedBar)', () => {
+ const groupedBar = (extra?: Parameters<typeof buildTrendsQuery>[0]): ReturnType<typeof buildTrendsQuery> =>
+ buildTrendsQuery({ trendsFilter: { display: ChartDisplayType.ActionsUnstackedBar }, ...extra })
+
+ it('routes grouped bar insights through the hog-charts adapter', async () => {
+ renderInsight({ query: groupedBar(), featureFlags: HOG_CHARTS_FLAG })
+
+ await waitFor(() => {
+ expect(screen.getByTestId('trend-bar-graph')).toBeInTheDocument()
+ })
+ })
+
+ it('renders one band per series in grouped layout', async () => {
renderInsight({
- query: buildTrendsQuery({ trendsFilter: filter }),
+ query: groupedBar({
+ series: [
+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },
+ { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },
+ ],
+ }),
featureFlags: HOG_CHARTS_FLAG,
})
await waitFor(() => {
- // hog-charts BarChart sets data-attr="trend-bar-graph"; legacy ActionsLineGraph does not.
- expect(screen.queryByTestId('trend-bar-graph')).not.toBeInTheDocument()
- expect(screen.queryByTestId('trend-bar-value-graph')).not.toBeInTheDocument()
+ expect(screen.getByRole('img', { name: /chart with 2 data series/i })).toBeInTheDocument()
})
})
})
+
+describe('TrendsBarChart overlays', () => {
+ it('renders value labels when showValuesOnSeries is enabled', async () => {
+ renderInsight({
+ query: buildTrendsQuery({
+ trendsFilter: { display: ChartDisplayType.ActionsBar, showValuesOnSeries: true },
+ }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+
+ await screen.findByRole('img', { name: /chart with/i })
+ await waitFor(() => {
+ expect(getHogChart().valueLabels().length).toBeGreaterThan(0)
+ })
+ const labels = getHogChart()
+ .valueLabels()
+ .map((l) => l.text)
+ // Pageview series peaks at 210 — it should appear among the rendered labels.
+ expect(labels).toContain('210')
+ })
+
+ it('renders an annotation badge when an annotation exists', async () => {
+ renderInsight({
+ query: buildTrendsQuery({ trendsFilter: { display: ChartDisplayType.ActionsBar } }),
+ mocks: {
+ annotations: [
+ buildAnnotation({
+ scope: AnnotationScope.Project,
+ content: 'Hedgehog spotted',
+ date_marker: '2024-06-12T12:00:00Z',
+ }),
+ ],
+ },
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+
+ await screen.findByRole('img', { name: /chart with/i })
+ await waitFor(() => {
+ expect(getHogChart().annotationBadges().length).toBeGreaterThan(0)
+ })
+ })
+
+ // For ActionsBarValue (horizontal aggregated), axisOrientation='horizontal' flips the
+ // line geometry to a vertical stripe at the value-axis x-pixel.
+ it.each<{ display: ChartDisplayType; value: number; expectedOrientation: 'horizontal' | 'vertical' }>([
+ { display: ChartDisplayType.ActionsBar, value: 150, expectedOrientation: 'horizontal' },
+ { display: ChartDisplayType.ActionsBarValue, value: 100, expectedOrientation: 'vertical' },
+ ])(
+ 'renders a goal line with $expectedOrientation orientation for $display',
+ async ({ display, value, expectedOrientation }) => {
+ renderInsight({
+ query: buildTrendsQuery({
+ trendsFilter: { display, goalLines: [{ label: 'Target', value, displayIfCrossed: true }] },
+ }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+
+ await screen.findByRole('img', { name: /chart with/i })
+ const lines = getHogChart().referenceLines()
+ expect(lines.map((l) => l.label)).toEqual(['Target'])
+ expect(lines[0].orientation).toBe(expectedOrientation)
+ }
+ )
+})
diff --git a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx
index c6aeabce512d..f65fbdc71dee 100644
--- a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx
+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx
@@ -3,7 +3,14 @@ import posthog from 'posthog-js'
import { useCallback, useMemo, type ErrorInfo } from 'react'
import { buildTheme } from 'lib/charts/utils/theme'
-import { BarChart, buildYTickFormatter, createXAxisTickCallback, ValueLabels } from 'lib/hog-charts'
+import {
+ BarChart,
+ buildYTickFormatter,
+ createXAxisTickCallback,
+ DEFAULT_Y_AXIS_ID,
+ ReferenceLines,
+ ValueLabels,
+} from 'lib/hog-charts'
import type { BarChartConfig, PointClickData, TooltipContext } from 'lib/hog-charts'
import { formatPercentStackAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
@@ -20,6 +27,9 @@ import { openPersonsModal } from '../../persons-modal/PersonsModal'
import { trendsDataLogic } from '../../trendsDataLogic'
import type { IndexedTrendResult } from '../../types'
import { handleTrendsChartClick, type TrendsChartClickDeps } from '../handleTrendsChartClick'
+import { AnnotationsLayer } from '../trends-line-chart/AnnotationsLayer'
+import { goalLinesToReferenceLines } from '../trends-line-chart/goalLinesAdapter'
+import { TrendsAlertOverlays } from '../trends-line-chart/TrendsAlertOverlays'
import { trendsFilterToYFormatterConfig } from '../trends-line-chart/trendsAxisFormat'
import type { TrendsSeriesMeta } from '../trends-line-chart/trendsSeriesMeta'
import { TrendsTooltip } from '../trends-line-chart/TrendsTooltip'
@@ -28,6 +38,7 @@ import { buildTrendsBarAggregatedSeries, buildTrendsBarTimeSeries } from './tren
interface TrendsBarChartProps {
context?: QueryContext<InsightVizNode>
+ inSharedMode?: boolean
}
const EMPTY_LABELS: string[] = []
@@ -67,9 +78,9 @@ const handleChartError = (error: Error, info: ErrorInfo): void => {
})
}
-export function TrendsBarChart({ context }: TrendsBarChartProps): JSX.Element | null {
+export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChartProps): JSX.Element | null {
const theme = useMemo(() => buildTheme(), [])
- const { insightProps } = useValues(insightLogic)
+ const { insightProps, insight } = useValues(insightLogic)
const {
indexedResults,
@@ -89,12 +100,14 @@ export function TrendsBarChart({ context }: TrendsBarChartProps): JSX.Element |
querySource,
getTrendsColor,
getTrendsHidden,
+ goalLines,
showValuesOnSeries,
} = useValues(trendsDataLogic(insightProps))
const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)
const { aggregationLabel } = useValues(groupsModel)
const isAggregated = display === ChartDisplayType.ActionsBarValue
+ const isGrouped = display === ChartDisplayType.ActionsUnstackedBar
const isPercentStackView = !isAggregated && !!showPercentStackView && !!supportsPercentStackView
const resolvedGroupTypeLabel = resolveGroupTypeLabel(labelGroupType, aggregationLabel, context?.groupTypeLabel)
@@ -145,11 +158,11 @@ export function TrendsBarChart({ context }: TrendsBarChartProps): JSX.Element |
tooltip: { pinnable: true, placement: 'top' },
yScaleType: yAxisScaleType === 'log10' ? 'log' : 'linear',
axisOrientation: isAggregated ? 'horizontal' : 'vertical',
- barLayout: isPercentStackView ? 'percent' : 'stacked',
+ barLayout: isPercentStackView ? 'percent' : isGrouped ? 'grouped' : 'stacked',
xTickFormatter,
yTickFormatter,
}),
- [yAxisScaleType, isAggregated, isPercentStackView, xTickFormatter, yTickFormatter]
+ [yAxisScaleType, isAggregated, isGrouped, isPercentStackView, xTickFormatter, yTickFormatter]
)
const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal
@@ -183,6 +196,17 @@ export function TrendsBarChart({ context }: TrendsBarChartProps): JSX.Element |
[trendsFilter, isPercentStackView, baseCurrency]
)
+ const overlayAxisOrientation: 'vertical' | 'horizontal' = isAggregated ? 'horizontal' : 'vertical'
+
+ const referenceLines = useMemo(
+ () => goalLinesToReferenceLines(goalLines, series, overlayAxisOrientation),
+ [goalLines, series, overlayAxisOrientation]
+ )
+
+ // Bar charts don't yet expose multi-axis configuration, so all series live on the
+ // primary axis — alert anomaly markers always read the default scale.
+ const getYAxisId = useCallback(() => DEFAULT_Y_AXIS_ID, [])
+
const onPointClick = useCallback(
(clickData: PointClickData) => {
if (isAggregated) {
@@ -256,6 +280,11 @@ export function TrendsBarChart({ context }: TrendsBarChartProps): JSX.Element |
return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
}
+ // Annotations are date-anchored, so they only make sense for the time-series bar
+ // layouts (vertical bars). The horizontal aggregated layout has categorical labels.
+ const showAnnotations = !inSharedMode && !isAggregated
+ const annotationsDates = currentPeriodResult?.days ?? []
+
return (
<BarChart<TrendsSeriesMeta>
series={series}
@@ -268,7 +297,26 @@ export function TrendsBarChart({ context }: TrendsBarChartProps): JSX.Element |
dataAttr={isAggregated ? 'trend-bar-value-graph' : 'trend-bar-graph'}
onError={handleChartError}
>
+ <ReferenceLines lines={referenceLines} />
+ {insight.id && (
+ <TrendsAlertOverlays
+ insightId={insight.id}
+ insightProps={insightProps}
+ indexedResults={indexedResults}
+ getColor={getTrendsColor}
+ getYAxisId={getYAxisId}
+ isHidden={getTrendsHidden}
+ axisOrientation={overlayAxisOrientation}
+ />
+ )}
{showValuesOnSeries && <ValueLabels valueFormatter={valueLabelFormatter} />}
+ {showAnnotations && (
+ <AnnotationsLayer
+ insightNumericId={insight.id || 'new'}
+ dates={annotationsDates}
+ xTickFormatter={xTickFormatter}
+ />
+ )}
</BarChart>
)
}
diff --git a/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.ts b/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.ts
index e06089cc5cdd..abbb86b1344c 100644
--- a/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.ts
+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.ts
@@ -1,7 +1,7 @@
import type { Series } from 'lib/hog-charts'
import { hexToRGBA } from 'lib/utils'
-const COMPARE_PREVIOUS_DIM_OPACITY = 0.5
+import { COMPARE_PREVIOUS_DIM_OPACITY } from '../trendsAdapterConstants'
// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.
export interface TrendsBarResultLike {
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsAlertOverlays.tsx b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsAlertOverlays.tsx
index 74de066813a8..5f5ce4e476fd 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsAlertOverlays.tsx
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsAlertOverlays.tsx
@@ -17,6 +17,9 @@ interface TrendsAlertOverlaysProps {
getColor: (r: IndexedTrendResult) => string
isHidden: (r: IndexedTrendResult) => boolean
getYAxisId: (r: IndexedTrendResult) => string
+ /** Chart axis orientation. When `'horizontal'`, threshold lines flip to vertical
+ * stripes at the value-axis x-pixel. Defaults to `'vertical'`. */
+ axisOrientation?: 'vertical' | 'horizontal'
}
/** Renders alert threshold lines and anomaly point markers on top of the trends chart.
@@ -32,12 +35,16 @@ export function TrendsAlertOverlays({
getColor,
isHidden,
getYAxisId,
+ axisOrientation,
}: TrendsAlertOverlaysProps): React.ReactElement | null {
const { alertThresholdLines, alertAnomalyPoints } = useValues(
insightAlertsLogic({ insightId, insightLogicProps: insightProps })
)
- const referenceLines = useMemo(() => alertThresholdsToReferenceLines(alertThresholdLines), [alertThresholdLines])
+ const referenceLines = useMemo(
+ () => alertThresholdsToReferenceLines(alertThresholdLines, axisOrientation),
+ [alertThresholdLines, axisOrientation]
+ )
const anomalyMarkers = useMemo(
() => buildAnomalyMarkers(alertAnomalyPoints, indexedResults, getColor, getYAxisId, isHidden),
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.ts b/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.ts
index b4075e5013c7..087d886dc9c8 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.ts
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.ts
@@ -28,28 +28,40 @@ function schemaToReferenceLine(line: SchemaGoalLine, variant: 'goal' | 'alert'):
}
}
+function withAxisOrientation(
+ refs: ReferenceLineProps[],
+ axisOrientation: 'vertical' | 'horizontal' | undefined
+): ReferenceLineProps[] {
+ return axisOrientation === 'horizontal' ? refs.map((r) => ({ ...r, axisOrientation })) : refs
+}
+
/** Map persisted {@link SchemaGoalLine}s to {@link ReferenceLineProps} for the hog-charts
* primitive, preserving the `displayIfCrossed` filter. The filter drops a goal when
* `displayIfCrossed` is explicitly `false` *and* the line sits below the series peak —
- * i.e. the data has already crossed it. */
+ * i.e. the data has already crossed it. Pass `axisOrientation: 'horizontal'` when the
+ * chart's value axis is horizontal (e.g. horizontal bar charts) to flip rendering. */
export function goalLinesToReferenceLines(
goalLines: SchemaGoalLine[] | null | undefined,
- series: Series[]
+ series: Series[],
+ axisOrientation?: 'vertical' | 'horizontal'
): ReferenceLineProps[] {
if (!goalLines?.length) {
return []
}
- return buildGoalLineReferenceLines(goalLines.map(schemaToGoalLineConfig), series)
+ const refs = buildGoalLineReferenceLines(goalLines.map(schemaToGoalLineConfig), series)
+ return withAxisOrientation(refs, axisOrientation)
}
/** Map alert threshold lines (sourced from `insightAlertsLogic.alertThresholdLines`) to
* {@link ReferenceLineProps}. Same shape as goal lines, but rendered with the `alert`
* variant (dashed red) so they read as bounds, not targets. */
export function alertThresholdsToReferenceLines(
- alertThresholdLines: SchemaGoalLine[] | null | undefined
+ alertThresholdLines: SchemaGoalLine[] | null | undefined,
+ axisOrientation?: 'vertical' | 'horizontal'
): ReferenceLineProps[] {
if (!alertThresholdLines?.length) {
return []
}
- return alertThresholdLines.map((line) => schemaToReferenceLine(line, 'alert'))
+ const refs = alertThresholdLines.map((line) => schemaToReferenceLine(line, 'alert'))
+ return withAxisOrientation(refs, axisOrientation)
}
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts
index 83d83594a3ef..ae08fc71581a 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts
@@ -9,8 +9,7 @@ import { hexToRGBA } from 'lib/utils'
import { ChartDisplayType } from '~/types'
-const COMPARE_PREVIOUS_DIM_OPACITY = 0.5
-const TRENDLINE_DIM_OPACITY = 0.5
+import { COMPARE_PREVIOUS_DIM_OPACITY, TRENDLINE_DIM_OPACITY } from '../trendsAdapterConstants'
// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.
export interface TrendsResultLike {
diff --git a/frontend/src/scenes/trends/viz/trendsAdapterConstants.ts b/frontend/src/scenes/trends/viz/trendsAdapterConstants.ts
new file mode 100644
index 000000000000..cc4d50905613
--- /dev/null
+++ b/frontend/src/scenes/trends/viz/trendsAdapterConstants.ts
@@ -0,0 +1,7 @@
+// Shared constants for the trends-line-chart and trends-bar-chart adapters.
+//
+// `COMPARE_PREVIOUS_DIM_OPACITY` dims the previous-period series in compare mode so it
+// reads as the "ghost" series. `TRENDLINE_DIM_OPACITY` dims the regression line so it
+// doesn't visually compete with the raw series.
+export const COMPARE_PREVIOUS_DIM_OPACITY = 0.5
+export const TRENDLINE_DIM_OPACITY = 0.5