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): expose timeseries config additions for trends migration (#57668)

Sam Pennington7031bbab0e7e
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 7376820305c3..41ee3fb75698 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -1,6 +1,13 @@
import React, { useMemo } from 'react'
-import type { ChartTheme, LineChartConfig, PointClickData, Series, TooltipContext } from '../../core/types'
+import type {
+ ChartTheme,
+ LineChartConfig,
+ PointClickData,
+ Series,
+ TooltipConfig,
+ TooltipContext,
+} from '../../core/types'
import { ReferenceLines } from '../../overlays/ReferenceLine'
import { ValueLabels } from '../../overlays/ValueLabels'
import { LineChart } from '../LineChart'
@@ -31,11 +38,16 @@ export interface TimeSeriesLineChartConfig {
confidenceIntervals?: ConfidenceIntervalConfig[]
movingAverage?: MovingAverageConfig[]
trendLines?: TrendLineConfig[]
- /** Map of comparison series key → its primary series key. Comparison series render
- * at reduced opacity so they read as subordinate to their primary. */
+ /** Comparison series keys mapped to their primary. Comparison series render dimmed. */
comparisonOf?: Record<string, string>
/** Anomaly markers rendered as filled circles on top of the chart. */
anomalies?: AnomalyMarker[]
+ /** Render area-fill series as a 100% stacked view; y-axis becomes 0–100%. */
+ percentStackView?: boolean
+ /** Show a vertical crosshair line that follows the cursor. */
+ showCrosshair?: boolean
+ /** Tooltip behaviour (pinning, placement). Tooltip *content* is the `tooltip` render prop. */
+ tooltip?: TooltipConfig
}
export interface TimeSeriesLineChartProps<Meta = unknown> {
@@ -48,6 +60,7 @@ export interface TimeSeriesLineChartProps<Meta = unknown> {
dataAttr?: string
className?: string
children?: React.ReactNode
+ onError?: (error: Error, info: React.ErrorInfo) => void
}
function resolveValueLabelsConfig(valueLabels: TimeSeriesLineChartConfig['valueLabels']): ValueLabelsConfig | null {
@@ -70,6 +83,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
dataAttr,
className,
children,
+ onError,
}: TimeSeriesLineChartProps<Meta>): React.ReactElement {
const {
xAxis,
@@ -82,6 +96,9 @@ export function TimeSeriesLineChart<Meta = unknown>({
trendLines,
comparisonOf,
anomalies,
+ percentStackView,
+ showCrosshair,
+ tooltip: tooltipConfig,
} = config ?? {}
const xTickFormatter = useXTickFormatter(xAxis, labels)
const yTickFormatter = useYTickFormatter(yAxis)
@@ -129,6 +146,9 @@ export function TimeSeriesLineChart<Meta = unknown>({
hideXAxis: xAxis?.hide,
hideYAxis: yAxis?.hide,
showGrid: yAxis?.showGrid,
+ percentStackView,
+ showCrosshair,
+ tooltip: tooltipConfig,
}
return (
@@ -141,6 +161,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
onPointClick={onPointClick}
className={className}
dataAttr={dataAttr}
+ onError={onError}
>
{referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
{valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts
index 0112db823baf..08922a9c6bcf 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts
@@ -41,10 +41,14 @@ export interface BuildMovingAverageSeriesInput<Meta = unknown> {
label?: string
}
+export function movingAverageKey(sourceKey: string): string {
+ return `${sourceKey}-ma`
+}
+
export function buildMovingAverageSeries<Meta = unknown>(input: BuildMovingAverageSeriesInput<Meta>): Series<Meta> {
const { sourceSeries, window: windowSize } = input
return {
- key: `${sourceSeries.key}-ma`,
+ key: movingAverageKey(sourceSeries.key),
label: input.label ?? `${sourceSeries.label} (Moving avg)`,
data: movingAverage(sourceSeries.data, windowSize),
color: sourceSeries.color,
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts
index ca2f5954d06b..eb3823e0aa34 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts
@@ -41,4 +41,48 @@ describe('useDerivedSeries', () => {
expect(result.current[0].color).toBe('#112233')
expect(result.current[1].color).toMatch(/^rgba\([^)]*,\s*0\.5\)$/)
})
+
+ it('resolves a trendline whose seriesKey targets a moving-average series', () => {
+ const { result } = renderHook(() =>
+ useDerivedSeries(SOURCE, {
+ movingAverage: [{ seriesKey: 'a', window: 2 }],
+ trendLines: [{ seriesKey: 'a-ma', kind: 'linear' }],
+ })
+ )
+ // Order: source (a, b) → MA (a-ma) → trendline of MA (a-ma__trendline)
+ expect(result.current.map((s) => s.key)).toEqual(['a', 'b', 'a-ma', 'a-ma__trendline'])
+ })
+
+ it('threads fitUpTo from the trendLines config into the regression fit', () => {
+ // Constrained fit over [0, 4) stays flat near 10; unconstrained fit slopes up.
+ const data = [10, 10, 10, 10, 100, 100]
+ const source: Series[] = [{ key: 'a', label: 'A', data, color: '#112233' }]
+ const { result: fitted } = renderHook(() =>
+ useDerivedSeries(source, { trendLines: [{ seriesKey: 'a', kind: 'linear', fitUpTo: 4 }] })
+ )
+ const { result: full } = renderHook(() =>
+ useDerivedSeries(source, { trendLines: [{ seriesKey: 'a', kind: 'linear' }] })
+ )
+ const fittedTrend = fitted.current.find((s) => s.key === 'a__trendline')!.data
+ const fullTrend = full.current.find((s) => s.key === 'a__trendline')!.data
+ const fittedDeviationFromTen = fittedTrend.map((v) => Math.abs(v - 10))
+ const fittedLast = fittedTrend[fittedTrend.length - 1]
+ const fullLast = fullTrend[fullTrend.length - 1]
+ expect(Math.max(...fittedDeviationFromTen)).toBeLessThan(1e-6)
+ expect(fullLast).toBeGreaterThan(fittedLast)
+ })
+
+ it('busts the memo cache when fitUpTo changes between renders', () => {
+ const data = [10, 10, 10, 10, 100, 100]
+ const source: Series[] = [{ key: 'a', label: 'A', data, color: '#112233' }]
+ const { result, rerender } = renderHook(
+ ({ fitUpTo }: { fitUpTo: number | undefined }) =>
+ useDerivedSeries(source, { trendLines: [{ seriesKey: 'a', kind: 'linear', fitUpTo }] }),
+ { initialProps: { fitUpTo: 4 as number | undefined } }
+ )
+ const constrained = result.current.find((s) => s.key === 'a__trendline')!.data.slice()
+ rerender({ fitUpTo: undefined })
+ const unconstrained = result.current.find((s) => s.key === 'a__trendline')!.data
+ expect(unconstrained[unconstrained.length - 1]).toBeGreaterThan(constrained[constrained.length - 1])
+ })
})
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.ts
index 298af44f77f5..914489c74ba4 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.ts
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.ts
@@ -24,6 +24,10 @@ export interface TrendLineConfig {
seriesKey: string
kind: 'linear' | 'exponential'
label?: string
+ /** Restrict the regression fit to indices `[0, fitUpTo)`; trend is still extrapolated
+ * across the full range. Use to exclude an in-progress tail so the partial bucket
+ * doesn't drag the slope. */
+ fitUpTo?: number
}
export interface DerivedSeriesOptions {
@@ -91,13 +95,30 @@ export function useDerivedSeries<Meta>(source: Series<Meta>[], options: DerivedS
maSeries.push(buildMovingAverageSeries<Meta>({ sourceSeries: found, window: ma.window, label: ma.label }))
}
+ // Trend lines may reference moving-average series too (e.g. trends renders both a
+ // raw trendline and a trendline of the MA), so fold MA keys into the lookup —
+ // but only clone the source map when there are MA entries to add.
+ let trendLineSourceByKey = sourceByKey
+ if (maSeries.length > 0) {
+ trendLineSourceByKey = new Map(sourceByKey)
+ for (const ma of maSeries) {
+ trendLineSourceByKey.set(ma.key, ma)
+ }
+ }
const tlSeries: Series<Meta>[] = []
for (const tl of trendLines ?? []) {
- const found = sourceByKey.get(tl.seriesKey)
+ const found = trendLineSourceByKey.get(tl.seriesKey)
if (!found) {
continue
}
- tlSeries.push(buildTrendLineSeries<Meta>({ sourceSeries: found, kind: tl.kind, label: tl.label }))
+ tlSeries.push(
+ buildTrendLineSeries<Meta>({
+ sourceSeries: found,
+ kind: tl.kind,
+ label: tl.label,
+ fitUpTo: tl.fitUpTo,
+ })
+ )
}
return applyComparisonDimming([...ciSeries, ...source, ...maSeries, ...tlSeries], comparisonOf)
@@ -128,7 +149,7 @@ function tlSig(tl: TrendLineConfig[] | undefined): string {
if (!tl?.length) {
return ''
}
- return tl.map((t) => `${t.seriesKey}|${t.kind}|${t.label ?? ''}`).join(';')
+ return tl.map((t) => `${t.seriesKey}|${t.kind}|${t.label ?? ''}|${t.fitUpTo ?? ''}`).join(';')
}
function cmpSig(cmp: Record<string, string> | undefined): string {
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index cbc7871e392b..e32271302774 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -38,6 +38,7 @@ export type {
ResolvedSeries,
ResolveValueFn,
Series,
+ TooltipConfig,
TooltipContext,
YAxisScale,
} from './core/types'
@@ -66,6 +67,7 @@ export { computeVisibleXLabels } from './overlays/AxisLabels'
// Timeseries overlays
export { AnomalyPointsLayer } from './charts/TimeSeriesLineChart/overlays/AnomalyPointsLayer'
export type { AnomalyMarker } from './charts/TimeSeriesLineChart/overlays/AnomalyPointsLayer'
+export { movingAverageKey } from './charts/TimeSeriesLineChart/utils/derived-series'
// Timeseries utils
export { createXAxisTickCallback, parseDateForAxis } from './charts/TimeSeriesLineChart/utils/dates'