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): extract buildDerivedConfigs helper + perf fixes (#57673)

Sam Pennington43261045beb4
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx
index c6ad1ecc9cd4..62f5997a3b68 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/TrendsLineChart.tsx
@@ -4,16 +4,7 @@ import { useCallback, useMemo, type ErrorInfo } from 'react'
import { buildTheme } from 'lib/charts/utils/theme'
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 { ciRanges } from 'lib/statistics'
+import type { PointClickData, Series, TimeSeriesLineChartConfig, TooltipConfig, TooltipContext } from 'lib/hog-charts'
import { formatPercentStackAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
@@ -33,7 +24,7 @@ import { AnnotationsLayer } from './AnnotationsLayer'
import { schemaGoalLinesToConfigs } from './goalLinesAdapter'
import { TrendsAlertOverlays } from './TrendsAlertOverlays'
import { buildTrendsYAxisConfig } from './trendsAxisFormat'
-import { buildTrendsSeries } from './trendsChartTransforms'
+import { buildDerivedConfigs, buildTrendsSeries } from './trendsChartTransforms'
import type { TrendsSeriesMeta } from './trendsSeriesMeta'
import { TrendsTooltip } from './TrendsTooltip'
@@ -42,6 +33,8 @@ interface TrendsLineChartProps {
inSharedMode?: boolean
}
+const TOOLTIP_CONFIG: TooltipConfig = { pinnable: true, placement: 'top' }
+
const handleChartError = (error: Error, info: ErrorInfo): void => {
posthog.captureException(error, {
feature: 'trends-line-chart',
@@ -130,6 +123,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
]
)
+ // Built here so the same instance can be threaded into <AnnotationsLayer> below.
const xTickFormatter = useMemo(
() =>
createXAxisTickCallback({
@@ -156,77 +150,41 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
[trendsFilter, isPercentStackView, baseCurrency]
)
- 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,
- ])
+ const derivedConfigs = useMemo(
+ () =>
+ buildDerivedConfigs(indexedResults ?? [], {
+ showConfidenceIntervals,
+ confidenceLevel,
+ showMovingAverage,
+ movingAverageIntervals,
+ showTrendLines,
+ isStickiness,
+ incompletenessOffsetFromEnd,
+ getHidden: getTrendsHidden,
+ }),
+ [
+ indexedResults,
+ showConfidenceIntervals,
+ confidenceLevel,
+ showMovingAverage,
+ movingAverageIntervals,
+ showTrendLines,
+ isStickiness,
+ incompletenessOffsetFromEnd,
+ getTrendsHidden,
+ ]
+ )
- // 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,
- },
+ xAxis: { tickFormatter: xTickFormatter },
yAxis: yAxisConfig,
valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,
goalLines: goalLineConfigs,
- confidenceIntervals,
- movingAverage,
- trendLines,
+ ...derivedConfigs,
percentStackView: isPercentStackView,
showCrosshair: true,
- tooltip: { pinnable: true, placement: 'top' },
+ tooltip: TOOLTIP_CONFIG,
}),
[
xTickFormatter,
@@ -234,19 +192,23 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
showValuesOnSeries,
valueLabelFormatter,
goalLineConfigs,
- confidenceIntervals,
- movingAverage,
- trendLines,
+ derivedConfigs,
isPercentStackView,
]
)
+ const indexByResult = useMemo(() => {
+ const m = new Map<IndexedTrendResult, number>()
+ ;(indexedResults ?? []).forEach((r, i) => m.set(r, i))
+ return m
+ }, [indexedResults])
+
const getYAxisId = useCallback(
(r: IndexedTrendResult) => {
- const idx = (indexedResults ?? []).indexOf(r)
+ const idx = indexByResult.get(r) ?? 0
return showMultipleYAxes && idx > 0 ? `y${idx}` : DEFAULT_Y_AXIS_ID
},
- [indexedResults, showMultipleYAxes]
+ [indexByResult, showMultipleYAxes]
)
const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal
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 1f7e22183942..48dcc0552528 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,9 +1,14 @@
import { DEFAULT_Y_AXIS_ID } from 'lib/hog-charts'
-import { hexToRGBA } from 'lib/utils'
import { ChartDisplayType } from '~/types'
-import { buildMainTrendsSeries, buildTrendsSeries, type TrendsResultLike } from './trendsChartTransforms'
+import {
+ buildDerivedConfigs,
+ buildMainTrendsSeries,
+ buildTrendsSeries,
+ computeDashedFromIndex,
+ type TrendsResultLike,
+} from './trendsChartTransforms'
const RED = '#ff0000'
@@ -17,33 +22,29 @@ const makeResult = (overrides: Partial<TrendsResultLike> = {}): TrendsResultLike
describe('trendsChartTransforms', () => {
describe('buildMainTrendsSeries', () => {
it('builds a single main series with no compare and no in-progress tail', () => {
- const built = buildMainTrendsSeries(makeResult(), 0, { getColor: () => RED })
+ const series = buildMainTrendsSeries(makeResult(), 0, { getColor: () => RED })
- expect(built.baseColor).toBe(RED)
- expect(built.dashedFromIndex).toBeUndefined()
- expect(built.excluded).toBe(false)
- expect(built.main).toMatchObject({
+ expect(series).toMatchObject({
key: '0',
label: 'Pageview',
data: [1, 2, 3, 4, 5],
color: RED,
yAxisId: DEFAULT_Y_AXIS_ID,
})
- expect(built.main.stroke).toBeUndefined()
- expect(built.main.fill).toBeUndefined()
- expect(built.main.visibility).toBeUndefined()
+ expect(series.stroke).toBeUndefined()
+ expect(series.fill).toBeUndefined()
+ expect(series.visibility).toBeUndefined()
})
- it('dims compare-previous series colors to 0.5 alpha', () => {
- const built = buildMainTrendsSeries(makeResult({ compare: true, compare_label: 'previous' }), 0, {
+ it('keeps compare-previous color un-dimmed (comparisonOf does the dimming downstream)', () => {
+ const series = buildMainTrendsSeries(makeResult({ compare: true, compare_label: 'previous' }), 0, {
getColor: () => RED,
})
- expect(built.baseColor).toBe(RED)
- expect(built.main.color).toBe(hexToRGBA(RED, 0.5))
+ expect(series.color).toBe(RED)
})
- it('sets dashedFromIndex on active series and skips it on compare-previous', () => {
+ it('sets a dashed in-progress tail on active series and skips it on compare-previous', () => {
const data = [1, 2, 3, 4, 5, 6, 7]
const opts = { getColor: () => RED, incompletenessOffsetFromEnd: -2 }
@@ -54,68 +55,60 @@ describe('trendsChartTransforms', () => {
opts
)
- expect(active.dashedFromIndex).toBe(5)
- expect(active.main.stroke).toEqual({ partial: { fromIndex: 5 } })
- expect(previous.dashedFromIndex).toBeUndefined()
- expect(previous.main.stroke).toBeUndefined()
+ expect(active.stroke).toEqual({ partial: { fromIndex: 5 } })
+ expect(previous.stroke).toBeUndefined()
})
it('skips the dashed tail entirely for stickiness', () => {
- const built = buildMainTrendsSeries(makeResult({ data: [1, 2, 3, 4, 5, 6, 7] }), 0, {
+ const series = buildMainTrendsSeries(makeResult({ data: [1, 2, 3, 4, 5, 6, 7] }), 0, {
getColor: () => RED,
incompletenessOffsetFromEnd: -2,
isStickiness: true,
})
-
- expect(built.dashedFromIndex).toBeUndefined()
- expect(built.main.stroke).toBeUndefined()
+ expect(series.stroke).toBeUndefined()
})
it('attaches an empty fill object for ActionsAreaGraph display', () => {
- const built = buildMainTrendsSeries(makeResult(), 0, {
+ const series = buildMainTrendsSeries(makeResult(), 0, {
getColor: () => RED,
display: ChartDisplayType.ActionsAreaGraph,
})
- // Truthy presence (chart treats fill presence as opt-in), but no overrides.
- expect(built.main.fill).toEqual({})
+ expect(series.fill).toEqual({})
})
it('marks a series excluded when getHidden returns true', () => {
- const built = buildMainTrendsSeries(makeResult(), 0, {
+ const series = buildMainTrendsSeries(makeResult(), 0, {
getColor: () => RED,
getHidden: () => true,
})
-
- expect(built.excluded).toBe(true)
- expect(built.main.visibility).toEqual({ excluded: true })
+ expect(series.visibility).toEqual({ excluded: true })
})
it('attaches the meta payload returned by buildMeta', () => {
const meta = { breakdown_value: 'spike', order: 7 }
- const built = buildMainTrendsSeries(makeResult(), 0, {
+ const series = buildMainTrendsSeries(makeResult(), 0, {
getColor: () => RED,
buildMeta: () => meta,
})
-
- expect(built.main.meta).toBe(meta)
+ expect(series.meta).toBe(meta)
})
it('falls back to empty string label when result has none', () => {
- const built = buildMainTrendsSeries(makeResult({ label: null }), 0, { getColor: () => RED })
- expect(built.main.label).toBe('')
+ const series = buildMainTrendsSeries(makeResult({ label: null }), 0, { getColor: () => RED })
+ expect(series.label).toBe('')
})
it('keeps index 0 on the default y-axis even when showMultipleYAxes is true', () => {
- const built = buildMainTrendsSeries(makeResult(), 0, { getColor: () => RED, showMultipleYAxes: true })
- expect(built.main.yAxisId).toBe(DEFAULT_Y_AXIS_ID)
+ const series = buildMainTrendsSeries(makeResult(), 0, { getColor: () => RED, showMultipleYAxes: true })
+ expect(series.yAxisId).toBe(DEFAULT_Y_AXIS_ID)
})
it('skips the dashed tail when incompletenessOffsetFromEnd is 0', () => {
- const built = buildMainTrendsSeries(makeResult({ data: [1, 2, 3] }), 0, {
+ const series = buildMainTrendsSeries(makeResult({ data: [1, 2, 3] }), 0, {
getColor: () => RED,
incompletenessOffsetFromEnd: 0,
})
- expect(built.dashedFromIndex).toBeUndefined()
+ expect(series.stroke).toBeUndefined()
})
it('passes the result index through to getColor and buildMeta', () => {
@@ -143,4 +136,176 @@ describe('trendsChartTransforms', () => {
expect(series.map((s) => s.yAxisId)).toEqual([DEFAULT_Y_AXIS_ID, 'y1', 'y2'])
})
})
+
+ describe('computeDashedFromIndex', () => {
+ it.each([
+ ['active series + negative offset', { compare_label: 'current' }, { incompletenessOffsetFromEnd: -2 }, 5],
+ ['plain non-compare series', {}, { incompletenessOffsetFromEnd: -1 }, 6],
+ ] as const)('%s → %s', (_, resultOverrides, opts, expected) => {
+ const r = makeResult({ data: [1, 2, 3, 4, 5, 6, 7], compare: true, ...resultOverrides })
+ expect(computeDashedFromIndex(r, opts)).toBe(expected)
+ })
+
+ it.each([
+ ['compare-previous', { compare: true, compare_label: 'previous' }, { incompletenessOffsetFromEnd: -2 }],
+ ['stickiness', {}, { isStickiness: true, incompletenessOffsetFromEnd: -2 }],
+ ['no offset', {}, {}],
+ ['offset of 0', {}, { incompletenessOffsetFromEnd: 0 }],
+ ['positive offset', {}, { incompletenessOffsetFromEnd: 1 }],
+ ] as const)('returns undefined for %s', (_, resultOverrides, opts) => {
+ const r = makeResult({ data: [1, 2, 3, 4, 5, 6, 7], ...resultOverrides })
+ expect(computeDashedFromIndex(r, opts)).toBeUndefined()
+ })
+ })
+
+ describe('buildDerivedConfigs', () => {
+ it('returns an empty object for empty results', () => {
+ expect(buildDerivedConfigs([], { showConfidenceIntervals: true })).toEqual({})
+ })
+
+ it('returns an empty object when no derived flags are set', () => {
+ expect(buildDerivedConfigs([makeResult()], {})).toEqual({})
+ })
+
+ describe('confidenceIntervals', () => {
+ it('emits one CI config per result with seriesKey and lower/upper arrays', () => {
+ const out = buildDerivedConfigs([makeResult({ id: 'a' }), makeResult({ id: 'b' })], {
+ showConfidenceIntervals: true,
+ confidenceLevel: 95,
+ })
+ expect(out.confidenceIntervals).toHaveLength(2)
+ expect(out.confidenceIntervals?.[0].seriesKey).toBe('a')
+ expect(out.confidenceIntervals?.[0].lower).toHaveLength(5)
+ expect(out.confidenceIntervals?.[0].upper).toHaveLength(5)
+ })
+
+ it('defaults confidenceLevel to 95 when undefined', () => {
+ const explicit = buildDerivedConfigs([makeResult()], {
+ showConfidenceIntervals: true,
+ confidenceLevel: 95,
+ })
+ const defaulted = buildDerivedConfigs([makeResult()], { showConfidenceIntervals: true })
+ expect(defaulted.confidenceIntervals?.[0].lower).toEqual(explicit.confidenceIntervals?.[0].lower)
+ })
+
+ it('omits confidenceIntervals when showConfidenceIntervals is false', () => {
+ expect(buildDerivedConfigs([makeResult()], {}).confidenceIntervals).toBeUndefined()
+ })
+ })
+
+ describe('movingAverage', () => {
+ it('emits MA configs only for results whose data is at least window-long', () => {
+ const out = buildDerivedConfigs(
+ [makeResult({ id: 'a', data: [1, 2, 3, 4, 5] }), makeResult({ id: 'b', data: [1, 2] })],
+ { showMovingAverage: true, movingAverageIntervals: 3 }
+ )
+ expect(out.movingAverage).toEqual([{ seriesKey: 'a', window: 3 }])
+ })
+
+ it('omits movingAverage when movingAverageIntervals is undefined', () => {
+ expect(buildDerivedConfigs([makeResult()], { showMovingAverage: true }).movingAverage).toBeUndefined()
+ })
+
+ it('omits movingAverage when showMovingAverage is false', () => {
+ expect(buildDerivedConfigs([makeResult()], { movingAverageIntervals: 3 }).movingAverage).toBeUndefined()
+ })
+ })
+
+ describe('trendLines', () => {
+ it('emits one trendline per visible result with linear kind', () => {
+ const out = buildDerivedConfigs([makeResult({ id: 'a' }), makeResult({ id: 'b' })], {
+ showTrendLines: true,
+ })
+ expect(out.trendLines?.map((t) => t.seriesKey)).toEqual(['a', 'b'])
+ expect(out.trendLines?.every((t) => t.kind === 'linear')).toBe(true)
+ })
+
+ it('skips hidden results', () => {
+ const out = buildDerivedConfigs([makeResult({ id: 'a' }), makeResult({ id: 'b' })], {
+ showTrendLines: true,
+ getHidden: (r) => r.id === 'b',
+ })
+ expect(out.trendLines?.map((t) => t.seriesKey)).toEqual(['a'])
+ })
+
+ it('threads fitUpTo from incompletenessOffsetFromEnd for active series', () => {
+ const out = buildDerivedConfigs([makeResult({ data: [1, 2, 3, 4, 5, 6, 7] })], {
+ showTrendLines: true,
+ incompletenessOffsetFromEnd: -2,
+ })
+ expect(out.trendLines?.[0].fitUpTo).toBe(5)
+ })
+
+ it('omits fitUpTo for compare-previous results', () => {
+ const out = buildDerivedConfigs(
+ [
+ makeResult({
+ id: 'p',
+ compare: true,
+ compare_label: 'previous',
+ data: [1, 2, 3, 4, 5, 6, 7],
+ }),
+ ],
+ { showTrendLines: true, incompletenessOffsetFromEnd: -2 }
+ )
+ expect(out.trendLines?.[0].fitUpTo).toBeUndefined()
+ })
+
+ it('emits an MA-trendline alongside the raw trendline when MA is also on and data is long enough', () => {
+ const out = buildDerivedConfigs([makeResult({ id: 'a', data: [1, 2, 3, 4, 5] })], {
+ showTrendLines: true,
+ showMovingAverage: true,
+ movingAverageIntervals: 3,
+ })
+ expect(out.trendLines?.map((t) => t.seriesKey)).toEqual(['a', 'a-ma'])
+ })
+
+ it('skips the MA-trendline when MA data is gated out by short input', () => {
+ const out = buildDerivedConfigs([makeResult({ data: [1, 2] })], {
+ showTrendLines: true,
+ showMovingAverage: true,
+ movingAverageIntervals: 3,
+ })
+ expect(out.trendLines?.map((t) => t.seriesKey)).toEqual(['0'])
+ })
+
+ it('omits trendLines when showTrendLines is false', () => {
+ expect(buildDerivedConfigs([makeResult()], {}).trendLines).toBeUndefined()
+ })
+ })
+
+ describe('comparisonOf', () => {
+ it('omits comparisonOf when there are no compare-previous results', () => {
+ const out = buildDerivedConfigs([makeResult()], {})
+ expect(out.comparisonOf).toBeUndefined()
+ })
+
+ it('maps each compare-previous result key to itself (presence-only marker)', () => {
+ const out = buildDerivedConfigs(
+ [
+ makeResult({ id: 0, compare: true, compare_label: 'current' }),
+ makeResult({ id: 1, compare: true, compare_label: 'previous' }),
+ ],
+ {}
+ )
+ expect(out.comparisonOf).toEqual({ '1': '1' })
+ })
+
+ it('also marks the MA-of-previous key when MA is enabled', () => {
+ const out = buildDerivedConfigs([makeResult({ id: 1, compare: true, compare_label: 'previous' })], {
+ showMovingAverage: true,
+ movingAverageIntervals: 3,
+ })
+ expect(out.comparisonOf).toEqual({ '1': '1', '1-ma': '1' })
+ })
+
+ it('omits the MA-of-previous key when the result is too short for an MA series', () => {
+ const out = buildDerivedConfigs(
+ [makeResult({ id: 1, compare: true, compare_label: 'previous', data: [1, 2] })],
+ { showMovingAverage: true, movingAverageIntervals: 3 }
+ )
+ expect(out.comparisonOf).toEqual({ '1': '1' })
+ })
+ })
+ })
})
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 2e3558125617..936fea639529 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,9 @@
-import { DEFAULT_Y_AXIS_ID } from 'lib/hog-charts'
-import type { Series } from 'lib/hog-charts'
-import { hexToRGBA } from 'lib/utils'
+import { DEFAULT_Y_AXIS_ID, movingAverageKey } from 'lib/hog-charts'
+import type { ConfidenceIntervalConfig, MovingAverageConfig, Series, TrendLineConfig } from 'lib/hog-charts'
+import { ciRanges } from 'lib/statistics'
import { ChartDisplayType } from '~/types'
-import { COMPARE_PREVIOUS_DIM_OPACITY } from '../trendsAdapterConstants'
-
// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.
export interface TrendsResultLike {
id?: string | number
@@ -30,46 +28,129 @@ export interface BuildTrendsSeriesOpts<R extends TrendsResultLike, M = unknown>
buildMeta?: (r: R, index: number) => M
}
-export interface BuiltTrendsSeries<M> {
- main: Series<M>
- // Un-dimmed base color, exposed so derived series can dim further without re-resolving.
- baseColor: string
- dashedFromIndex: number | undefined
- excluded: boolean
+// Shared between buildMainTrendsSeries (stroke.partial.fromIndex) and buildDerivedConfigs
+// (trendline fitUpTo) — they must agree on the in-progress boundary.
+export function computeDashedFromIndex(
+ r: TrendsResultLike,
+ opts: { isStickiness?: boolean; incompletenessOffsetFromEnd?: number }
+): number | undefined {
+ const isActiveSeries = !r.compare || r.compare_label !== 'previous'
+ const isInProgress =
+ !opts.isStickiness && opts.incompletenessOffsetFromEnd !== undefined && opts.incompletenessOffsetFromEnd < 0
+ if (!isInProgress || !isActiveSeries) {
+ return undefined
+ }
+ return r.data.length + (opts.incompletenessOffsetFromEnd as number)
}
export function buildMainTrendsSeries<R extends TrendsResultLike, M = unknown>(
r: R,
index: number,
opts: BuildTrendsSeriesOpts<R, M>
-): BuiltTrendsSeries<M> {
- const isActiveSeries = !r.compare || r.compare_label !== 'previous'
- const isInProgress =
- !opts.isStickiness && opts.incompletenessOffsetFromEnd !== undefined && opts.incompletenessOffsetFromEnd < 0
- const dashedFromIndex =
- isInProgress && isActiveSeries ? r.data.length + (opts.incompletenessOffsetFromEnd as number) : undefined
+): Series<M> {
+ const dashedFromIndex = computeDashedFromIndex(r, opts)
const yAxisId = opts.showMultipleYAxes && index > 0 ? `y${index}` : DEFAULT_Y_AXIS_ID
- const baseColor = opts.getColor(r, index)
- const displayColor = r.compare_label === 'previous' ? hexToRGBA(baseColor, COMPARE_PREVIOUS_DIM_OPACITY) : baseColor
const excluded = opts.getHidden ? opts.getHidden(r, index) : false
const meta: M | undefined = opts.buildMeta ? opts.buildMeta(r, index) : undefined
- const main: Series<M> = {
+ return {
key: String(r.id),
label: r.label ?? '',
data: r.data,
- color: displayColor,
+ color: opts.getColor(r, index),
yAxisId,
meta,
fill: opts.display === ChartDisplayType.ActionsAreaGraph ? {} : undefined,
stroke: dashedFromIndex !== undefined ? { partial: { fromIndex: dashedFromIndex } } : undefined,
visibility: excluded ? { excluded: true } : undefined,
}
- return { main, baseColor, dashedFromIndex, excluded }
}
export function buildTrendsSeries<R extends TrendsResultLike, M = unknown>(
results: R[],
opts: BuildTrendsSeriesOpts<R, M>
): Series<M>[] {
- return results.map((r, index) => buildMainTrendsSeries(r, index, opts).main)
+ return results.map((r, index) => buildMainTrendsSeries(r, index, opts))
+}
+
+export interface BuildDerivedConfigsOpts<R extends TrendsResultLike> {
+ showConfidenceIntervals?: boolean
+ confidenceLevel?: number
+ showMovingAverage?: boolean
+ movingAverageIntervals?: number
+ showTrendLines?: boolean
+ isStickiness?: boolean
+ incompletenessOffsetFromEnd?: number
+ getHidden?: (r: R) => boolean
+}
+
+export interface DerivedConfigs {
+ confidenceIntervals?: ConfidenceIntervalConfig[]
+ movingAverage?: MovingAverageConfig[]
+ trendLines?: TrendLineConfig[]
+ comparisonOf?: Record<string, string>
+}
+
+export function buildDerivedConfigs<R extends TrendsResultLike>(
+ results: readonly R[],
+ opts: BuildDerivedConfigsOpts<R>
+): DerivedConfigs {
+ const out: DerivedConfigs = {}
+ if (!results.length) {
+ return out
+ }
+
+ if (opts.showConfidenceIntervals) {
+ const ci = (opts.confidenceLevel ?? 95) / 100
+ out.confidenceIntervals = results.map((r) => {
+ const [lower, upper] = ciRanges(r.data, ci)
+ return { seriesKey: String(r.id), lower, upper }
+ })
+ }
+
+ const includeMa = !!opts.showMovingAverage && opts.movingAverageIntervals !== undefined
+ if (includeMa) {
+ const window = opts.movingAverageIntervals as number
+ out.movingAverage = results
+ .filter((r) => r.data.length >= window)
+ .map((r) => ({ seriesKey: String(r.id), window }))
+ }
+
+ if (opts.showTrendLines) {
+ const trendLines: TrendLineConfig[] = []
+ for (const r of results) {
+ if (opts.getHidden?.(r)) {
+ continue
+ }
+ const fitUpTo = computeDashedFromIndex(r, opts)
+ trendLines.push({ seriesKey: String(r.id), kind: 'linear', fitUpTo })
+ if (includeMa && r.data.length >= (opts.movingAverageIntervals as number)) {
+ trendLines.push({
+ seriesKey: movingAverageKey(String(r.id)),
+ kind: 'linear',
+ label: `${r.label ?? ''} (Moving avg)`,
+ })
+ }
+ }
+ if (trendLines.length) {
+ out.trendLines = trendLines
+ }
+ }
+
+ const comparisonOf: Record<string, string> = {}
+ for (const r of results) {
+ if (r.compare && r.compare_label === 'previous') {
+ const key = String(r.id)
+ // Self-map: applyComparisonDimming only checks key presence; the paired primary
+ // id isn't carried on TrendsResultLike.
+ comparisonOf[key] = key
+ if (includeMa && r.data.length >= (opts.movingAverageIntervals as number)) {
+ comparisonOf[movingAverageKey(key)] = key
+ }
+ }
+ }
+ if (Object.keys(comparisonOf).length) {
+ out.comparisonOf = comparisonOf
+ }
+
+ return out
}