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(insights): switch trends bar chart to TimeSeriesBarChart (#58028)

Sam Pennington7cad3f0f174e
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 65cf2dfc5864..699ee5c68a9f 100644
--- a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx
+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx
@@ -6,12 +6,12 @@ import { buildTheme } from 'lib/charts/utils/theme'
import {
BarChart,
buildYTickFormatter,
- createXAxisTickCallback,
DEFAULT_Y_AXIS_ID,
ReferenceLines,
+ TimeSeriesBarChart,
ValueLabels,
} from 'lib/hog-charts'
-import type { BarChartConfig, PointClickData, TooltipContext } from 'lib/hog-charts'
+import type { BarChartConfig, PointClickData, TimeSeriesBarChartConfig, TooltipContext } from 'lib/hog-charts'
import { formatPercentStackAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -34,7 +34,11 @@ import { trendsFilterToYFormatterConfig } from '../shared/trendsAxisFormat'
import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
import { TrendsTooltip } from '../shared/TrendsTooltip'
import { handleTrendsBarAggregatedChartClick } from './handleTrendsBarAggregatedChartClick'
-import { buildTrendsBarAggregatedSeries, buildTrendsBarTimeSeries } from './trendsBarChartTransforms'
+import {
+ buildTrendsBarAggregatedSeries,
+ buildTrendsBarTimeSeries,
+ buildTrendsBarTimeSeriesConfig,
+} from './trendsBarChartTransforms'
interface TrendsBarChartProps {
context?: QueryContext<InsightVizNode>
@@ -42,6 +46,7 @@ interface TrendsBarChartProps {
}
const EMPTY_LABELS: string[] = []
+const TOOLTIP_CONFIG = { pinnable: true, placement: 'top' as const }
const buildBarMeta = (r: IndexedTrendResult): TrendsSeriesMeta => ({
action: r.action,
@@ -136,33 +141,56 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
return { series: timeSeries, labels: currentPeriodResult?.labels ?? EMPTY_LABELS }
}, [isAggregated, indexedResults, getTrendsColor, getTrendsHidden, currentPeriodResult?.labels])
- const xTickFormatter = useMemo(() => {
- if (isAggregated) {
- return undefined
- }
- return createXAxisTickCallback({
- interval: interval ?? 'day',
- allDays: currentPeriodResult?.days ?? [],
+ const valueLabelFormatter = useCallback(
+ (value: number) => formatPercentStackAxisValue(trendsFilter, value, isPercentStackView, baseCurrency),
+ [trendsFilter, isPercentStackView, baseCurrency]
+ )
+
+ const timeSeriesConfig: TimeSeriesBarChartConfig = useMemo(
+ () =>
+ buildTrendsBarTimeSeriesConfig({
+ trendsFilter,
+ baseCurrency,
+ isPercentStackView,
+ isGrouped,
+ yAxisScaleType,
+ interval,
+ timezone,
+ allDays: currentPeriodResult?.days ?? [],
+ goalLines,
+ valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,
+ tooltip: TOOLTIP_CONFIG,
+ }),
+ [
+ trendsFilter,
+ baseCurrency,
+ isPercentStackView,
+ isGrouped,
+ yAxisScaleType,
+ interval,
timezone,
- })
- }, [isAggregated, interval, currentPeriodResult?.days, timezone])
+ currentPeriodResult?.days,
+ goalLines,
+ showValuesOnSeries,
+ valueLabelFormatter,
+ ]
+ )
- const yTickFormatter = useMemo(
+ const aggregatedYTickFormatter = useMemo(
() => buildYTickFormatter(trendsFilterToYFormatterConfig(trendsFilter, isPercentStackView, baseCurrency)),
[trendsFilter, isPercentStackView, baseCurrency]
)
- const chartConfig: BarChartConfig = useMemo(
+ const aggregatedConfig: BarChartConfig = useMemo(
() => ({
showGrid: true,
- tooltip: { pinnable: true, placement: 'top' },
+ tooltip: TOOLTIP_CONFIG,
yScaleType: yAxisScaleType === 'log10' ? 'log' : 'linear',
- axisOrientation: isAggregated ? 'horizontal' : 'vertical',
- barLayout: isPercentStackView ? 'percent' : isGrouped ? 'grouped' : 'stacked',
- xTickFormatter,
- yTickFormatter,
+ axisOrientation: 'horizontal',
+ barLayout: 'stacked',
+ yTickFormatter: aggregatedYTickFormatter,
}),
- [yAxisScaleType, isAggregated, isGrouped, isPercentStackView, xTickFormatter, yTickFormatter]
+ [yAxisScaleType, aggregatedYTickFormatter]
)
const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal
@@ -191,16 +219,9 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
]
)
- const valueLabelFormatter = useCallback(
- (value: number) => formatPercentStackAxisValue(trendsFilter, value, isPercentStackView, baseCurrency),
- [trendsFilter, isPercentStackView, baseCurrency]
- )
-
- const overlayAxisOrientation: 'vertical' | 'horizontal' = isAggregated ? 'horizontal' : 'vertical'
-
- const referenceLines = useMemo(
- () => goalLinesToReferenceLines(goalLines, series, overlayAxisOrientation),
- [goalLines, series, overlayAxisOrientation]
+ const aggregatedReferenceLines = useMemo(
+ () => (isAggregated ? goalLinesToReferenceLines(goalLines, series, 'horizontal') : []),
+ [isAggregated, goalLines, series]
)
// Bar charts don't yet expose multi-axis configuration, so all series live on the
@@ -280,9 +301,39 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
}
+ if (isAggregated) {
+ return (
+ <BarChart<TrendsSeriesMeta>
+ series={series}
+ labels={labels}
+ config={aggregatedConfig}
+ theme={theme}
+ tooltip={renderTooltip}
+ onPointClick={canHandleClick ? onPointClick : undefined}
+ className="BarGraph"
+ dataAttr="trend-bar-value-graph"
+ onError={handleChartError}
+ >
+ <ReferenceLines lines={aggregatedReferenceLines} />
+ {insight.id && (
+ <TrendsAlertOverlays
+ insightId={insight.id}
+ insightProps={insightProps}
+ indexedResults={indexedResults}
+ getColor={getTrendsColor}
+ getYAxisId={getYAxisId}
+ isHidden={getTrendsHidden}
+ axisOrientation="horizontal"
+ />
+ )}
+ {showValuesOnSeries && <ValueLabels valueFormatter={valueLabelFormatter} />}
+ </BarChart>
+ )
+ }
+
// 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 showAnnotations = !inSharedMode
const annotationsDates = currentPeriodResult?.days ?? []
// In compare-against-previous grouped layouts each band holds two bars (previous, current).
// Anchor each period's annotations on its matching bar so they line up with what they describe.
@@ -294,18 +345,17 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
const annotationsPreviousDates = previousPeriodResult?.days
return (
- <BarChart<TrendsSeriesMeta>
+ <TimeSeriesBarChart<TrendsSeriesMeta>
series={series}
labels={labels}
- config={chartConfig}
+ config={timeSeriesConfig}
theme={theme}
tooltip={renderTooltip}
onPointClick={canHandleClick ? onPointClick : undefined}
className="BarGraph"
- dataAttr={isAggregated ? 'trend-bar-value-graph' : 'trend-bar-graph'}
+ dataAttr="trend-bar-graph"
onError={handleChartError}
>
- <ReferenceLines lines={referenceLines} />
{insight.id && (
<TrendsAlertOverlays
insightId={insight.id}
@@ -314,10 +364,8 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
getColor={getTrendsColor}
getYAxisId={getYAxisId}
isHidden={getTrendsHidden}
- axisOrientation={overlayAxisOrientation}
/>
)}
- {showValuesOnSeries && <ValueLabels valueFormatter={valueLabelFormatter} />}
{showAnnotations && (
<AnnotationsLayer
insightNumericId={insight.id || 'new'}
@@ -327,6 +375,6 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
previousSeriesKey={previousSeriesKey}
/>
)}
- </BarChart>
+ </TimeSeriesBarChart>
)
}
diff --git a/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.test.ts b/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.test.ts
index 4302a66e1615..924f5e0db67d 100644
--- a/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.test.ts
+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.test.ts
@@ -1,8 +1,11 @@
import { hexToRGBA } from 'lib/utils'
+import type { CurrencyCode, GoalLine as SchemaGoalLine, TrendsFilter } from '~/queries/schema/schema-general'
+
import {
buildTrendsBarAggregatedSeries,
buildTrendsBarTimeSeries,
+ buildTrendsBarTimeSeriesConfig,
type TrendsBarResultLike,
} from './trendsBarChartTransforms'
@@ -124,3 +127,83 @@ describe('buildTrendsBarAggregatedSeries', () => {
expect(series[1].data).toEqual([0, 3])
})
})
+
+describe('buildTrendsBarTimeSeriesConfig', () => {
+ it.each([
+ { isPercentStackView: false, isGrouped: false, expected: 'stacked' },
+ { isPercentStackView: false, isGrouped: true, expected: 'grouped' },
+ { isPercentStackView: true, isGrouped: false, expected: 'percent' },
+ { isPercentStackView: true, isGrouped: true, expected: 'percent' },
+ ])(
+ 'maps isPercentStackView=$isPercentStackView / isGrouped=$isGrouped to barLayout=$expected',
+ ({ isPercentStackView, isGrouped, expected }) => {
+ const cfg = buildTrendsBarTimeSeriesConfig({ isPercentStackView, isGrouped })
+ expect(cfg.barLayout).toBe(expected)
+ }
+ )
+
+ it.each([
+ {
+ name: 'builds the xAxis from interval/timezone/allDays',
+ input: { interval: 'day' as const, timezone: 'UTC', allDays: ['2024-06-10', '2024-06-11'] },
+ expected: { timezone: 'UTC', interval: 'day', allDays: ['2024-06-10', '2024-06-11'] },
+ },
+ {
+ name: 'defaults interval to "day" and allDays to empty when omitted',
+ input: {},
+ expected: { timezone: undefined, interval: 'day', allDays: [] },
+ },
+ ])('$name', ({ input, expected }) => {
+ const cfg = buildTrendsBarTimeSeriesConfig({ isPercentStackView: false, isGrouped: false, ...input })
+ expect(cfg.xAxis).toEqual(expected)
+ })
+
+ it('forwards the y-axis from buildTrendsYAxisConfig with showGrid: true', () => {
+ const trendsFilter: TrendsFilter = { aggregationAxisFormat: 'duration', aggregationAxisPrefix: '~' }
+ const cfg = buildTrendsBarTimeSeriesConfig({
+ isPercentStackView: false,
+ isGrouped: false,
+ trendsFilter,
+ baseCurrency: 'USD' as CurrencyCode,
+ yAxisScaleType: 'log10',
+ })
+ expect(cfg.yAxis).toMatchObject({
+ format: 'duration',
+ prefix: '~',
+ currency: 'USD',
+ scale: 'log',
+ showGrid: true,
+ })
+ })
+
+ it('forces percentage format when isPercentStackView is true', () => {
+ const cfg = buildTrendsBarTimeSeriesConfig({
+ isPercentStackView: true,
+ isGrouped: false,
+ trendsFilter: { aggregationAxisFormat: 'currency' },
+ })
+ expect(cfg.yAxis?.format).toBe('percentage')
+ })
+
+ it('maps schema goal lines through the shared adapter', () => {
+ const goalLines: SchemaGoalLine[] = [{ value: 50, label: 'Target' }]
+ const cfg = buildTrendsBarTimeSeriesConfig({
+ isPercentStackView: false,
+ isGrouped: false,
+ goalLines,
+ })
+ expect(cfg.goalLines).toEqual([expect.objectContaining({ value: 50, label: 'Target' })])
+ })
+
+ it('passes valueLabels and tooltip through unchanged', () => {
+ const formatter = (v: number): string => `~${v}`
+ const cfg = buildTrendsBarTimeSeriesConfig({
+ isPercentStackView: false,
+ isGrouped: false,
+ valueLabels: { formatter },
+ tooltip: { pinnable: true, placement: 'top' },
+ })
+ expect(cfg.valueLabels).toEqual({ formatter })
+ expect(cfg.tooltip).toEqual({ pinnable: true, placement: 'top' })
+ })
+})
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 abbb86b1344c..285a9a64d23c 100644
--- a/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.ts
+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/trendsBarChartTransforms.ts
@@ -1,6 +1,11 @@
-import type { Series } from 'lib/hog-charts'
+import type { Series, TimeSeriesBarChartConfig } from 'lib/hog-charts'
import { hexToRGBA } from 'lib/utils'
+import type { CurrencyCode, GoalLine as SchemaGoalLine, TrendsFilter } from '~/queries/schema/schema-general'
+import type { IntervalType } from '~/types'
+
+import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'
+import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'
import { COMPARE_PREVIOUS_DIM_OPACITY } from '../trendsAdapterConstants'
// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.
@@ -50,6 +55,40 @@ export function buildTrendsBarTimeSeries<R extends TrendsBarResultLike, M = unkn
return results.map((r, index) => buildMainTrendsBarSeries(r, index, opts, r.data))
}
+export interface BuildTrendsBarTimeSeriesConfigOpts {
+ trendsFilter?: TrendsFilter | null
+ baseCurrency?: CurrencyCode
+ isPercentStackView: boolean
+ isGrouped: boolean
+ yAxisScaleType?: string | null
+ interval?: IntervalType | null
+ timezone?: string
+ allDays?: string[]
+ goalLines?: SchemaGoalLine[] | null
+ valueLabels?: TimeSeriesBarChartConfig['valueLabels']
+ tooltip?: TimeSeriesBarChartConfig['tooltip']
+}
+
+export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesConfigOpts): TimeSeriesBarChartConfig {
+ const yAxis = buildTrendsYAxisConfig(opts.trendsFilter, opts.isPercentStackView, opts.baseCurrency, {
+ yAxisScaleType: opts.yAxisScaleType,
+ showGrid: true,
+ })
+ const goalLineConfigs = schemaGoalLinesToConfigs(opts.goalLines)
+ return {
+ xAxis: {
+ timezone: opts.timezone,
+ interval: opts.interval ?? 'day',
+ allDays: opts.allDays ?? [],
+ },
+ yAxis,
+ valueLabels: opts.valueLabels,
+ goalLines: goalLineConfigs,
+ barLayout: opts.isPercentStackView ? 'percent' : opts.isGrouped ? 'grouped' : 'stacked',
+ tooltip: opts.tooltip,
+ }
+}
+
// 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.