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.

refactor(trends): drop dead derived-series helpers from trendsChartTransforms (#57672)

Sam Penningtonf004944a6a98
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.test.ts b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.test.ts
index 14c19ac69bf4..1f7e22183942 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.test.ts
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.test.ts
@@ -1,14 +1,9 @@
-import { DEFAULT_Y_AXIS_ID, type Series } from 'lib/hog-charts'
+import { DEFAULT_Y_AXIS_ID } from 'lib/hog-charts'
import { hexToRGBA } from 'lib/utils'
import { ChartDisplayType } from '~/types'
-import {
- buildMainTrendsSeries,
- buildTrendsChartConfig,
- buildTrendsSeries,
- type TrendsResultLike,
-} from './trendsChartTransforms'
+import { buildMainTrendsSeries, buildTrendsSeries, type TrendsResultLike } from './trendsChartTransforms'
const RED = '#ff0000'
@@ -19,8 +14,6 @@ const makeResult = (overrides: Partial<TrendsResultLike> = {}): TrendsResultLike
...overrides,
})
-const lowerDataOf = (s: Series): number[] => (s.fill as { lowerData: number[] }).lowerData
-
describe('trendsChartTransforms', () => {
describe('buildMainTrendsSeries', () => {
it('builds a single main series with no compare and no in-progress tail', () => {
@@ -135,7 +128,7 @@ describe('trendsChartTransforms', () => {
})
describe('buildTrendsSeries', () => {
- it('returns one main series per result when no derived series flags are set', () => {
+ it('returns one main series per result', () => {
const results = [makeResult({ id: 'a' }), makeResult({ id: 'b' })]
const series = buildTrendsSeries(results, { getColor: () => RED })
@@ -149,259 +142,5 @@ describe('trendsChartTransforms', () => {
expect(series.map((s) => s.yAxisId)).toEqual([DEFAULT_Y_AXIS_ID, 'y1', 'y2'])
})
-
- describe('confidence intervals', () => {
- const ciOpts = {
- getColor: (): string => RED,
- showConfidenceIntervals: true,
- confidenceLevel: 95,
- }
-
- it('emits a CI series with key, label, color, yAxisId, and meta from the main series', () => {
- const meta = { breakdown_value: 'a' }
- const series = buildTrendsSeries([makeResult({ id: 7 })], {
- ...ciOpts,
- buildMeta: () => meta,
- })
-
- expect(series).toHaveLength(2)
- expect(series[1]).toMatchObject({
- key: '7__ci',
- label: 'Pageview (CI)',
- color: RED,
- yAxisId: DEFAULT_Y_AXIS_ID,
- meta,
- })
- expect(series[1].data?.length).toBe(5)
- expect(series[1].fill).toMatchObject({ opacity: 0.2 })
- expect(lowerDataOf(series[1]).length).toBe(5)
- })
-
- it('passes confidenceLevel through to ciRanges as a fraction', () => {
- const [s95] = buildTrendsSeries([makeResult()], { ...ciOpts, confidenceLevel: 95 }).slice(1)
- const [s50] = buildTrendsSeries([makeResult()], { ...ciOpts, confidenceLevel: 50 }).slice(1)
-
- expect(lowerDataOf(s95)[0]).not.toBe(lowerDataOf(s50)[0])
- })
-
- it('hides CI series when its main is excluded but keeps it visible from tooltip/value-labels', () => {
- const series = buildTrendsSeries([makeResult()], { ...ciOpts, getHidden: () => true })
-
- expect(series[1].visibility).toEqual({ excluded: true, fromTooltip: true, fromValueLabels: true })
- })
-
- it('omits CI series entirely when showConfidenceIntervals is false', () => {
- const series = buildTrendsSeries([makeResult()], { getColor: () => RED })
- expect(series).toHaveLength(1)
- })
-
- it('defaults confidenceLevel to 95 when undefined', () => {
- const explicit = buildTrendsSeries([makeResult()], { ...ciOpts, confidenceLevel: 95 })[1]
- const defaulted = buildTrendsSeries([makeResult()], {
- getColor: () => RED,
- showConfidenceIntervals: true,
- })[1]
- expect(lowerDataOf(defaulted)).toEqual(lowerDataOf(explicit))
- })
- })
-
- describe('moving average', () => {
- const maOpts = {
- getColor: (): string => RED,
- showMovingAverage: true,
- movingAverageIntervals: 3,
- }
-
- it('emits a moving-average series when data is at least as long as the interval', () => {
- const series = buildTrendsSeries([makeResult({ id: 9, data: [1, 2, 3, 4, 5] })], maOpts)
-
- expect(series).toHaveLength(2)
- expect(series[1]).toMatchObject({
- key: '9-ma',
- label: 'Pageview (Moving avg)',
- color: RED,
- yAxisId: DEFAULT_Y_AXIS_ID,
- stroke: { pattern: [10, 3] },
- visibility: { fromTooltip: true, fromStack: true },
- })
- expect(series[1].data?.length).toBe(5)
- })
-
- it('skips the MA series when data is shorter than the interval', () => {
- const series = buildTrendsSeries([makeResult({ data: [1, 2] })], maOpts)
- expect(series).toHaveLength(1)
- })
-
- it('skips the MA series when movingAverageIntervals is undefined', () => {
- const series = buildTrendsSeries([makeResult()], {
- getColor: () => RED,
- showMovingAverage: true,
- })
- expect(series).toHaveLength(1)
- })
-
- it('skips the MA series when showMovingAverage is false', () => {
- const series = buildTrendsSeries([makeResult()], {
- getColor: () => RED,
- movingAverageIntervals: 3,
- })
- expect(series).toHaveLength(1)
- })
- })
-
- describe('trend lines', () => {
- const tlOpts = { getColor: (): string => RED, showTrendLines: true }
-
- it('emits a raw trend-line series with the result label and dimmed base color', () => {
- const series = buildTrendsSeries([makeResult({ id: 4 })], tlOpts)
-
- expect(series).toHaveLength(2)
- expect(series[1]).toMatchObject({
- key: '4__trendline',
- label: 'Pageview',
- color: hexToRGBA(RED, 0.5),
- yAxisId: DEFAULT_Y_AXIS_ID,
- stroke: { pattern: [1, 3] },
- visibility: { fromTooltip: true, fromValueLabels: true, fromStack: true },
- })
- })
-
- it('uses the un-dimmed base color for the trend-line, independent of compare-previous dimming', () => {
- // Compare across both compare states. Main.color reflects compare-dimming;
- // the trend-line is derived from the un-dimmed baseColor, so it must be
- // identical in both. If the implementation regressed to dimming twice
- // (e.g. used main.color), current[1].color would diverge from previous[1].color.
- const current = buildTrendsSeries([makeResult({ compare: true, compare_label: 'current' })], tlOpts)
- const previous = buildTrendsSeries([makeResult({ compare: true, compare_label: 'previous' })], tlOpts)
-
- expect(current[0].color).not.toBe(previous[0].color)
- expect(current[1].color).toBe(previous[1].color)
- expect(current[1].color).toBe(hexToRGBA(RED, 0.5))
- })
-
- it('fits the trend-line up to dashedFromIndex (excludes the in-progress tail)', () => {
- const data = [0, 0, 0, 0, 0, 100, 100]
- // incompletenessOffsetFromEnd=-2 → dashedFromIndex=5 → fit excludes the 100s.
- const series = buildTrendsSeries([makeResult({ data })], {
- ...tlOpts,
- incompletenessOffsetFromEnd: -2,
- })
- const fitted = series[1].data
- // Slope is zero for the fitted prefix — every fitted value should be ~0.
- expect(fitted?.every((v) => Math.abs(v) < 1e-9)).toBe(true)
- })
-
- it('skips the trend-line when the main series is excluded', () => {
- const series = buildTrendsSeries([makeResult()], { ...tlOpts, getHidden: () => true })
- expect(series).toHaveLength(1)
- })
-
- it('skips the trend-line when showTrendLines is false', () => {
- const series = buildTrendsSeries([makeResult()], { getColor: () => RED })
- expect(series).toHaveLength(1)
- })
- })
-
- describe('moving-average trend line', () => {
- const maTlOpts = {
- getColor: (): string => RED,
- showMovingAverage: true,
- movingAverageIntervals: 3,
- showTrendLines: true,
- }
-
- it('emits an MA trend-line subseries when both MA and trendlines are enabled', () => {
- const series = buildTrendsSeries([makeResult({ id: 2 })], maTlOpts)
- expect(series).toHaveLength(4)
- expect(series.map((s) => s.key)).toEqual(['2', '2-ma', '2-ma__trendline', '2__trendline'])
- })
-
- it('skips the MA trend-line when the main series is excluded (but still keeps the MA itself)', () => {
- const series = buildTrendsSeries([makeResult({ id: 2 })], { ...maTlOpts, getHidden: () => true })
- expect(series.map((s) => s.key)).toEqual(['2', '2-ma'])
- })
-
- it('skips the MA trend-line when MA is gated out by short data', () => {
- const series = buildTrendsSeries([makeResult({ data: [1, 2] })], maTlOpts)
- expect(series.map((s) => s.key)).toEqual(['0', '0__trendline'])
- })
- })
-
- describe('composition', () => {
- it('emits derived series in order [main, CI, MA, MA-trendline, raw-trendline] when all are enabled', () => {
- const series = buildTrendsSeries([makeResult({ id: 'x', data: [1, 2, 3, 4, 5] })], {
- getColor: () => RED,
- showConfidenceIntervals: true,
- confidenceLevel: 95,
- showMovingAverage: true,
- movingAverageIntervals: 3,
- showTrendLines: true,
- })
-
- expect(series.map((s) => s.key)).toEqual(['x', 'x__ci', 'x-ma', 'x-ma__trendline', 'x__trendline'])
- })
-
- it('preserves the result iteration order across multiple results', () => {
- const series = buildTrendsSeries([makeResult({ id: 'a' }), makeResult({ id: 'b' })], {
- getColor: () => RED,
- showTrendLines: true,
- })
- expect(series.map((s) => s.key)).toEqual(['a', 'a__trendline', 'b', 'b__trendline'])
- })
- })
- })
-
- describe('buildTrendsChartConfig', () => {
- it('returns every optional key undefined and yScaleType "linear" when no opts are provided', () => {
- const config = buildTrendsChartConfig({})
- expect(config).toEqual({
- showGrid: undefined,
- showCrosshair: undefined,
- tooltip: undefined,
- yScaleType: 'linear',
- percentStackView: undefined,
- xTickFormatter: undefined,
- yTickFormatter: undefined,
- })
- })
-
- it.each([
- ['log10', 'log'],
- ['linear', 'linear'],
- ['auto', 'linear'],
- [undefined, 'linear'],
- [null, 'linear'],
- ] as const)('translates yAxisScaleType "%s" to hog-charts yScaleType "%s"', (input, expected) => {
- expect(buildTrendsChartConfig({ yAxisScaleType: input }).yScaleType).toBe(expected)
- })
-
- it('builds a tooltip object only when pinnable or placement is set', () => {
- expect(buildTrendsChartConfig({ pinnableTooltip: true, tooltipPlacement: 'top' }).tooltip).toEqual({
- pinnable: true,
- placement: 'top',
- })
- expect(buildTrendsChartConfig({}).tooltip).toBeUndefined()
- })
-
- it('passes through grid, crosshair, percentStackView, and tick formatters', () => {
- const xTickFormatter = (v: string | number): string | null => String(v)
- const yTickFormatter = (v: number): string => `${v}`
-
- expect(
- buildTrendsChartConfig({
- showGrid: true,
- showCrosshair: true,
- isPercentStackView: true,
- xTickFormatter,
- yTickFormatter,
- })
- ).toMatchObject({
- showGrid: true,
- showCrosshair: true,
- percentStackView: true,
- xTickFormatter,
- yTickFormatter,
- })
- })
})
})
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 9fc839fe0f56..2e3558125617 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts
@@ -1,11 +1,5 @@
import { DEFAULT_Y_AXIS_ID } from 'lib/hog-charts'
-import type { LineChartConfig, Series } from 'lib/hog-charts'
-import {
- buildConfidenceIntervalSeries,
- buildMovingAverageSeries,
- buildTrendLineSeries,
-} from 'lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series'
-import { ciRanges } from 'lib/statistics'
+import type { Series } from 'lib/hog-charts'
import { hexToRGBA } from 'lib/utils'
import { ChartDisplayType } from '~/types'
@@ -34,13 +28,6 @@ export interface BuildTrendsSeriesOpts<R extends TrendsResultLike, M = unknown>
getColor: (r: R, index: number) => string
getHidden?: (r: R, index: number) => boolean
buildMeta?: (r: R, index: number) => M
- // Derived series — opt-in. Each block is independent so MCP-side callers
- // can leave them off without unintended overlays.
- showConfidenceIntervals?: boolean
- confidenceLevel?: number
- showMovingAverage?: boolean
- movingAverageIntervals?: number
- showTrendLines?: boolean
}
export interface BuiltTrendsSeries<M> {
@@ -80,113 +67,9 @@ export function buildMainTrendsSeries<R extends TrendsResultLike, M = unknown>(
return { main, baseColor, dashedFromIndex, excluded }
}
-function buildDerivedTrendsSeries<R extends TrendsResultLike, M = unknown>(
- r: R,
- built: BuiltTrendsSeries<M>,
- opts: BuildTrendsSeriesOpts<R, M>
-): Series<M>[] {
- const { main, baseColor, dashedFromIndex, excluded } = built
- const label = r.label ?? ''
- const out: Series<M>[] = []
-
- if (opts.showConfidenceIntervals) {
- const ci = (opts.confidenceLevel ?? 95) / 100
- const [lower, upper] = ciRanges(r.data, ci)
- out.push(
- buildConfidenceIntervalSeries<M>({
- seriesKey: main.key,
- label,
- baseColor: main.color,
- lower,
- upper,
- yAxisId: main.yAxisId,
- meta: main.meta,
- excluded,
- })
- )
- }
-
- let maSeries: Series<M> | undefined
- if (
- opts.showMovingAverage &&
- opts.movingAverageIntervals !== undefined &&
- r.data.length >= opts.movingAverageIntervals
- ) {
- maSeries = buildMovingAverageSeries<M>({
- sourceSeries: main,
- window: opts.movingAverageIntervals,
- label: `${label} (Moving avg)`,
- })
- out.push(maSeries)
- }
-
- if (maSeries && opts.showTrendLines && !excluded) {
- // The MA-derived trendline must use the un-dimmed baseColor so compare-prev
- // dimming doesn't compound with the trendline's own dimming. Pass a
- // synthetic source whose colour is the un-dimmed base.
- out.push(
- buildTrendLineSeries<M>({
- sourceSeries: { ...maSeries, color: baseColor },
- kind: 'linear',
- label: `${label} (Moving avg)`,
- })
- )
- }
-
- if (opts.showTrendLines && !excluded) {
- // Fit excludes the in-progress tail (dashedFromIndex..end) so the flat
- // partial bucket doesn't drag the slope down. Dimmed so the dashed
- // overlay reads as subordinate to the series line — at full intensity
- // the two colors visually compete, especially on a dark background.
- out.push(
- buildTrendLineSeries<M>({
- sourceSeries: { ...main, color: baseColor },
- kind: 'linear',
- label,
- fitUpTo: dashedFromIndex,
- })
- )
- }
-
- return out
-}
-
export function buildTrendsSeries<R extends TrendsResultLike, M = unknown>(
results: R[],
opts: BuildTrendsSeriesOpts<R, M>
): Series<M>[] {
- return results.flatMap((r, index) => {
- const built = buildMainTrendsSeries(r, index, opts)
- return [built.main, ...buildDerivedTrendsSeries(r, built, opts)]
- })
-}
-
-export interface BuildTrendsChartConfigOpts {
- // Anything other than 'log10' is treated as linear.
- yAxisScaleType?: string | null
- isPercentStackView?: boolean
- showCrosshair?: boolean
- showGrid?: boolean
- pinnableTooltip?: boolean
- tooltipPlacement?: 'top' | 'follow-data'
- xTickFormatter?: (value: string | number, index: number) => string | null
- yTickFormatter?: (value: number) => string
-}
-
-// Undefined keys fall through to hog-charts defaults — don't add fallbacks here.
-export function buildTrendsChartConfig(opts: BuildTrendsChartConfigOpts): LineChartConfig {
- const tooltip =
- opts.pinnableTooltip !== undefined || opts.tooltipPlacement !== undefined
- ? { pinnable: opts.pinnableTooltip, placement: opts.tooltipPlacement }
- : undefined
- const yScaleType: 'linear' | 'log' = opts.yAxisScaleType === 'log10' ? 'log' : 'linear'
- return {
- showGrid: opts.showGrid,
- showCrosshair: opts.showCrosshair,
- tooltip,
- yScaleType,
- percentStackView: opts.isPercentStackView,
- xTickFormatter: opts.xTickFormatter,
- yTickFormatter: opts.yTickFormatter,
- }
+ return results.map((r, index) => buildMainTrendsSeries(r, index, opts).main)
}