: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
feat(hog-charts): add trendLines + comparisonOf config to TimeSeriesLineChart (#57488)
Sam Penningtondc20c7e975de
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 254cf04eac74..eaf0c7e6f881 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -580,6 +580,10 @@ snapshots:hash: v1.k794b7964.529535e435c93c8f004cdba8f2ba29681dd679eb9bfbaff745a5f00c3b424ffd.2Kq3-2B9F2VNlkrFY-dge3vntnfrudonJ-Lle1s8m5Ecomponents-hogcharts-timeserieslinechart--basic--light:hash: v1.k794b7964.3a097fd7390b5a54fcf6e20a1769cc9058b66f4d040ed58748d0d4dc55c8788b.zqLqP936uYDq025ot6wQL3TxRVnq4UzQAtiS92DFZp8+ components-hogcharts-timeserieslinechart--comparison-of--dark:+ hash: v1.k794b7964.aa337a8f5a91d73e016f4f22959d401546472f882b4ed16c8f86c9dbea7313ee.b9ovlLn2FH-CDTyiX4aBo6eTitW98Sv3_iAnYo0igtg+ components-hogcharts-timeserieslinechart--comparison-of--light:+ hash: v1.k794b7964.f765c2b9fa66bd68ddc97b1e12adde81f4bed9375be55238b4ce902cf18061c5.JgAvyFSvBD_UD9pTvlG2wTVDy5slZ7NEnvNH-8e4izgcomponents-hogcharts-timeserieslinechart--confidence-intervals--dark:hash: v1.k794b7964.604addbe746f827ade2350d9167a72d9a7fbedfd96bd621a7af7994cd489c4c8.M3UGtYXBVSJzocWg4vxO3GwAXWveRgWHTGCql8iWjeccomponents-hogcharts-timeserieslinechart--confidence-intervals--light:@@ -592,6 +596,10 @@ snapshots:hash: v1.k794b7964.276935f8bb553e4ab9fac3ace6eebb3d28dfdf96cffe2e034fedb97e74ce37d0.5SBoJ3War_QIpdVFWyeow-y8o4S-qReI1UdVs9HO6Ikcomponents-hogcharts-timeserieslinechart--moving-average--light:hash: v1.k794b7964.326fb129af77ff50842a525cabd6dc99bdda0184f67de96e57ad1c9a13be4ab3.e5Hz2jQlR4ZqIhUHnbbeFlfLsHNkw7_7_1JJqj1v2N0+ components-hogcharts-timeserieslinechart--trend-lines--dark:+ hash: v1.k794b7964.542f8d5fee67e14dc285806bc677c0417df77c44589d005b0dea49ba75fc80e5.ZF5lPBCHngzzZ9Cw1ITdZbIJ-OGvJmU9OlK2V1wYeAE+ components-hogcharts-timeserieslinechart--trend-lines--light:+ hash: v1.k794b7964.5801e5c4274cd0b2d2fdb3d69cfb0299804f62f39036e5a2901e78789e0d764b.x4egj_Wp44H8iI00Wsgho-a68dHFvkXzSziDZG0zwFwcomponents-hogcharts-timeserieslinechart--y-axis-formats--dark:hash: v1.k794b7964.ab5470e4567b923b3414ddc27d0e40872a481d973df9e12d1765fbedff32c20d.JdA-hTR2nKp921x6JROPc0p43nBvLgWiXzJQRPLviMQcomponents-hogcharts-timeserieslinechart--y-axis-formats--light:diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsxindex 4909a9904d83..f16806233c4f 100644--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx@@ -235,6 +235,56 @@ export const MovingAverage: Story = {},}+export const TrendLines: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <TimeSeriesLineChart+ series={DERIVED_SERIES}+ labels={DAYS}+ theme={theme}+ config={{+ yAxis: { showGrid: true },+ trendLines: [+ { seriesKey: 'visits', kind: 'linear' },+ { seriesKey: 'signups', kind: 'linear' },+ ],+ }}+ />+ </Stage>+ )+ },+}++export const ComparisonOf: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ { key: 'visits', label: 'Visits', data: [20, 35, 28, 60, 45, 70, 52], color: theme.colors[0] },+ {+ key: 'visits-prev',+ label: 'Visits (previous)',+ data: [15, 25, 32, 40, 38, 50, 44],+ color: theme.colors[0],+ },+ ]+ return (+ <Stage>+ <TimeSeriesLineChart+ series={series}+ labels={DAYS}+ theme={theme}+ config={{+ yAxis: { showGrid: true },+ comparisonOf: { 'visits-prev': 'visits' },+ }}+ />+ </Stage>+ )+ },+}+export const DateAxis: Story = {render: () => {const cells: { interval: TimeInterval; labels: string[]; series: Series[]; title: string }[] = [diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsxindex 4894dd536089..6b2ee07f5145 100644--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx@@ -255,6 +255,7 @@ describe('TimeSeriesLineChart', () => {it.each([['confidenceIntervals', { confidenceIntervals: [{ seriesKey: 'a', lower: [0, 1, 2], upper: [2, 3, 4] }] }],['movingAverage', { movingAverage: [{ seriesKey: 'a', window: 2 }] }],+ ['trendLines', { trendLines: [{ seriesKey: 'a', kind: 'linear' as const }] }],])('plumbs config.%s through to the rendered series count', (_, derivedConfig) => {const { chart } = renderHogChart(<TimeSeriesLineChart series={SERIES} labels={LABELS} theme={THEME} config={derivedConfig} />@@ -262,6 +263,22 @@ describe('TimeSeriesLineChart', () => {// SERIES has 1 entry; each derived block adds one more series.expect(chart.seriesCount).toBe(2)})++ it('skips comparison-period series count change while still rendering them', () => {+ const series: Series[] = [+ { key: 'a', label: 'A', data: [1, 2, 3], color: '#112233' },+ { key: 'a-prev', label: 'A (prev)', data: [1, 2, 3], color: '#112233' },+ ]+ const { chart } = renderHogChart(+ <TimeSeriesLineChart+ series={series}+ labels={LABELS}+ theme={THEME}+ config={{ comparisonOf: { 'a-prev': 'a' } }}+ />+ )+ expect(chart.seriesCount).toBe(2)+ })})it('forwards children alongside built-in overlays', () => {diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsxindex 1297f07ed628..7376820305c3 100644--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx@@ -8,14 +8,19 @@ import { AnomalyPointsLayer, type AnomalyMarker } from './overlays/AnomalyPointsimport { buildGoalLineReferenceLines, type GoalLineConfig } from './utils/goal-lines'import { applyInProgressToSeries, type InProgressConfig } from './utils/in-progress'import { useXTickFormatter, useYTickFormatter, type XAxisConfig, type YAxisConfig } from './utils/use-axis-formatters'-import { useDerivedSeries, type ConfidenceIntervalConfig, type MovingAverageConfig } from './utils/use-derived-series'+import {+ useDerivedSeries,+ type ConfidenceIntervalConfig,+ type MovingAverageConfig,+ type TrendLineConfig,+} from './utils/use-derived-series'export interface ValueLabelsConfig {seriesKeys?: string[]formatter?: (value: number) => string}-export type { ConfidenceIntervalConfig, MovingAverageConfig }+export type { ConfidenceIntervalConfig, MovingAverageConfig, TrendLineConfig }export interface TimeSeriesLineChartConfig {xAxis?: XAxisConfig@@ -25,6 +30,10 @@ export interface TimeSeriesLineChartConfig {goalLines?: GoalLineConfig[]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. */+ comparisonOf?: Record<string, string>/** Anomaly markers rendered as filled circles on top of the chart. */anomalies?: AnomalyMarker[]}@@ -62,8 +71,18 @@ export function TimeSeriesLineChart<Meta = unknown>({className,children,}: TimeSeriesLineChartProps<Meta>): React.ReactElement {- const { xAxis, yAxis, inProgress, valueLabels, goalLines, confidenceIntervals, movingAverage, anomalies } =- config ?? {}+ const {+ xAxis,+ yAxis,+ inProgress,+ valueLabels,+ goalLines,+ confidenceIntervals,+ movingAverage,+ trendLines,+ comparisonOf,+ anomalies,+ } = config ?? {}const xTickFormatter = useXTickFormatter(xAxis, labels)const yTickFormatter = useYTickFormatter(yAxis)@@ -95,6 +114,8 @@ export function TimeSeriesLineChart<Meta = unknown>({const finalSeries = useDerivedSeries(seriesAfterValueLabels, {confidenceIntervals,movingAverage,+ trendLines,+ comparisonOf,})const valueLabelFormatter = valueLabelsConfig ? (valueLabelsConfig.formatter ?? yTickFormatter) : undefineddiff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.test.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.test.tsindex c5f56f7fef97..8bed88c55ee4 100644--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.test.ts+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.test.ts@@ -1,5 +1,10 @@import type { Series } from '../../../core/types'-import { buildConfidenceIntervalSeries, buildMovingAverageSeries } from './derived-series'+import {+ applyComparisonDimming,+ buildConfidenceIntervalSeries,+ buildMovingAverageSeries,+ buildTrendLineSeries,+} from './derived-series'const SOURCE: Series = {key: 'visits',@@ -64,3 +69,54 @@ describe('buildMovingAverageSeries', () => {expect(ma.label).toBe('Smoothed')})})++describe('buildTrendLineSeries', () => {+ it('keys, labels, and styles a dotted dimmed overlay', () => {+ const tl = buildTrendLineSeries({ sourceSeries: SOURCE, kind: 'linear' })+ expect(tl.key).toBe('visits__trendline')+ expect(tl.label).toBe('Visits')+ expect(tl.color).toMatch(/^rgba\(/)+ expect(tl.stroke?.pattern).toEqual([1, 3])+ expect(tl.visibility?.fromStack).toBe(true)+ })++ it.each([+ ['linear', [10, 12, 14, 16, 18, 20, 22], 'linear', undefined, 10, 22],+ ['exponential, all positive (y=2^x)', [1, 2, 4, 8, 16, 32, 64], 'exponential', undefined, 1, 64],+ ['exponential, non-positive falls back to linear y=x-1', [-1, 0, 1, 2], 'exponential', undefined, -1, 2],+ ['exponential, zero in tail with fitUpTo skipping it', [1, 2, 4, 8, 0], 'exponential', 4, 1, 16],+ ] as const)('fits %s', (_label, data, kind, fitUpTo, expectedFirst, expectedLast) => {+ const tl = buildTrendLineSeries({ sourceSeries: { ...SOURCE, data: [...data] }, kind, fitUpTo })+ expect(tl.data).toHaveLength(data.length)+ expect(tl.data.every(Number.isFinite)).toBe(true)+ expect(tl.data[0]).toBeCloseTo(expectedFirst, 2)+ expect(tl.data[data.length - 1]).toBeCloseTo(expectedLast, 2)+ })+})++describe('applyComparisonDimming', () => {+ const A: Series = { key: 'a', label: 'A', data: [1, 2], color: '#112233' }+ const A_PREV: Series = { key: 'a-prev', label: 'A (prev)', data: [1, 2], color: '#112233' }+ const B: Series = { key: 'b', label: 'B', data: [3, 4], color: '#445566' }++ it.each([+ ['undefined', undefined],+ ['empty', {}],+ ] as const)('returns the same reference when comparisonOf is %s', (_label, comparisonOf) => {+ const series = [A, B]+ expect(applyComparisonDimming(series, comparisonOf)).toBe(series)+ })++ it('rewrites comparison series to a dimmed rgba colour, leaves primaries alone', () => {+ const result = applyComparisonDimming([A, A_PREV, B], { 'a-prev': 'a' })+ expect(result[0]).toBe(A)+ expect(result[2]).toBe(B)+ expect(result[1].color).toMatch(/^rgba\([^)]*,\s*0\.5\)$/)+ })++ it('leaves non-hex colours untouched (no double-wrapping)', () => {+ const rgbaSource: Series = { key: 'a-prev', label: '', data: [], color: 'rgba(0,0,0,1)' }+ const result = applyComparisonDimming([rgbaSource], { 'a-prev': 'a' })+ expect(result[0].color).toBe('rgba(0,0,0,1)')+ })+})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.tsindex 6c04e3bf13bc..0112db823baf 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@@ -1,9 +1,13 @@-import { movingAverage } from 'lib/statistics'+import { linearRegression, movingAverage, trendLine } from 'lib/statistics'+import { hexToRGBA } from 'lib/utils'import type { Series } from '../../../core/types'+const COMPARISON_DIM_OPACITY = 0.5+const TREND_LINE_DIM_OPACITY = 0.5const CI_FILL_OPACITY = 0.2const MA_DASH_PATTERN = [10, 3]+const TREND_LINE_DASH_PATTERN = [1, 3]export interface BuildConfidenceIntervalSeriesInput<Meta = unknown> {seriesKey: string@@ -50,3 +54,84 @@ export function buildMovingAverageSeries<Meta = unknown>(input: BuildMovingAveravisibility: { fromTooltip: true, fromStack: true },}}++export interface BuildTrendLineSeriesInput<Meta = unknown> {+ sourceSeries: Series<Meta>+ kind: 'linear' | 'exponential'+ label?: string+ /** When set, only the prefix `[0, fitUpTo)` contributes to the regression, but the+ * trend is extrapolated across the full data range. Useful for excluding an+ * in-progress tail so the partial bucket doesn't drag the slope. */+ fitUpTo?: number+}++/** Linear or exponential regression rendered as a dimmed dotted line. Exponential is+ * fitted in log-space and exp'd back, so it falls back to linear when any value in the+ * fit range is non-positive (log-space is undefined there). Colour dimming is applied+ * only to hex source colours; non-hex inputs are passed through untouched (mirrors+ * `applyComparisonDimming`). */+export function buildTrendLineSeries<Meta = unknown>(input: BuildTrendLineSeriesInput<Meta>): Series<Meta> {+ const { sourceSeries, kind, fitUpTo } = input+ const data =+ kind === 'exponential' ? exponentialTrend(sourceSeries.data, fitUpTo) : trendLine(sourceSeries.data, fitUpTo)+ const baseColor = sourceSeries.color+ return {+ key: `${sourceSeries.key}__trendline`,+ label: input.label ?? sourceSeries.label,+ data,+ color: dimHex(baseColor, TREND_LINE_DIM_OPACITY),+ yAxisId: sourceSeries.yAxisId,+ meta: sourceSeries.meta,+ stroke: { pattern: TREND_LINE_DASH_PATTERN },+ visibility: { fromTooltip: true, fromValueLabels: true, fromStack: true },+ }+}++function exponentialTrend(values: number[], fitUpTo?: number): number[] {+ const n = values.length+ if (n < 2) {+ return trendLine(values, fitUpTo)+ }+ const fitEnd = fitUpTo != null ? Math.max(2, Math.min(fitUpTo, n)) : n+ // Single pass: build the log-space coords and bail on the first non-positive value.+ // The prefix `[0, fitEnd)` is the only region that contributes to the regression,+ // so a 0 in the in-progress tail mustn't force a fallback.+ const coords: [number, number][] = []+ for (let x = 0; x < fitEnd; x++) {+ const y = values[x]+ if (y <= 0) {+ return trendLine(values, fitUpTo)+ }+ coords.push([x, Math.log(y)])+ }+ const { m, b } = linearRegression(coords)+ return values.map((_, x) => Math.exp(m * x + b))+}++/** Re-render comparison series at reduced opacity so they read as subordinate to their+ * primary. Series whose colour is missing or already an `rgba(...)` string are left as-is+ * — `hexToRGBA` only handles hex inputs. */+export function applyComparisonDimming<Meta = unknown>(+ series: Series<Meta>[],+ comparisonOf: Record<string, string> | undefined+): Series<Meta>[] {+ if (!comparisonOf || Object.keys(comparisonOf).length === 0) {+ return series+ }+ return series.map((s) => {+ if (!(s.key in comparisonOf)) {+ return s+ }+ const dimmed = dimHex(s.color, COMPARISON_DIM_OPACITY)+ return dimmed === s.color ? s : { ...s, color: dimmed }+ })+}++/** Apply alpha dimming to a hex colour. Returns the input unchanged for non-hex inputs+ * (CSS variables, `rgba(...)`, undefined) since `hexToRGBA` only handles hex. */+function dimHex(color: string | undefined, alpha: number): string | undefined {+ if (!color || !color.startsWith('#')) {+ return color+ }+ return hexToRGBA(color, alpha)+}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.tsindex 47c7bcd28cfe..ca2f5954d06b 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@@ -14,14 +14,15 @@ describe('useDerivedSeries', () => {expect(result.current).toBe(SOURCE)})- it('orders derived series CI → main → MA', () => {+ it('orders derived series CI → main → MA → trend lines', () => {const { result } = renderHook(() =>useDerivedSeries(SOURCE, {confidenceIntervals: [{ seriesKey: 'a', lower: [0, 1, 2, 3], upper: [2, 3, 4, 5] }],movingAverage: [{ seriesKey: 'a', window: 2 }],+ trendLines: [{ seriesKey: 'a', kind: 'linear' }],}))- expect(result.current.map((s) => s.key)).toEqual(['a__ci', 'a', 'b', 'a-ma'])+ expect(result.current.map((s) => s.key)).toEqual(['a__ci', 'a', 'b', 'a-ma', 'a__trendline'])})it('skips derived entries whose seriesKey does not exist in source', () => {@@ -30,4 +31,14 @@ describe('useDerivedSeries', () => {)expect(result.current.map((s) => s.key)).toEqual(['a', 'b'])})++ it('applies comparison dimming as the final pass', () => {+ const series: Series[] = [+ { key: 'a', label: 'A', data: [1, 2], color: '#112233' },+ { key: 'a-prev', label: 'A (prev)', data: [1, 2], color: '#112233' },+ ]+ const { result } = renderHook(() => useDerivedSeries(series, { comparisonOf: { 'a-prev': 'a' } }))+ expect(result.current[0].color).toBe('#112233')+ expect(result.current[1].color).toMatch(/^rgba\([^)]*,\s*0\.5\)$/)+ })})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.tsindex 557caa1f6655..298af44f77f5 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@@ -1,7 +1,12 @@import { useMemo } from 'react'import type { Series } from '../../../core/types'-import { buildConfidenceIntervalSeries, buildMovingAverageSeries } from './derived-series'+import {+ applyComparisonDimming,+ buildConfidenceIntervalSeries,+ buildMovingAverageSeries,+ buildTrendLineSeries,+} from './derived-series'export interface ConfidenceIntervalConfig {seriesKey: string@@ -15,27 +20,43 @@ export interface MovingAverageConfig {label?: string}+export interface TrendLineConfig {+ seriesKey: string+ kind: 'linear' | 'exponential'+ label?: string+}+export interface DerivedSeriesOptions {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. */+ comparisonOf?: Record<string, string>}-/** Builds CI bands and moving averages from `source` and merges them with the source- * series in paint order: CI behind, then main, then MA on top (matches- * `LineChart.drawStatic` array iteration). Returns the original `source` reference- * when no derived-series options are set. */+/** Builds CI bands, moving averages, and trend lines from `source` and merges them+ * with the source series in paint order: CI behind, then main, then MA, then trend+ * lines on top (matches `LineChart.drawStatic` array iteration). Comparison-period+ * dimming runs as a final pass. Returns the original `source` reference when no+ * derived-series options are set. */export function useDerivedSeries<Meta>(source: Series<Meta>[], options: DerivedSeriesOptions): Series<Meta>[] {- const { confidenceIntervals, movingAverage } = options+ const { confidenceIntervals, movingAverage, trendLines, comparisonOf } = options// Reduce each config to a primitive signature so callers passing inline configs- // (`config={{ movingAverage: [...] }}`) don't reallocate the dep refs on every render+ // (`config={{ trendLines: [...] }}`) don't reallocate the dep refs on every render// and miss the cache. CI's lower/upper data arrays aren't included — we assume the// caller hands us stable references when the underlying numbers haven't changed.const ciSignature = ciSig(confidenceIntervals)const maSignature = maSig(movingAverage)+ const tlSignature = tlSig(trendLines)+ const cmpSignature = cmpSig(comparisonOf)return useMemo(() => {const hasDerived =- (confidenceIntervals && confidenceIntervals.length > 0) || (movingAverage && movingAverage.length > 0)- if (!hasDerived) {+ (confidenceIntervals && confidenceIntervals.length > 0) ||+ (movingAverage && movingAverage.length > 0) ||+ (trendLines && trendLines.length > 0)+ const hasComparisons = comparisonOf && Object.keys(comparisonOf).length > 0+ if (!hasDerived && !hasComparisons) {return source}@@ -70,11 +91,20 @@ export function useDerivedSeries<Meta>(source: Series<Meta>[], options: DerivedSmaSeries.push(buildMovingAverageSeries<Meta>({ sourceSeries: found, window: ma.window, label: ma.label }))}- return [...ciSeries, ...source, ...maSeries]- // The signatures above stand in for the two reference-typed config inputs; the+ const tlSeries: Series<Meta>[] = []+ for (const tl of trendLines ?? []) {+ const found = sourceByKey.get(tl.seriesKey)+ if (!found) {+ continue+ }+ tlSeries.push(buildTrendLineSeries<Meta>({ sourceSeries: found, kind: tl.kind, label: tl.label }))+ }++ return applyComparisonDimming([...ciSeries, ...source, ...maSeries, ...tlSeries], comparisonOf)+ // The signatures above stand in for the four reference-typed config inputs; the// raw refs are intentionally absent so inline-config callers don't bust the cache.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [source, ciSignature, maSignature])+ }, [source, ciSignature, maSignature, tlSignature, cmpSignature])}function ciSig(ci: ConfidenceIntervalConfig[] | undefined): string {@@ -94,6 +124,23 @@ function maSig(ma: MovingAverageConfig[] | undefined): string {return ma.map((m) => `${m.seriesKey}|${m.window}|${m.label ?? ''}`).join(';')}+function tlSig(tl: TrendLineConfig[] | undefined): string {+ if (!tl?.length) {+ return ''+ }+ return tl.map((t) => `${t.seriesKey}|${t.kind}|${t.label ?? ''}`).join(';')+}++function cmpSig(cmp: Record<string, string> | undefined): string {+ if (!cmp) {+ return ''+ }+ return Object.entries(cmp)+ .map(([k, v]) => `${k}=${v}`)+ .sort()+ .join(';')+}+const refIds = new WeakMap<object, number>()let nextRefId = 1function refKey(arr: number[]): number {diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.tsindex fbb6f307693a..cbc7871e392b 100644--- a/frontend/src/lib/hog-charts/index.ts+++ b/frontend/src/lib/hog-charts/index.ts@@ -9,6 +9,7 @@ export type {MovingAverageConfig,TimeSeriesLineChartConfig,TimeSeriesLineChartProps,+ TrendLineConfig,ValueLabelsConfig,} from './charts/TimeSeriesLineChart/TimeSeriesLineChart'export type { InProgressConfig } from './charts/TimeSeriesLineChart/utils/in-progress'diff --git a/frontend/src/lib/statistics.ts b/frontend/src/lib/statistics.tsindex f86393c655e9..55fdb01feb0f 100644--- a/frontend/src/lib/statistics.ts+++ b/frontend/src/lib/statistics.ts@@ -1,5 +1,7 @@import { linearRegression, probit, standardDeviation } from 'simple-statistics'+export { linearRegression }+/*** Calculates the confidence interval ranges for a given set of values.*diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.tsindex ae08fc71581a..9fc839fe0f56 100644--- a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts+++ b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts@@ -3,13 +3,14 @@ import type { LineChartConfig, Series } from 'lib/hog-charts'import {buildConfidenceIntervalSeries,buildMovingAverageSeries,+ buildTrendLineSeries,} from 'lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series'-import { ciRanges, trendLine } from 'lib/statistics'+import { ciRanges } from 'lib/statistics'import { hexToRGBA } from 'lib/utils'import { ChartDisplayType } from '~/types'-import { COMPARE_PREVIOUS_DIM_OPACITY, TRENDLINE_DIM_OPACITY } from '../trendsAdapterConstants'+import { COMPARE_PREVIOUS_DIM_OPACITY } from '../trendsAdapterConstants'// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.export interface TrendsResultLike {@@ -117,34 +118,34 @@ function buildDerivedTrendsSeries<R extends TrendsResultLike, M = unknown>(label: `${label} (Moving avg)`,})out.push(maSeries)+ }- if (opts.showTrendLines && !excluded) {- out.push({- key: `${r.id}-ma__trendline`,+ 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)`,- data: trendLine(maSeries.data),- color: hexToRGBA(baseColor, TRENDLINE_DIM_OPACITY),- yAxisId: main.yAxisId,- stroke: { pattern: [1, 3] },- visibility: { fromTooltip: true, fromValueLabels: true, fromStack: true },})- }+ )}- // 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.if (opts.showTrendLines && !excluded) {- out.push({- key: `${r.id}__trendline`,- label,- data: trendLine(r.data, dashedFromIndex),- color: hexToRGBA(baseColor, TRENDLINE_DIM_OPACITY),- yAxisId: main.yAxisId,- stroke: { pattern: [1, 3] },- visibility: { fromTooltip: true, fromValueLabels: true, fromStack: true },- })+ // 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