: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
refactor(trends): switch TrendsLineChart parent to TimeSeriesLineChart (#57642)
Sam Penningtonca8874c25a2d
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsxindex 34e2ab76fa2b..c6ad1ecc9cd4 100644--- a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx+++ b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx@@ -3,15 +3,17 @@ import posthog from 'posthog-js'import { useCallback, useMemo, type ErrorInfo } from 'react'import { buildTheme } from 'lib/charts/utils/theme'-import {- buildYTickFormatter,- createXAxisTickCallback,- DEFAULT_Y_AXIS_ID,- LineChart,- ReferenceLines,- ValueLabels,+import { createXAxisTickCallback, DEFAULT_Y_AXIS_ID, TimeSeriesLineChart } from 'lib/hog-charts'+import type {+ ConfidenceIntervalConfig,+ MovingAverageConfig,+ PointClickData,+ Series,+ TimeSeriesLineChartConfig,+ TooltipContext,+ TrendLineConfig,} from 'lib/hog-charts'-import type { LineChartConfig, PointClickData, Series, TooltipContext } from 'lib/hog-charts'+import { ciRanges } from 'lib/statistics'import { formatPercentStackAxisValue } from 'scenes/insights/aggregationAxisFormat'import { insightLogic } from 'scenes/insights/insightLogic'import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'@@ -28,10 +30,10 @@ import { trendsDataLogic } from '../../trendsDataLogic'import type { IndexedTrendResult } from '../../types'import { handleTrendsChartClick } from '../handleTrendsChartClick'import { AnnotationsLayer } from './AnnotationsLayer'-import { goalLinesToReferenceLines } from './goalLinesAdapter'+import { schemaGoalLinesToConfigs } from './goalLinesAdapter'import { TrendsAlertOverlays } from './TrendsAlertOverlays'-import { trendsFilterToYFormatterConfig } from './trendsAxisFormat'-import { buildTrendsChartConfig, buildTrendsSeries } from './trendsChartTransforms'+import { buildTrendsYAxisConfig } from './trendsAxisFormat'+import { buildTrendsSeries } from './trendsChartTransforms'import type { TrendsSeriesMeta } from './trendsSeriesMeta'import { TrendsTooltip } from './TrendsTooltip'@@ -116,11 +118,6 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaorder: rr.action?.order ?? rr.id,filter: rr.filter,}),- showConfidenceIntervals,- confidenceLevel,- showMovingAverage,- movingAverageIntervals,- showTrendLines,}),[indexedResults,@@ -130,11 +127,6 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaisStickiness,incompletenessOffsetFromEnd,showMultipleYAxes,- showMovingAverage,- movingAverageIntervals,- showTrendLines,- showConfidenceIntervals,- confidenceLevel,])@@ -148,27 +140,106 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha[interval, currentPeriodResult?.days, timezone])- const yTickFormatter = useMemo(- () => buildYTickFormatter(trendsFilterToYFormatterConfig(trendsFilter, isPercentStackView, baseCurrency)),- [trendsFilter, isPercentStackView, baseCurrency]- )-- const chartConfig: LineChartConfig = useMemo(+ const yAxisConfig = useMemo(() =>- buildTrendsChartConfig({+ buildTrendsYAxisConfig(trendsFilter, isPercentStackView, baseCurrency, {yAxisScaleType,- isPercentStackView,showGrid: true,- showCrosshair: true,- pinnableTooltip: true,- tooltipPlacement: 'top',- xTickFormatter,- yTickFormatter,}),- [yAxisScaleType, isPercentStackView, xTickFormatter, yTickFormatter]+ [trendsFilter, isPercentStackView, baseCurrency, yAxisScaleType]+ )++ const goalLineConfigs = useMemo(() => schemaGoalLinesToConfigs(goalLines), [goalLines])++ const valueLabelFormatter = useCallback(+ (value: number) => formatPercentStackAxisValue(trendsFilter, value, isPercentStackView, baseCurrency),+ [trendsFilter, isPercentStackView, baseCurrency])- const referenceLines = useMemo(() => goalLinesToReferenceLines(goalLines, series), [goalLines, series])+ const confidenceIntervals: ConfidenceIntervalConfig[] | undefined = useMemo(() => {+ if (!showConfidenceIntervals || !indexedResults?.length) {+ return undefined+ }+ const ci = (confidenceLevel ?? 95) / 100+ return indexedResults.map((r) => {+ const [lower, upper] = ciRanges(r.data, ci)+ return { seriesKey: String(r.id), lower, upper }+ })+ }, [showConfidenceIntervals, confidenceLevel, indexedResults])++ const movingAverage: MovingAverageConfig[] | undefined = useMemo(() => {+ if (!showMovingAverage || movingAverageIntervals === undefined || !indexedResults?.length) {+ return undefined+ }+ return indexedResults+ .filter((r) => r.data.length >= movingAverageIntervals)+ .map((r) => ({ seriesKey: String(r.id), window: movingAverageIntervals }))+ }, [showMovingAverage, movingAverageIntervals, indexedResults])++ const trendLines: TrendLineConfig[] | undefined = useMemo(() => {+ if (!showTrendLines || !indexedResults?.length) {+ return undefined+ }+ const out: TrendLineConfig[] = []+ const includeMa = showMovingAverage && movingAverageIntervals !== undefined+ for (const r of indexedResults) {+ if (getTrendsHidden(r)) {+ continue+ }+ const isActiveSeries = !r.compare || r.compare_label !== 'previous'+ const isInProgress =+ !isStickiness && incompletenessOffsetFromEnd !== undefined && incompletenessOffsetFromEnd < 0+ const fitUpTo = isInProgress && isActiveSeries ? r.data.length + incompletenessOffsetFromEnd : undefined+ out.push({ seriesKey: String(r.id), kind: 'linear', fitUpTo })+ if (includeMa && r.data.length >= movingAverageIntervals) {+ out.push({+ seriesKey: `${r.id}-ma`,+ kind: 'linear',+ label: `${r.label ?? ''} (Moving avg)`,+ })+ }+ }+ return out.length ? out : undefined+ }, [+ showTrendLines,+ showMovingAverage,+ movingAverageIntervals,+ indexedResults,+ getTrendsHidden,+ isStickiness,+ incompletenessOffsetFromEnd,+ ])++ // Compare-previous dimming flows through `buildMainTrendsSeries` for now; a+ // follow-up PR (the buildDerivedConfigs extraction) moves it to the library's+ // `comparisonOf` pass. Visual parity preserved either way.+ const chartConfig: TimeSeriesLineChartConfig = useMemo(+ () => ({+ xAxis: {+ tickFormatter: xTickFormatter,+ },+ yAxis: yAxisConfig,+ valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,+ goalLines: goalLineConfigs,+ confidenceIntervals,+ movingAverage,+ trendLines,+ percentStackView: isPercentStackView,+ showCrosshair: true,+ tooltip: { pinnable: true, placement: 'top' },+ }),+ [+ xTickFormatter,+ yAxisConfig,+ showValuesOnSeries,+ valueLabelFormatter,+ goalLineConfigs,+ confidenceIntervals,+ movingAverage,+ trendLines,+ isPercentStackView,+ ]+ )const getYAxisId = useCallback((r: IndexedTrendResult) => {@@ -178,11 +249,6 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha[indexedResults, showMultipleYAxes])- const valueLabelFormatter = useCallback(- (value: number) => formatPercentStackAxisValue(trendsFilter, value, isPercentStackView, baseCurrency),- [trendsFilter, isPercentStackView, baseCurrency]- )-const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModalconst clickDeps = useMemo(@@ -268,18 +334,17 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaconst annotationsDates = currentPeriodResult?.days ?? []return (- <LineChart+ <TimeSeriesLineChart<TrendsSeriesMeta>series={series}labels={labels}- config={chartConfig}theme={theme}+ config={chartConfig}tooltip={renderTooltip}onPointClick={canHandleClick ? onPointClick : undefined}className="LineGraph"dataAttr="trend-line-graph"onError={handleChartError}>- <ReferenceLines lines={referenceLines} />{insight.id ? (<TrendsAlertOverlaysinsightId={insight.id}@@ -290,7 +355,6 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaisHidden={getTrendsHidden}/>) : null}- {showValuesOnSeries && <ValueLabels valueFormatter={valueLabelFormatter} />}{showAnnotations && (<AnnotationsLayerinsightNumericId={insight.id || 'new'}@@ -298,6 +362,6 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaxTickFormatter={xTickFormatter}/>)}- </LineChart>+ </TimeSeriesLineChart>)}diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.test.ts b/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.test.tsindex 2fe36fe759f4..f051946ac590 100644--- a/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.test.ts+++ b/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.test.ts@@ -1,8 +1,9 @@+import { computeSeriesNonZeroMax } from 'lib/hog-charts'import type { Series } from 'lib/hog-charts'import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'-import { alertThresholdsToReferenceLines, computeSeriesNonZeroMax, goalLinesToReferenceLines } from './goalLinesAdapter'+import { alertThresholdsToReferenceLines, goalLinesToReferenceLines } from './goalLinesAdapter'const makeSeries = (data: number[], overrides: Partial<Series> = {}): Series => ({key: 'a',diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.ts b/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.tsindex 087d886dc9c8..492a6aefb865 100644--- a/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.ts+++ b/frontend/src/scenes/trends/viz/trends-line-chart/goalLinesAdapter.ts@@ -1,12 +1,9 @@-import { buildGoalLineReferenceLines, computeSeriesNonZeroMax } from 'lib/hog-charts'+import { buildGoalLineReferenceLines } from 'lib/hog-charts'import type { GoalLineConfig, ReferenceLineProps, Series } from 'lib/hog-charts'import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'-// Re-exported so existing call sites importing from this adapter keep working.-export { computeSeriesNonZeroMax }--function schemaToGoalLineConfig(line: SchemaGoalLine): GoalLineConfig {+export function schemaGoalLineToConfig(line: SchemaGoalLine): GoalLineConfig {return {value: line.value,label: line.label,@@ -17,6 +14,13 @@ function schemaToGoalLineConfig(line: SchemaGoalLine): GoalLineConfig {}}+export function schemaGoalLinesToConfigs(goalLines: SchemaGoalLine[] | null | undefined): GoalLineConfig[] | undefined {+ if (!goalLines?.length) {+ return undefined+ }+ return goalLines.map(schemaGoalLineToConfig)+}+function schemaToReferenceLine(line: SchemaGoalLine, variant: 'goal' | 'alert'): ReferenceLineProps {return {value: line.value,@@ -48,7 +52,7 @@ export function goalLinesToReferenceLines(if (!goalLines?.length) {return []}- const refs = buildGoalLineReferenceLines(goalLines.map(schemaToGoalLineConfig), series)+ const refs = buildGoalLineReferenceLines(goalLines.map(schemaGoalLineToConfig), series)return withAxisOrientation(refs, axisOrientation)}diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/trendsAxisFormat.ts b/frontend/src/scenes/trends/viz/trends-line-chart/trendsAxisFormat.tsindex ec803a35d693..d395e1feb8a4 100644--- a/frontend/src/scenes/trends/viz/trends-line-chart/trendsAxisFormat.ts+++ b/frontend/src/scenes/trends/viz/trends-line-chart/trendsAxisFormat.ts@@ -1,3 +1,4 @@+import type { YAxisConfig } from 'lib/hog-charts'import { YFormatterConfig } from 'lib/hog-charts/charts/TimeSeriesLineChart/utils/y-formatters'import { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'@@ -19,3 +20,16 @@ export function trendsFilterToYFormatterConfig(currency: baseCurrency,}}++export function buildTrendsYAxisConfig(+ trendsFilter: TrendsFilter | null | undefined,+ isPercentStackView: boolean,+ baseCurrency: CurrencyCode | undefined,+ extras: { yAxisScaleType?: string | null; showGrid?: boolean } = {}+): YAxisConfig {+ return {+ ...trendsFilterToYFormatterConfig(trendsFilter, isPercentStackView, baseCurrency),+ scale: extras.yAxisScaleType === 'log10' ? 'log' : 'linear',+ showGrid: extras.showGrid,+ }+}