: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(insights): extract buildTrendsLineTimeSeriesConfig (#58187)
Sam Penningtonf7eb83d36c5f
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsxindex b748c73eabbd..5aabdfa77766 100644--- a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx+++ b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx@@ -21,12 +21,10 @@ import { trendsDataLogic } from '../../trendsDataLogic'import type { IndexedTrendResult } from '../../types'import { handleTrendsChartClick } from '../handleTrendsChartClick'import { AnnotationsLayer } from '../shared/AnnotationsLayer'-import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'import { TrendsAlertOverlays } from '../shared/TrendsAlertOverlays'-import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'import { TrendsTooltip } from '../shared/TrendsTooltip'-import { buildDerivedConfigs, buildTrendsSeries } from './trendsChartTransforms'+import { buildTrendsLineTimeSeriesConfig, buildTrendsSeries } from './trendsChartTransforms'interface TrendsLineChartProps {context?: QueryContext<InsightVizNode>@@ -123,72 +121,55 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha])- const yAxisConfig = useMemo(- () =>- buildTrendsYAxisConfig(trendsFilter, isPercentStackView, baseCurrency, {- yAxisScaleType,- showGrid: true,- }),- [trendsFilter, isPercentStackView, baseCurrency, yAxisScaleType]- )-- const goalLineConfigs = useMemo(() => schemaGoalLinesToConfigs(goalLines), [goalLines])-const valueLabelFormatter = useCallback((value: number) => formatPercentStackAxisValue(trendsFilter, value, isPercentStackView, baseCurrency),[trendsFilter, isPercentStackView, baseCurrency])- const derivedConfigs = useMemo(+ const chartConfig: TimeSeriesLineChartConfig = useMemo(() =>- buildDerivedConfigs(indexedResults ?? [], {+ buildTrendsLineTimeSeriesConfig({+ results: indexedResults ?? [],+ trendsFilter,+ baseCurrency,+ isPercentStackView,+ isStickiness,+ yAxisScaleType,+ interval,+ timezone,+ allDays: currentPeriodResult?.days ?? [],+ goalLines,+ incompletenessOffsetFromEnd,+ getHidden: getTrendsHidden,showConfidenceIntervals,confidenceLevel,showMovingAverage,movingAverageIntervals,showTrendLines,- isStickiness,- incompletenessOffsetFromEnd,- getHidden: getTrendsHidden,+ valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,+ showCrosshair: true,+ tooltip: TOOLTIP_CONFIG,}),[indexedResults,+ trendsFilter,+ baseCurrency,+ isPercentStackView,+ isStickiness,+ yAxisScaleType,+ interval,+ timezone,+ currentPeriodResult?.days,+ goalLines,+ incompletenessOffsetFromEnd,+ getTrendsHidden,showConfidenceIntervals,confidenceLevel,showMovingAverage,movingAverageIntervals,showTrendLines,- isStickiness,- incompletenessOffsetFromEnd,- getTrendsHidden,- ]- )-- const chartConfig: TimeSeriesLineChartConfig = useMemo(- () => ({- xAxis: {- timezone,- interval: interval ?? 'day',- allDays: currentPeriodResult?.days ?? [],- },- yAxis: yAxisConfig,- valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,- goalLines: goalLineConfigs,- ...derivedConfigs,- percentStackView: isPercentStackView,- showCrosshair: true,- tooltip: TOOLTIP_CONFIG,- }),- [- timezone,- interval,- currentPeriodResult?.days,- yAxisConfig,showValuesOnSeries,valueLabelFormatter,- goalLineConfigs,- derivedConfigs,- isPercentStackView,])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.tsindex 48dcc0552528..0f4aceb64e5d 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,10 +1,13 @@import { DEFAULT_Y_AXIS_ID } from 'lib/hog-charts'+import type { TooltipConfig } from 'lib/hog-charts'+import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'import {buildDerivedConfigs,buildMainTrendsSeries,+ buildTrendsLineTimeSeriesConfig,buildTrendsSeries,computeDashedFromIndex,type TrendsResultLike,@@ -308,4 +311,106 @@ describe('trendsChartTransforms', () => {})})})++ describe('buildTrendsLineTimeSeriesConfig', () => {+ const TOOLTIP: TooltipConfig = { pinnable: true, placement: 'top' }++ const baseOpts = {+ results: [makeResult()],+ isPercentStackView: false,+ } as const++ it('returns the same top-level keys TrendsLineChart spreads today', () => {+ const config = buildTrendsLineTimeSeriesConfig({+ ...baseOpts,+ trendsFilter: null,+ interval: 'day',+ timezone: 'UTC',+ allDays: ['2024-01-01', '2024-01-02'],+ goalLines: [{ label: 'goal', value: 10 }] satisfies SchemaGoalLine[],+ showConfidenceIntervals: true,+ confidenceLevel: 95,+ valueLabels: false,+ showCrosshair: true,+ tooltip: TOOLTIP,+ })++ expect(config.xAxis).toEqual({ timezone: 'UTC', interval: 'day', allDays: ['2024-01-01', '2024-01-02'] })+ expect(config.yAxis).not.toBeUndefined()+ expect(config.valueLabels).toBe(false)+ expect(config.goalLines).toHaveLength(1)+ expect(config.confidenceIntervals).toHaveLength(1)+ expect(config.percentStackView).toBe(false)+ expect(config.showCrosshair).toBe(true)+ expect(config.tooltip).toBe(TOOLTIP)+ })++ it.each([[80], [95], [99]])(+ 'confidenceIntervals match buildDerivedConfigs at confidenceLevel %d',+ (confidenceLevel) => {+ const results = [makeResult({ id: 'a' }), makeResult({ id: 'b', data: [10, 11, 9, 12, 13] })]+ const config = buildTrendsLineTimeSeriesConfig({+ ...baseOpts,+ results,+ showConfidenceIntervals: true,+ confidenceLevel,+ })+ const direct = buildDerivedConfigs(results, {+ showConfidenceIntervals: true,+ confidenceLevel,+ })+ expect(config.confidenceIntervals).toEqual(direct.confidenceIntervals)+ }+ )++ describe('valueLabels', () => {+ it('passes through valueLabels: false unchanged', () => {+ const config = buildTrendsLineTimeSeriesConfig({+ ...baseOpts,+ valueLabels: false,+ })+ expect(config.valueLabels).toBe(false)+ })++ it('passes through an assembled valueLabels object unchanged', () => {+ const formatter = (value: number): string => `${value}!`+ const config = buildTrendsLineTimeSeriesConfig({+ ...baseOpts,+ valueLabels: { formatter },+ })+ expect(config.valueLabels).toEqual({ formatter })+ })+ })++ describe('goalLines', () => {+ it.each<[string, SchemaGoalLine[] | null]>([+ ['null', null],+ ['empty array', []],+ ])('is undefined when goalLines is %s', (_, goalLines) => {+ const config = buildTrendsLineTimeSeriesConfig({+ ...baseOpts,+ goalLines,+ })+ expect(config.goalLines).toBeUndefined()+ })+ })++ it('defaults xAxis.interval to "day" when interval is omitted', () => {+ const config = buildTrendsLineTimeSeriesConfig({ ...baseOpts })+ expect(config.xAxis?.interval).toBe('day')+ })++ it('derives yAxis from buildTrendsYAxisConfig when isPercentStackView is true and passes through tooltip / showCrosshair', () => {+ const config = buildTrendsLineTimeSeriesConfig({+ ...baseOpts,+ isPercentStackView: true,+ tooltip: TOOLTIP,+ showCrosshair: false,+ })+ expect(config.yAxis).toMatchObject({ format: 'percentage', scale: 'linear', showGrid: true })+ expect(config.percentStackView).toBe(true)+ expect(config.tooltip).toBe(TOOLTIP)+ expect(config.showCrosshair).toBe(false)+ })+ })})diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.tsindex 936fea639529..848b69ebb7cd 100644--- a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts+++ b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts@@ -1,8 +1,19 @@import { DEFAULT_Y_AXIS_ID, movingAverageKey } from 'lib/hog-charts'-import type { ConfidenceIntervalConfig, MovingAverageConfig, Series, TrendLineConfig } from 'lib/hog-charts'+import type {+ ConfidenceIntervalConfig,+ MovingAverageConfig,+ Series,+ TimeSeriesLineChartConfig,+ TooltipConfig,+ TrendLineConfig,+} from 'lib/hog-charts'import { ciRanges } from 'lib/statistics'-import { ChartDisplayType } from '~/types'+import type { CurrencyCode, GoalLine as SchemaGoalLine, TrendsFilter } from '~/queries/schema/schema-general'+import { ChartDisplayType, type IntervalType } from '~/types'++import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'+import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.export interface TrendsResultLike {@@ -154,3 +165,63 @@ export function buildDerivedConfigs<R extends TrendsResultLike>(return out}++export interface BuildTrendsLineTimeSeriesConfigOpts<R extends TrendsResultLike> {+ results: readonly R[]+ trendsFilter?: TrendsFilter | null+ baseCurrency?: CurrencyCode+ isPercentStackView: boolean+ isStickiness?: boolean+ yAxisScaleType?: string | null+ interval?: IntervalType | null+ timezone?: string+ allDays?: string[]+ goalLines?: SchemaGoalLine[] | null+ incompletenessOffsetFromEnd?: number+ getHidden?: (r: R) => boolean++ showConfidenceIntervals?: boolean+ confidenceLevel?: number+ showMovingAverage?: boolean+ movingAverageIntervals?: number+ showTrendLines?: boolean++ valueLabels?: TimeSeriesLineChartConfig['valueLabels']++ showCrosshair?: boolean+ tooltip?: TooltipConfig+}++export function buildTrendsLineTimeSeriesConfig<R extends TrendsResultLike>(+ opts: BuildTrendsLineTimeSeriesConfigOpts<R>+): TimeSeriesLineChartConfig {+ const yAxis = buildTrendsYAxisConfig(opts.trendsFilter, opts.isPercentStackView, opts.baseCurrency, {+ yAxisScaleType: opts.yAxisScaleType,+ showGrid: true,+ })+ const goalLineConfigs = schemaGoalLinesToConfigs(opts.goalLines)+ const derivedConfigs = buildDerivedConfigs(opts.results, {+ showConfidenceIntervals: opts.showConfidenceIntervals,+ confidenceLevel: opts.confidenceLevel,+ showMovingAverage: opts.showMovingAverage,+ movingAverageIntervals: opts.movingAverageIntervals,+ showTrendLines: opts.showTrendLines,+ isStickiness: opts.isStickiness,+ incompletenessOffsetFromEnd: opts.incompletenessOffsetFromEnd,+ getHidden: opts.getHidden,+ })+ return {+ xAxis: {+ timezone: opts.timezone,+ interval: opts.interval ?? 'day',+ allDays: opts.allDays ?? [],+ },+ yAxis,+ valueLabels: opts.valueLabels,+ goalLines: goalLineConfigs,+ ...derivedConfigs,+ percentStackView: opts.isPercentStackView,+ showCrosshair: opts.showCrosshair,+ tooltip: opts.tooltip,+ }+}