: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
fix(insights): dim compare-previous series in stickiness charts (#65378)
Thomas Obermüller4a178cac1c93
diff --git a/frontend/src/test/insight-testing/mocks.ts b/frontend/src/test/insight-testing/mocks.tsindex 2ebd32bbdebe..cd21e9d0a667 100644--- a/frontend/src/test/insight-testing/mocks.ts+++ b/frontend/src/test/insight-testing/mocks.ts@@ -113,12 +113,14 @@ function buildStickinessResponse(series: SeriesData[]): TrendsQueryResponse {return {results: series.map((s, i) => {const buckets = s.data.length+ // Compare current/previous share one series identity (order 0), mirroring the real runner.+ const seriesOrder = s.compare || s.breakdown_value != null ? 0 : ireturn {action: {id: `$${s.label.toLowerCase().replace(/\s+/g, '_')}`,type: 'events',name: s.label,- order: i,+ order: seriesOrder,},label: s.label,count: s.data.reduce((a, b) => a + b, 0),@@ -127,6 +129,8 @@ function buildStickinessResponse(series: SeriesData[]): TrendsQueryResponse {labels: Array.from({ length: buckets }, (_, j) => `${j + 1} day${j === 0 ? '' : 's'}`),days: Array.from({ length: buckets }, (_, j) => j + 1),breakdown_value: s.breakdown_value,+ compare: s.compare,+ compare_label: s.compare_label,}}),} as TrendsQueryResponsediff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.compare.test.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.compare.test.tsxnew file mode 100644index 000000000000..d696568a2b2d--- /dev/null+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.compare.test.tsx@@ -0,0 +1,72 @@+import '@testing-library/jest-dom'++import { cleanup, waitFor } from '@testing-library/react'++import type { Series } from '@posthog/quill-charts'+import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { buildStickinessQuery, renderInsight } from '~/test/insight-testing'+import { ChartDisplayType } from '~/types'++import type { TrendsSeriesMeta } from '../../trends/shared/trendsSeriesMeta'++// Capture the series the component hands to the quill bar chart so we can assert the resolved+// colors end-to-end (indexedResults → getTrendsColor → dimming) without poking at the canvas.+const mockCapturedSeries: Series<TrendsSeriesMeta>[][] = []+jest.mock('@posthog/quill-charts', () => {+ const actual = jest.requireActual('@posthog/quill-charts')+ return {+ __esModule: true,+ ...actual,+ TimeSeriesBarChart: (props: { series: Series<TrendsSeriesMeta>[] }) => {+ mockCapturedSeries.push(props.series)+ return null+ },+ }+})++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ mockCapturedSeries.length = 0+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++describe('StickinessBarChart compare-against-previous', () => {+ it('dims the previous-period series to 0.5 alpha while the current period keeps its full color', async () => {+ renderInsight({+ query: buildStickinessQuery({+ stickinessFilter: { display: ChartDisplayType.ActionsBar },+ compareFilter: { compare: true },+ }),+ })++ await waitFor(+ () => {+ const latest = mockCapturedSeries[mockCapturedSeries.length - 1] ?? []+ if (!latest.some((s) => s.meta?.compare_label === 'previous')) {+ throw new Error('compare series not captured yet')+ }+ },+ { timeout: 5000 }+ )++ const series = mockCapturedSeries[mockCapturedSeries.length - 1]+ const previous = series.find((s) => s.meta?.compare_label === 'previous')+ const current = series.find((s) => s.meta?.compare_label === 'current')++ expect(previous).not.toBeUndefined()+ expect(current).not.toBeUndefined()+ // Previous period is dimmed via rgba(...) at half opacity; current keeps the opaque palette color.+ expect(previous!.color).toMatch(/^rgba\(.+,\s*0?\.5\)$/)+ expect(current!.color).not.toMatch(/^rgba\(/)+ })+})diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.tsindex afa9159646dd..11bf95d01264 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts@@ -1,6 +1,8 @@import { DEFAULT_Y_AXIS_ID } from '@posthog/quill-charts'import type { TooltipConfig, YAxisConfig } from '@posthog/quill-charts'+import { hexToRGBA } from 'lib/utils/colors'+import { ChartDisplayType } from '~/types'import {@@ -59,6 +61,18 @@ describe('stickinessChartTransforms', () => {expect(series.visibility).toBeUndefined()})+ it.each([+ { compare_label: undefined, expectedColor: RED },+ { compare_label: 'current' as const, expectedColor: RED },+ { compare_label: 'previous' as const, expectedColor: hexToRGBA(RED, 0.5) },+ ])(+ 'dims the compare-against-previous series to 0.5 alpha, leaving others full color (compare_label=$compare_label)',+ ({ compare_label, expectedColor }) => {+ const series = buildStickinessMainSeries(makeResult({ compare_label }), 0, { getColor: () => RED })+ expect(series.color).toBe(expectedColor)+ }+ )+it('never sets a partial-stroke / in-progress tail (stickiness has no incomplete buckets)', () => {const series = buildStickinessMainSeries(makeResult({ data: [1, 2, 3, 4, 5] }), 0, { getColor: () => RED })expect(series.stroke).toBeUndefined()diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.tsindex 180284b554ed..4b7351085239 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts@@ -5,6 +5,8 @@ import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUimport { ChartDisplayType } from '~/types'+import { COMPARE_PREVIOUS_DIM_OPACITY, dimHexColor } from '../../trends/shared/compareDimming'+// Shape both IndexedTrendResult (kea) and StickinessResultItem (MCP) satisfy.export interface StickinessResultLike {id?: string | number@@ -12,6 +14,7 @@ export interface StickinessResultLike {data: number[]count: numberdays?: Array<string | number>+ compare_label?: string | nullaction?: { order?: number } | nullbreakdown_value?: unknownfilter?: unknown@@ -47,11 +50,14 @@ export function buildStickinessMainSeries<R extends StickinessResultLike, M = unconst yAxisId = opts.showMultipleYAxes && index > 0 ? `y${index}` : DEFAULT_Y_AXIS_IDconst excluded = opts.getHidden ? opts.getHidden(r, index) : falseconst meta: M | undefined = opts.buildMeta ? opts.buildMeta(r, index) : undefined+ // Dim the compare-against-previous series so it recedes behind the current period, matching trends.+ const baseColor = opts.getColor(r, index)+ const color = r.compare_label === 'previous' ? dimHexColor(baseColor, COMPARE_PREVIOUS_DIM_OPACITY) : baseColorreturn {key: String(r.id),label: r.label ?? '',data: toPercentData(r.data, r.count),- color: opts.getColor(r, index),+ color,yAxisId,meta,fill: opts.display === ChartDisplayType.ActionsAreaGraph ? {} : undefined,diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.tsindex 9b5a5e7cd123..b80dcab532cc 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts@@ -41,7 +41,7 @@ describe('buildTrendsBarTimeSeries', () => {})- // The inlined hex dimming must match lib/utils' hexToRGBA for valid hex (incl. 3-digit shorthand);+ // The shared dimHexColor must match lib/utils' hexToRGBA for valid hex (incl. 3-digit shorthand);// a non-hex color is passed through unchanged (the one intentional divergence from hexToRGBA).it.each([{ base: '#ff0000', expected: hexToRGBA('#ff0000', 0.5) },diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.tsindex 6ce9ac47f500..27b41eae1500 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts@@ -1,33 +1,11 @@import { DEFAULT_Y_AXIS_ID, normalizeAxisLabel } from '@posthog/quill-charts'import type { Series, TimeInterval, TimeSeriesBarChartConfig } from '@posthog/quill-charts'+import { COMPARE_PREVIOUS_DIM_OPACITY, dimHexColor } from '../shared/compareDimming'import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'import type { GoalLineLike, YFormatterFields } from '../shared/trendsChartDisplayOptions'-// Compare-against-previous bars render at half opacity so they recede behind the current period.-const COMPARE_PREVIOUS_DIM_OPACITY = 0.5--// Inlined from `lib/utils` so this module stays free of `lib/`/`~/`/`scenes/` deps and compiles in-// the MCP Vite bundle, which only resolves `products/*` and `@posthog/*`. Returns the input unchanged-// if it isn't a 3/6/8-digit hex (callers always pass palette hexes).-function dimHexColor(hex: string, alpha: number): string {- let h = hex.replace(/^#/, '')- if (h.length === 3 || h.length === 4) {- h = h- .split('')- .map((char) => char + char)- .join('')- }- if (h.length !== 6 && h.length !== 8) {- return hex- }- const r = parseInt(h.slice(0, 2), 16)- const g = parseInt(h.slice(2, 4), 16)- const b = parseInt(h.slice(4, 6), 16)- return `rgba(${r},${g},${b},${alpha})`-}-// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.export interface TrendsBarResultLike {id?: string | numberdiff --git a/products/product_analytics/frontend/insights/trends/shared/compareDimming.test.ts b/products/product_analytics/frontend/insights/trends/shared/compareDimming.test.tsnew file mode 100644index 000000000000..749f9066b789--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/compareDimming.test.ts@@ -0,0 +1,25 @@+import { hexToRGBA } from 'lib/utils/colors'++import { COMPARE_PREVIOUS_DIM_OPACITY, dimHexColor } from './compareDimming'++describe('compareDimming', () => {+ it('COMPARE_PREVIOUS_DIM_OPACITY is half opacity', () => {+ expect(COMPARE_PREVIOUS_DIM_OPACITY).toBe(0.5)+ })++ // Must match lib/utils' hexToRGBA for valid hex (incl. 3/8-digit forms); the one intentional+ // divergence is that a non-hex string is returned unchanged rather than producing rgba(NaN,...).+ it.each([+ { base: '#ff0000', expected: hexToRGBA('#ff0000', 0.5) },+ { base: '#f00', expected: hexToRGBA('#f00', 0.5) },+ { base: '#ff000080', expected: hexToRGBA('#ff000080', 0.5) },+ { base: 'var(--color-1)', expected: 'var(--color-1)' },+ { base: 'not-a-hex', expected: 'not-a-hex' },+ ])('dimHexColor($base) -> $expected', ({ base, expected }) => {+ expect(dimHexColor(base, 0.5)).toBe(expected)+ })++ it('respects the requested alpha', () => {+ expect(dimHexColor('#ffffff', 0.25)).toBe('rgba(255,255,255,0.25)')+ })+})diff --git a/products/product_analytics/frontend/insights/trends/shared/compareDimming.ts b/products/product_analytics/frontend/insights/trends/shared/compareDimming.tsnew file mode 100644index 000000000000..99ce7076fb72--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/compareDimming.ts@@ -0,0 +1,23 @@+// Compare-against-previous series render at half opacity so they recede behind the current period.+export const COMPARE_PREVIOUS_DIM_OPACITY = 0.5++// Inlined hex math (mirrors `lib/utils` `hexToRGBA`) so this module stays free of `lib/`/`~/`/`scenes/`+// deps and compiles in the MCP Vite bundle, which only resolves `products/*` and `@posthog/*`. 3/4-digit+// shorthand is expanded to 6/8-digit first; anything that isn't ultimately a 6- or 8-digit hex is returned+// unchanged (callers always pass palette hexes). Note an 8-digit input's alpha byte is dropped in favor of `alpha`.+export function dimHexColor(hex: string, alpha: number): string {+ let h = hex.replace(/^#/, '')+ if (h.length === 3 || h.length === 4) {+ h = h+ .split('')+ .map((char) => char + char)+ .join('')+ }+ if (h.length !== 6 && h.length !== 8) {+ return hex+ }+ const r = parseInt(h.slice(0, 2), 16)+ const g = parseInt(h.slice(2, 4), 16)+ const b = parseInt(h.slice(4, 6), 16)+ return `rgba(${r},${g},${b},${alpha})`+}