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(insights): port stickiness line chart to hog-charts behind flag (#59810)

Sam Penningtondaf09e52feb0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8d85d2934262..06323f601fbf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1956,6 +1956,10 @@ snapshots:
hash: v1.k794b7964.d669cc7bd939e7cd9bae4003a228e194a6c383d827feb04baf491a89dfc0b698.eD11DZ4cr8p1GMBdBaTW1doXInEVj9CIhnyMP8RNpFo
insights-insightstable--is-legend--light:
hash: v1.k794b7964.d9eec920b0b2f3c9ea87c9e0d2b298bc37339217e4211d0cf1a147630f09b75d.xGcJlQO8pvoNnHyoMNZ4F58uqKh5PDg_UiGlO5bAMn8
+ insights-stickinesslinechart--default--dark:
+ hash: v1.k794b7964.41390e8fbafc9d75682179e198664c729a05ed3439fb99ad516fe1b1032cf6c0.dmsgYkZeOieitZlRh1HAveS5ej1pzamiMVQQdBstzIg
+ insights-stickinesslinechart--default--light:
+ hash: v1.k794b7964.e5281ee27e4687b2f9240f18fd0a61d70bf5b579e96e9c1200ba505eb36db3a4.0WBlzrCtDDl3Zk7GQDHpLr0MatZnxAwMwWPfUSmjc1o
insights-trendsbarchart--aggregated-compare-breakdown--dark:
hash: v1.k794b7964.665af86c19c56e64090968d389ad70f6c31723e48a5c33dd09471fd7f7803ee1.t7lftFAyNVc_TMUt4thz6VWm9dbx1fVSXYwzEhbKYBw
insights-trendsbarchart--aggregated-compare-breakdown--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 8b671a8c1373..4a6c503a1fa3 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -421,6 +421,7 @@ export const FEATURE_FLAGS = {
PRODUCT_ANALYTICS_HOG_CHARTS_FUNNEL: 'product-analytics-hog-charts-funnel', // owner: @sampennington #team-product-analytics
PRODUCT_ANALYTICS_HOG_CHARTS_LIFECYCLE: 'product-analytics-hog-charts-lifecycle', // owner: @sampennington #team-product-analytics
PRODUCT_ANALYTICS_HOG_CHARTS_RETENTION: 'product-analytics-hog-charts-retention', // owner: @sampennington #team-product-analytics
+ PRODUCT_ANALYTICS_HOG_CHARTS_STICKINESS: 'product-analytics-hog-charts-stickiness', // owner: @sampennington #team-product-analytics
PRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analytics
PRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analytics
PRODUCT_ANALYTICS_RETENTION_AGGREGATION: 'retention-aggregation', // owner: @anirudhpillai #team-product-analytics
diff --git a/frontend/src/scenes/trends/Trends.tsx b/frontend/src/scenes/trends/Trends.tsx
index 22d850f15cd8..5eb628052c54 100644
--- a/frontend/src/scenes/trends/Trends.tsx
+++ b/frontend/src/scenes/trends/Trends.tsx
@@ -34,6 +34,11 @@ const TrendsBarChart = lazy(() =>
default: m.TrendsBarChart,
}))
)
+const StickinessLineChart = lazy(() =>
+ import('products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart').then((m) => ({
+ default: m.StickinessLineChart,
+ }))
+)
const TrendsPieChart = lazy(() =>
import('products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart').then((m) => ({
default: m.TrendsPieChart,
@@ -73,6 +78,8 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
const hogChartsTrendsEnabled =
featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_TRENDS] && !isLifecycle && !isStickiness
+ const hogChartsStickinessEnabled =
+ !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_STICKINESS] && isStickiness
const hogChartsLifecycleEnabled =
!!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_LIFECYCLE] && isLifecycle
@@ -89,6 +96,9 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
if (hogChartsTrendsEnabled) {
return <TrendsLineChart context={context} inSharedMode={inSharedMode} />
}
+ if (hogChartsStickinessEnabled) {
+ return <StickinessLineChart context={context} />
+ }
return <ActionsLineGraph {...commonProps} />
}
if (display === ChartDisplayType.ActionsBar || display === ChartDisplayType.ActionsUnstackedBar) {
diff --git a/frontend/src/test/insight-testing/index.ts b/frontend/src/test/insight-testing/index.ts
index 7d7741505cdc..de53460645a1 100644
--- a/frontend/src/test/insight-testing/index.ts
+++ b/frontend/src/test/insight-testing/index.ts
@@ -6,6 +6,7 @@ export { createInsightTooltipAccessor } from './tooltip-helpers'
export type { InsightTooltipAccessor } from './tooltip-helpers'
export {
buildFunnelsQuery,
+ buildStickinessQuery,
buildTrendsQuery,
renderInsight,
renderInsight as renderInsightPage,
diff --git a/frontend/src/test/insight-testing/mocks.ts b/frontend/src/test/insight-testing/mocks.ts
index 655eb0ad2b6b..3888f7c78cc5 100644
--- a/frontend/src/test/insight-testing/mocks.ts
+++ b/frontend/src/test/insight-testing/mocks.ts
@@ -88,6 +88,32 @@ function buildTrendsResponse(series: SeriesData[]): TrendsQueryResponse {
} as TrendsQueryResponse
}
+/** Stickiness shares the TrendResult shape with trends, but uses integer-day labels
+ * ("1 day", "2 days", …) and numeric `days` (1, 2, …). The mock reuses the canned
+ * trends series for value diversity and re-keys the x-axis to stickiness form. */
+function buildStickinessResponse(series: SeriesData[]): TrendsQueryResponse {
+ return {
+ results: series.map((s, i) => {
+ const buckets = s.data.length
+ return {
+ action: {
+ id: `$${s.label.toLowerCase().replace(/\s+/g, '_')}`,
+ type: 'events',
+ name: s.label,
+ order: i,
+ },
+ label: s.label,
+ count: s.data.reduce((a, b) => a + b, 0),
+ aggregated_value: s.data.reduce((a, b) => a + b, 0),
+ data: s.data,
+ 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,
+ }
+ }),
+ } as TrendsQueryResponse
+}
+
/** Pull the bits of an ActorsQuery we use to look up canned actors. */
interface ActorsQueryBodyShape {
source?: {
@@ -191,6 +217,10 @@ export function setupInsightMocks({
match: (query) => query.kind === NodeKind.TrendsQuery,
response: (query) => buildTrendsResponse(resolveSeriesData(query)),
},
+ {
+ match: (query) => query.kind === NodeKind.StickinessQuery,
+ response: (query) => buildStickinessResponse(resolveSeriesData(query)),
+ },
{
match: (query) => query.kind === NodeKind.FunnelsQuery,
response: (query) => buildFunnelsResponse(query),
diff --git a/frontend/src/test/insight-testing/render-insight.tsx b/frontend/src/test/insight-testing/render-insight.tsx
index 3629322f7646..224fdf229c4b 100644
--- a/frontend/src/test/insight-testing/render-insight.tsx
+++ b/frontend/src/test/insight-testing/render-insight.tsx
@@ -5,7 +5,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { actionsModel } from '~/models/actionsModel'
import { groupsModel } from '~/models/groupsModel'
-import { FunnelsQuery, InsightVizNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
+import { FunnelsQuery, InsightVizNode, NodeKind, StickinessQuery, TrendsQuery } from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
import { FunnelVizType } from '~/types'
@@ -16,7 +16,7 @@ import { setupInsightMocks, type SetupMocksOptions } from './mocks'
export const INSIGHT_TEST_KEY = 'test-harness'
export const INSIGHT_TEST_ID = `new-AdHoc.InsightViz.${INSIGHT_TEST_KEY}`
-export type InsightQuery = TrendsQuery | FunnelsQuery
+export type InsightQuery = TrendsQuery | FunnelsQuery | StickinessQuery
export function buildTrendsQuery(overrides?: Partial<TrendsQuery>): TrendsQuery {
return {
@@ -26,6 +26,15 @@ export function buildTrendsQuery(overrides?: Partial<TrendsQuery>): TrendsQuery
}
}
+export function buildStickinessQuery(overrides?: Partial<StickinessQuery>): StickinessQuery {
+ return {
+ kind: NodeKind.StickinessQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }],
+ interval: 'day',
+ ...overrides,
+ }
+}
+
export function buildFunnelsQuery(overrides?: Partial<FunnelsQuery>): FunnelsQuery {
return {
kind: NodeKind.FunnelsQuery,
diff --git a/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.stories.tsx b/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.stories.tsx
new file mode 100644
index 000000000000..a1f5b647c143
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.stories.tsx
@@ -0,0 +1,76 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+import { useState } from 'react'
+
+import { insightLogic } from 'scenes/insights/insightLogic'
+
+import { mswDecorator } from '~/mocks/browser'
+import stickinessFixture from '~/mocks/fixtures/api/projects/team_id/insights/stickiness.json'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import type { DataNodeLogicProps } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'
+import { getCachedResults } from '~/queries/nodes/InsightViz/utils'
+import { InsightLogicProps, InsightShortId } from '~/types'
+
+import { StickinessLineChart } from './StickinessLineChart'
+
+type Story = StoryObj<{}>
+
+const meta: Meta = {
+ title: 'Insights/StickinessLineChart',
+ component: StickinessLineChart,
+ parameters: {
+ layout: 'centered',
+ mockDate: '2022-03-15',
+ testOptions: { snapshotBrowsers: ['chromium'] },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/annotations/': {
+ count: 0,
+ next: null,
+ previous: null,
+ results: [],
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+let uniqueNode = 0
+
+function Stage({ children }: { children: React.ReactNode }): JSX.Element {
+ return (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ height: 360, width: 720, display: 'flex', flexDirection: 'column' }}>{children}</div>
+ )
+}
+
+function StickinessLineChartStory({ insightFixture }: { insightFixture: any }): JSX.Element {
+ const [dashboardItemId] = useState(() => `StickinessLineChartStory.${uniqueNode++}` as InsightShortId)
+ const cachedInsight = { ...insightFixture, short_id: dashboardItemId }
+
+ const insightProps: InsightLogicProps = { dashboardItemId, doNotLoad: true, cachedInsight }
+ const dataNodeLogicProps: DataNodeLogicProps = {
+ query: cachedInsight.query.source,
+ key: insightVizDataNodeKey(insightProps),
+ cachedResults: getCachedResults(cachedInsight, cachedInsight.query.source),
+ doNotLoad: true,
+ }
+
+ return (
+ <BindLogic logic={insightLogic} props={insightProps}>
+ <BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>
+ <Stage>
+ <StickinessLineChart />
+ </Stage>
+ </BindLogic>
+ </BindLogic>
+ )
+}
+
+export const Default: Story = {
+ render: () => <StickinessLineChartStory insightFixture={stickinessFixture} />,
+}
diff --git a/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.test.tsx
new file mode 100644
index 000000000000..63e1ecd8e841
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.test.tsx
@@ -0,0 +1,120 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, screen, waitFor } from '@testing-library/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { setupJsdom, setupSyncRaf } from 'lib/hog-charts/testing'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+import { buildStickinessQuery, chart, getHogChart, personsModal, renderInsight } from '~/test/insight-testing'
+
+let cleanupJsdom: () => void
+let cleanupRaf: () => void
+
+beforeEach(() => {
+ cleanupJsdom = setupJsdom()
+ cleanupRaf = setupSyncRaf()
+})
+
+afterEach(() => {
+ personsModal.cleanupAll()
+ cleanupRaf()
+ cleanupJsdom()
+ cleanup()
+})
+
+const HOG_CHARTS_FLAG = { [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_STICKINESS]: true }
+
+describe('StickinessLineChart', () => {
+ describe('renders', () => {
+ it('renders the chart from a StickinessQuery with one series', async () => {
+ renderInsight({ query: buildStickinessQuery(), featureFlags: HOG_CHARTS_FLAG })
+
+ await waitFor(() => {
+ expect(screen.getByRole('img', { name: /chart with 1 data series/i })).toBeInTheDocument()
+ })
+ })
+ })
+
+ describe('y-axis', () => {
+ it('renders percent ticks (legacy `${value.toFixed(1)}%` parity)', async () => {
+ renderInsight({ query: buildStickinessQuery(), featureFlags: HOG_CHARTS_FLAG })
+
+ await screen.findByRole('img', { name: /chart with/i })
+ const ticks = getHogChart().yTicks()
+ expect(ticks.length).toBeGreaterThan(0)
+ for (const t of ticks) {
+ expect(t).toMatch(/%/)
+ }
+ })
+ })
+
+ describe('tooltips', () => {
+ it('formats series values as percentages of the series total', async () => {
+ renderInsight({ query: buildStickinessQuery(), featureFlags: HOG_CHARTS_FLAG })
+
+ const tooltip = await chart.hoverTooltip(2)
+ // Pageview canned series is [45, 82, 134, 210, 95], total 566, so bucket 2 == 134/566 ≈ 23.7%.
+ expect(tooltip.row('Pageview')).toMatch(/%/)
+ })
+
+ it('uses "stickiness on {interval} {day}" as the tooltip title (not a calendar date)', async () => {
+ renderInsight({ query: buildStickinessQuery(), featureFlags: HOG_CHARTS_FLAG })
+
+ const tooltip = await chart.hoverTooltip(2)
+ // Day at index 2 is 3 in the mock's 1-indexed stickiness days.
+ expect(tooltip.title()).toMatch(/stickiness on day 3/i)
+ // Critically — must NOT default to a Unix-epoch-derived calendar date.
+ expect(tooltip.title()).not.toMatch(/1970/i)
+ })
+ })
+
+ describe('empty state', () => {
+ it('renders InsightEmptyState when all series are zero', async () => {
+ renderInsight({
+ query: buildStickinessQuery({
+ series: [{ kind: NodeKind.EventsNode, event: 'NoActivity', name: 'NoActivity' }],
+ }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+
+ await waitFor(() => {
+ expect(screen.getByTestId('insight-empty-state')).toBeInTheDocument()
+ })
+ expect(screen.queryByRole('img', { name: /chart with/i })).not.toBeInTheDocument()
+ })
+ })
+
+ describe('click → persons modal', () => {
+ it('opens the modal with a "stickiness on {interval} {day}" title', async () => {
+ renderInsight({ query: buildStickinessQuery(), featureFlags: HOG_CHARTS_FLAG })
+
+ await chart.clickAtIndex(2)
+
+ await waitFor(() => {
+ expect(personsModal.get()).toBeInTheDocument()
+ })
+ // The clicked bucket is index 2, days are 1-indexed in the mock, so day == 3.
+ expect(personsModal.title()).toMatch(/stickiness on day 3/i)
+ expect(personsModal.title()).toMatch(/Pageview/i)
+ })
+
+ it('fires context.onDataPointClick with the integer day instead of opening the modal', async () => {
+ const onDataPointClick = jest.fn()
+ renderInsight({
+ query: buildStickinessQuery(),
+ context: { onDataPointClick },
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+
+ await chart.clickAtIndex(2)
+
+ await waitFor(() => {
+ expect(onDataPointClick).toHaveBeenCalledTimes(1)
+ })
+ const [seriesArg] = onDataPointClick.mock.calls[0]
+ expect(seriesArg.day).toBe(3)
+ expect(personsModal.get()).not.toBeInTheDocument()
+ })
+ })
+})
diff --git a/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.tsx b/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.tsx
new file mode 100644
index 000000000000..af64262d0b26
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/StickinessLineChart/StickinessLineChart.tsx
@@ -0,0 +1,198 @@
+import { useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useCallback, useMemo, type ErrorInfo } from 'react'
+
+import { buildTheme } from 'lib/charts/utils/theme'
+import { TimeSeriesLineChart } from 'lib/hog-charts'
+import type { PointClickData, Series, TimeSeriesLineChartConfig, TooltipConfig, TooltipContext } from 'lib/hog-charts'
+import { InsightEmptyState } from 'scenes/insights/EmptyStates'
+import { insightLogic } from 'scenes/insights/insightLogic'
+import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
+import { teamLogic } from 'scenes/teamLogic'
+import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'
+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
+import type { IndexedTrendResult } from 'scenes/trends/types'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+import { groupsModel } from '~/models/groupsModel'
+import { InsightVizNode } from '~/queries/schema/schema-general'
+import { QueryContext } from '~/queries/types'
+
+import { resolveGroupTypeLabel, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
+import { TrendsTooltip } from '../shared/TrendsTooltip'
+import { handleStickinessChartClick } from './handleStickinessChartClick'
+import {
+ buildStickinessLabels,
+ buildStickinessLineTimeSeriesConfig,
+ buildStickinessSeries,
+ stickinessPercentFormatter,
+} from './stickinessChartTransforms'
+
+interface StickinessLineChartProps {
+ context?: QueryContext<InsightVizNode>
+}
+
+const TOOLTIP_CONFIG: TooltipConfig = { pinnable: true, placement: 'top' }
+
+const handleChartError = (error: Error, info: ErrorInfo): void => {
+ posthog.captureException(error, {
+ feature: 'stickiness-line-chart',
+ componentStack: info.componentStack ?? undefined,
+ })
+}
+
+/** Stickiness `date` is an interval-count integer (1, 2, …), not a date.
+ * Render "stickiness on {interval} {day}" so InsightTooltip doesn't try to
+ * format it as a calendar date (which would land on 1970-01-01). */
+function buildStickinessAltTitle(interval: string | null | undefined): (seriesData: SeriesDatum[]) => string {
+ return (seriesData) => {
+ const day = seriesData[0]?.date_label ?? ''
+ return `stickiness on ${interval || 'day'} ${day}`
+ }
+}
+
+export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.Element | null {
+ const { isDarkModeOn } = useValues(themeLogic)
+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+ const { insightProps } = useValues(insightLogic)
+
+ const {
+ indexedResults,
+ interval,
+ yAxisScaleType,
+ showMultipleYAxes,
+ getTrendsColor,
+ getTrendsHidden,
+ currentPeriodResult,
+ breakdownFilter,
+ trendsFilter,
+ formula,
+ labelGroupType,
+ hasPersonsModal,
+ querySource,
+ showValuesOnSeries,
+ } = useValues(trendsDataLogic(insightProps))
+ const { timezone, baseCurrency } = useValues(teamLogic)
+ const { aggregationLabel } = useValues(groupsModel)
+
+ const resolvedGroupTypeLabel = context?.groupTypeLabel ?? resolveGroupTypeLabel(labelGroupType, aggregationLabel)
+
+ const bucketCount = currentPeriodResult?.labels?.length ?? 0
+ const labels = useMemo(() => buildStickinessLabels(bucketCount, interval), [bucketCount, interval])
+
+ const hasData =
+ indexedResults &&
+ indexedResults[0]?.data &&
+ indexedResults.filter((result: IndexedTrendResult) => result.count !== 0).length > 0
+
+ const series: Series<TrendsSeriesMeta>[] = useMemo(
+ () =>
+ buildStickinessSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {
+ showMultipleYAxes: showMultipleYAxes ?? undefined,
+ getColor: getTrendsColor,
+ getHidden: getTrendsHidden,
+ buildMeta: (rr) => ({
+ action: rr.action,
+ breakdown_value: rr.breakdown_value,
+ compare_label: rr.compare_label,
+ days: rr.days,
+ order: rr.action?.order ?? rr.id,
+ filter: rr.filter,
+ }),
+ }),
+ [indexedResults, getTrendsColor, getTrendsHidden, showMultipleYAxes]
+ )
+
+ const chartConfig: TimeSeriesLineChartConfig = useMemo(
+ () =>
+ buildStickinessLineTimeSeriesConfig({
+ yAxisScaleType,
+ valueLabels: showValuesOnSeries ? { formatter: stickinessPercentFormatter } : false,
+ showCrosshair: true,
+ tooltip: TOOLTIP_CONFIG,
+ }),
+ [yAxisScaleType, showValuesOnSeries]
+ )
+
+ const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal
+
+ const clickDeps = useMemo(
+ () => ({
+ context,
+ hasPersonsModal: !!hasPersonsModal,
+ interval,
+ querySource,
+ indexedResults: indexedResults ?? [],
+ openPersonsModal,
+ }),
+ [context, hasPersonsModal, interval, querySource, indexedResults]
+ )
+
+ const onPointClick = useCallback(
+ (clickData: PointClickData) => {
+ handleStickinessChartClick(clickData.series.key, clickData.dataIndex, clickDeps)
+ },
+ [clickDeps]
+ )
+
+ const altTitle = useMemo(() => buildStickinessAltTitle(interval), [interval])
+
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext<TrendsSeriesMeta>) => {
+ const onRowClick = canHandleClick
+ ? (datum: SeriesDatum) => {
+ const seriesKey = ctx.seriesData[datum.datasetIndex].series.key
+ handleStickinessChartClick(seriesKey, datum.dataIndex, clickDeps)
+ }
+ : undefined
+ return (
+ <TrendsTooltip
+ context={ctx}
+ timezone={timezone}
+ interval={interval ?? undefined}
+ breakdownFilter={breakdownFilter ?? undefined}
+ trendsFilter={trendsFilter}
+ formula={formula}
+ showPercentView={true}
+ isPercentStackView={false}
+ baseCurrency={baseCurrency}
+ groupTypeLabel={resolvedGroupTypeLabel}
+ formatCompareLabel={context?.formatCompareLabel}
+ onRowClick={onRowClick}
+ altTitle={altTitle}
+ />
+ )
+ },
+ [
+ timezone,
+ interval,
+ breakdownFilter,
+ trendsFilter,
+ formula,
+ baseCurrency,
+ resolvedGroupTypeLabel,
+ context?.formatCompareLabel,
+ canHandleClick,
+ clickDeps,
+ altTitle,
+ ]
+ )
+
+ if (!hasData) {
+ return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ }
+
+ return (
+ <TimeSeriesLineChart<TrendsSeriesMeta>
+ series={series}
+ labels={labels}
+ theme={theme}
+ config={chartConfig}
+ tooltip={renderTooltip}
+ onPointClick={canHandleClick ? onPointClick : undefined}
+ className="LineGraph"
+ dataAttr="trend-line-graph"
+ onError={handleChartError}
+ />
+ )
+}
diff --git a/products/product_analytics/frontend/insights/trends/StickinessLineChart/handleStickinessChartClick.test.tsx b/products/product_analytics/frontend/insights/trends/StickinessLineChart/handleStickinessChartClick.test.tsx
new file mode 100644
index 000000000000..0599adb0e36f
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/StickinessLineChart/handleStickinessChartClick.test.tsx
@@ -0,0 +1,215 @@
+import { render } from '@testing-library/react'
+
+import type { IndexedTrendResult } from 'scenes/trends/types'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+import { CompareLabelType, EntityTypes } from '~/types'
+
+import { handleStickinessChartClick, type StickinessChartClickDeps } from './handleStickinessChartClick'
+
+// `IndexedTrendResult['days']` is declared `string[]`, but the backend serves
+// stickiness "days" as integers. Centralize the cast so the test bodies stay clean.
+const daysAsType = (nums: number[]): string[] => nums as unknown as string[]
+
+function makeTrendResult(overrides: Partial<IndexedTrendResult> = {}): IndexedTrendResult {
+ return {
+ id: 0,
+ seriesIndex: 0,
+ colorIndex: 0,
+ action: {
+ id: '$pageview',
+ type: EntityTypes.EVENTS,
+ order: 0,
+ name: '$pageview',
+ days: daysAsType([1, 2, 3]),
+ },
+ label: '$pageview',
+ count: 10,
+ aggregated_value: 10,
+ data: [5, 3, 2],
+ labels: ['1 day', '2 days', '3 days'],
+ days: daysAsType([1, 2, 3]),
+ ...overrides,
+ }
+}
+
+function keyFor(trendResult: IndexedTrendResult): string {
+ return `${trendResult.id}`
+}
+
+function makeDeps(overrides: Partial<StickinessChartClickDeps> = {}): StickinessChartClickDeps {
+ const trendResult = makeTrendResult()
+ return {
+ hasPersonsModal: true,
+ interval: 'day',
+ querySource: {
+ kind: NodeKind.StickinessQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ },
+ indexedResults: [trendResult],
+ openPersonsModal: jest.fn(),
+ ...overrides,
+ }
+}
+
+describe('handleStickinessChartClick', () => {
+ it('opens the persons modal with the legacy stickiness actors-query shape', () => {
+ const openPersonsModal = jest.fn()
+ const trendResult = makeTrendResult()
+ const deps = makeDeps({ openPersonsModal, indexedResults: [trendResult] })
+
+ handleStickinessChartClick(keyFor(trendResult), 1, deps)
+
+ expect(openPersonsModal).toHaveBeenCalledTimes(1)
+ const call = openPersonsModal.mock.calls[0][0]
+ expect(call.query).toMatchObject({
+ kind: NodeKind.InsightActorsQuery,
+ day: 2,
+ series: 0,
+ includeRecordings: true,
+ })
+ // Stickiness must omit additionalSelect entries and orderBy — legacy parity
+ // with ActionsLineGraph (isLifecycle || isStickiness branch).
+ expect(call.additionalSelect).toEqual({})
+ expect(call.orderBy).toBeUndefined()
+ })
+
+ it('renders a "stickiness on {interval} {day}" title with the series label', () => {
+ const openPersonsModal = jest.fn()
+ const trendResult = makeTrendResult({ label: '$pageview' })
+ const deps = makeDeps({ openPersonsModal, interval: 'day', indexedResults: [trendResult] })
+
+ handleStickinessChartClick(keyFor(trendResult), 2, deps)
+
+ const { container } = render(<>{openPersonsModal.mock.calls[0][0].title}</>)
+ // PropertyKeyInfo wraps the raw label; the label text itself surfaces in textContent.
+ expect(container.textContent).toContain('$pageview')
+ expect(container.textContent).toContain('stickiness on day 3')
+ })
+
+ it('uses "day" as the default interval when interval is null', () => {
+ const openPersonsModal = jest.fn()
+ const trendResult = makeTrendResult()
+ const deps = makeDeps({ openPersonsModal, interval: null, indexedResults: [trendResult] })
+
+ handleStickinessChartClick(keyFor(trendResult), 0, deps)
+
+ const { container } = render(<>{openPersonsModal.mock.calls[0][0].title}</>)
+ expect(container.textContent).toContain('stickiness on day 1')
+ })
+
+ it.each([
+ ['breakdown_value', { breakdown_value: 'Spike' }, 1, { day: 2, breakdown: 'Spike' }],
+ ['compare_label', { compare_label: CompareLabelType.Previous }, 0, { day: 1, compare: 'previous' }],
+ ] as const)('includes %s in the onDataPointClick payload when present', (_field, override, dataIndex, expected) => {
+ const openPersonsModal = jest.fn()
+ const onDataPointClick = jest.fn()
+ const trendResult = makeTrendResult(override)
+ const deps = makeDeps({
+ openPersonsModal,
+ indexedResults: [trendResult],
+ context: { onDataPointClick },
+ })
+
+ handleStickinessChartClick(keyFor(trendResult), dataIndex, deps)
+
+ expect(openPersonsModal).not.toHaveBeenCalled()
+ expect(onDataPointClick).toHaveBeenCalledTimes(1)
+ expect(onDataPointClick).toHaveBeenCalledWith(expect.objectContaining(expected), expect.anything())
+ })
+
+ it('passes indexedResults[0] (not the clicked dataset) as the second arg to onDataPointClick', () => {
+ const openPersonsModal = jest.fn()
+ const onDataPointClick = jest.fn()
+ const firstResult = makeTrendResult({ id: 0, label: 'first' })
+ const secondResult = makeTrendResult({ id: 1, label: 'second' })
+ const deps = makeDeps({
+ openPersonsModal,
+ indexedResults: [firstResult, secondResult],
+ context: { onDataPointClick },
+ })
+
+ handleStickinessChartClick(keyFor(secondResult), 1, deps)
+
+ expect(onDataPointClick.mock.calls[0][1]).toBe(firstResult)
+ expect(onDataPointClick.mock.calls[0][1]).not.toBe(secondResult)
+ })
+
+ it('does nothing when hasPersonsModal is false and no context callback', () => {
+ const openPersonsModal = jest.fn()
+ const trendResult = makeTrendResult()
+ const deps = makeDeps({ openPersonsModal, hasPersonsModal: false, indexedResults: [trendResult] })
+
+ handleStickinessChartClick(keyFor(trendResult), 1, deps)
+
+ expect(openPersonsModal).not.toHaveBeenCalled()
+ })
+
+ it('still fires context.onDataPointClick when hasPersonsModal is false', () => {
+ const openPersonsModal = jest.fn()
+ const onDataPointClick = jest.fn()
+ const trendResult = makeTrendResult()
+ const deps = makeDeps({
+ openPersonsModal,
+ hasPersonsModal: false,
+ indexedResults: [trendResult],
+ context: { onDataPointClick },
+ })
+
+ handleStickinessChartClick(keyFor(trendResult), 1, deps)
+
+ expect(onDataPointClick).toHaveBeenCalledTimes(1)
+ expect(openPersonsModal).not.toHaveBeenCalled()
+ })
+
+ it('no-ops when the clicked series has no matching indexedResult', () => {
+ const openPersonsModal = jest.fn()
+ const trendResult = makeTrendResult({ id: 42 })
+ const deps = makeDeps({ openPersonsModal, indexedResults: [trendResult] })
+
+ expect(() => handleStickinessChartClick('999', 1, deps)).not.toThrow()
+ expect(openPersonsModal).not.toHaveBeenCalled()
+ })
+
+ it('uses trendResult.days[index] as fallback when action.days is missing', () => {
+ const openPersonsModal = jest.fn()
+ const trendResult = makeTrendResult({
+ action: { id: '$pageview', type: EntityTypes.EVENTS, order: 0, name: '$pageview' },
+ days: daysAsType([10, 20, 30]),
+ })
+ const deps = makeDeps({ openPersonsModal, indexedResults: [trendResult] })
+
+ handleStickinessChartClick(keyFor(trendResult), 2, deps)
+
+ expect(openPersonsModal.mock.calls[0][0].query).toMatchObject({ day: 30 })
+ })
+
+ it('no-ops when neither action.days nor trendResult.days can supply a day', () => {
+ const openPersonsModal = jest.fn()
+ const onDataPointClick = jest.fn()
+ const trendResult = makeTrendResult({
+ action: { id: '$pageview', type: EntityTypes.EVENTS, order: 0, name: '$pageview' },
+ days: [],
+ })
+ const deps = makeDeps({
+ openPersonsModal,
+ indexedResults: [trendResult],
+ context: { onDataPointClick },
+ })
+
+ handleStickinessChartClick(keyFor(trendResult), 2, deps)
+
+ expect(openPersonsModal).not.toHaveBeenCalled()
+ expect(onDataPointClick).not.toHaveBeenCalled()
+ })
+
+ it('does nothing when querySource is missing and no context callback', () => {
+ const openPersonsModal = jest.fn()
+ const trendResult = makeTrendResult()
+ const deps = makeDeps({ openPersonsModal, querySource: null, indexedResults: [trendResult] })
+
+ handleStickinessChartClick(keyFor(trendResult), 1, deps)
+
+ expect(openPersonsModal).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/product_analytics/frontend/insights/trends/StickinessLineChart/handleStickinessChartClick.tsx b/products/product_analytics/frontend/insights/trends/StickinessLineChart/handleStickinessChartClick.tsx
new file mode 100644
index 000000000000..0a49972b8d04
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/StickinessLineChart/handleStickinessChartClick.tsx
@@ -0,0 +1,69 @@
+import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
+import type { OpenPersonsModalProps } from 'scenes/trends/persons-modal/PersonsModal'
+import type { IndexedTrendResult } from 'scenes/trends/types'
+import { datasetToActorsQuery } from 'scenes/trends/viz/datasetToActorsQuery'
+
+import { InsightActorsQuery, InsightVizNode } from '~/queries/schema/schema-general'
+import { QueryContext } from '~/queries/types'
+import { IntervalType } from '~/types'
+
+export interface StickinessChartClickDeps {
+ context?: QueryContext<InsightVizNode>
+ hasPersonsModal: boolean
+ interval: IntervalType | null | undefined
+ querySource: InsightActorsQuery['source'] | null | undefined
+ indexedResults: IndexedTrendResult[]
+ // Injected so the adapter stays decoupled from PersonsModal's dep graph.
+ openPersonsModal: (props: OpenPersonsModalProps) => void
+}
+
+function resolveDataset(seriesKey: string, indexedResults: IndexedTrendResult[]): IndexedTrendResult | null {
+ return indexedResults.find((r) => String(r.id) === seriesKey) ?? null
+}
+
+export function handleStickinessChartClick(seriesKey: string, dataIndex: number, deps: StickinessChartClickDeps): void {
+ const dataset = resolveDataset(seriesKey, deps.indexedResults)
+ if (!dataset) {
+ return
+ }
+
+ const day = dataset.action?.days?.[dataIndex] ?? dataset.days?.[dataIndex]
+ if (day == null || day === '') {
+ return
+ }
+
+ if (deps.context?.onDataPointClick) {
+ // Intentional behavior change from legacy ActionsLineGraph: that code path
+ // passed `dataset.breakdownValues?.[index]` which on stickiness `IndexedTrendResult`
+ // was always `undefined`. We surface `dataset.breakdown_value` instead so
+ // consumers see the actual breakdown value the user clicked.
+ deps.context.onDataPointClick(
+ {
+ breakdown: dataset.breakdown_value,
+ compare: dataset.compare_label || undefined,
+ day,
+ },
+ // Legacy parity with ActionsLineGraph — passes the first result, not the clicked one.
+ deps.indexedResults[0]
+ )
+ return
+ }
+
+ if (!deps.hasPersonsModal || !deps.querySource) {
+ return
+ }
+
+ const label = dataset.label ?? ''
+ const title = (
+ <>
+ <PropertyKeyInfo value={label} disablePopover /> stickiness on {deps.interval || 'day'} {day}
+ </>
+ )
+
+ deps.openPersonsModal({
+ title,
+ query: datasetToActorsQuery({ dataset, query: deps.querySource, day }),
+ additionalSelect: {},
+ orderBy: undefined,
+ })
+}
diff --git a/products/product_analytics/frontend/insights/trends/StickinessLineChart/stickinessChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/StickinessLineChart/stickinessChartTransforms.test.ts
new file mode 100644
index 000000000000..e1aa521e8364
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/StickinessLineChart/stickinessChartTransforms.test.ts
@@ -0,0 +1,214 @@
+import { DEFAULT_Y_AXIS_ID } from 'lib/hog-charts'
+import type { TooltipConfig } from 'lib/hog-charts'
+
+import {
+ buildStickinessLabels,
+ buildStickinessLineTimeSeriesConfig,
+ buildStickinessMainSeries,
+ buildStickinessSeries,
+ stickinessPercentFormatter,
+ toPercentData,
+ type StickinessResultLike,
+} from './stickinessChartTransforms'
+
+const RED = '#ff0000'
+
+const makeResult = (overrides: Partial<StickinessResultLike> = {}): StickinessResultLike => ({
+ id: 0,
+ label: '$pageview',
+ count: 100,
+ data: [50, 30, 15, 5],
+ days: [1, 2, 3, 4],
+ ...overrides,
+})
+
+describe('stickinessChartTransforms', () => {
+ describe('toPercentData', () => {
+ it.each<[string, number[], number, number[]]>([
+ ['typical share split', [50, 30, 15, 5], 100, [50, 30, 15, 5]],
+ ['fractional output', [1, 2, 3], 4, [25, 50, 75]],
+ ['count of 0 returns the raw values (avoids divide-by-zero)', [0, 0, 0], 0, [0, 0, 0]],
+ ['empty data stays empty', [], 10, []],
+ ])('%s', (_, data, count, expected) => {
+ expect(toPercentData(data, count)).toEqual(expected)
+ })
+
+ it('returns a copy when count is 0 (no aliasing of the input array)', () => {
+ const input = [1, 2, 3]
+ const out = toPercentData(input, 0)
+ expect(out).toEqual(input)
+ expect(out).not.toBe(input)
+ })
+ })
+
+ describe('buildStickinessMainSeries', () => {
+ it('builds a single main series with data transformed to percentages', () => {
+ const series = buildStickinessMainSeries(makeResult(), 0, { getColor: () => RED })
+
+ expect(series).toMatchObject({
+ key: '0',
+ label: '$pageview',
+ data: [50, 30, 15, 5],
+ color: RED,
+ yAxisId: DEFAULT_Y_AXIS_ID,
+ })
+ expect(series.stroke).toBeUndefined()
+ expect(series.fill).toBeUndefined()
+ expect(series.visibility).toBeUndefined()
+ })
+
+ 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()
+ })
+
+ it('marks a series excluded when getHidden returns true', () => {
+ const series = buildStickinessMainSeries(makeResult(), 0, {
+ getColor: () => RED,
+ getHidden: () => true,
+ })
+ expect(series.visibility).toEqual({ excluded: true })
+ })
+
+ it('attaches the meta payload returned by buildMeta', () => {
+ const meta = { breakdown_value: 'spike', order: 7 }
+ const series = buildStickinessMainSeries(makeResult(), 0, {
+ getColor: () => RED,
+ buildMeta: () => meta,
+ })
+ expect(series.meta).toBe(meta)
+ })
+
+ it('falls back to empty string label when result has none', () => {
+ const series = buildStickinessMainSeries(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 series = buildStickinessMainSeries(makeResult(), 0, {
+ getColor: () => RED,
+ showMultipleYAxes: true,
+ })
+ expect(series.yAxisId).toBe(DEFAULT_Y_AXIS_ID)
+ })
+
+ it('passes the result index through to getColor and buildMeta', () => {
+ const getColor = jest.fn(() => RED)
+ const buildMeta = jest.fn(() => ({}))
+ buildStickinessMainSeries(makeResult(), 3, { getColor, buildMeta })
+ expect(getColor).toHaveBeenCalledWith(expect.anything(), 3)
+ expect(buildMeta).toHaveBeenCalledWith(expect.anything(), 3)
+ })
+ })
+
+ describe('buildStickinessSeries', () => {
+ it('returns one main series per result', () => {
+ const results = [makeResult({ id: 'a' }), makeResult({ id: 'b' })]
+ const series = buildStickinessSeries(results, { getColor: () => RED })
+
+ expect(series).toHaveLength(2)
+ expect(series.map((s) => s.key)).toEqual(['a', 'b'])
+ })
+
+ it('assigns yAxisIds [left, y1, y2] across three results when showMultipleYAxes is true', () => {
+ const results = [makeResult({ id: 'a' }), makeResult({ id: 'b' }), makeResult({ id: 'c' })]
+ const series = buildStickinessSeries(results, { getColor: () => RED, showMultipleYAxes: true })
+
+ expect(series.map((s) => s.yAxisId)).toEqual([DEFAULT_Y_AXIS_ID, 'y1', 'y2'])
+ })
+
+ it('transforms each result independently using its own count', () => {
+ const results = [
+ makeResult({ id: 'a', count: 200, data: [100, 50, 25, 25] }),
+ makeResult({ id: 'b', count: 50, data: [10, 20, 10, 10] }),
+ ]
+ const series = buildStickinessSeries(results, { getColor: () => RED })
+ expect(series[0].data).toEqual([50, 25, 12.5, 12.5])
+ expect(series[1].data).toEqual([20, 40, 20, 20])
+ })
+ })
+
+ describe('buildStickinessLabels', () => {
+ it.each([
+ ['day', 3, ['Day 0', 'Day 1', 'Day 2']],
+ ['week', 2, ['Week 0', 'Week 1']],
+ ['hour', 2, ['Hour 0', 'Hour 1']],
+ ['month', 2, ['Month 0', 'Month 1']],
+ ] as const)('emits "%s"-prefixed labels by index', (interval, count, expected) => {
+ expect(buildStickinessLabels(count, interval)).toEqual(expected)
+ })
+
+ it('defaults to "Day" when interval is null/undefined', () => {
+ expect(buildStickinessLabels(2, null)).toEqual(['Day 0', 'Day 1'])
+ expect(buildStickinessLabels(2, undefined)).toEqual(['Day 0', 'Day 1'])
+ })
+
+ it('returns empty array when count is 0', () => {
+ expect(buildStickinessLabels(0, 'day')).toEqual([])
+ })
+ })
+
+ describe('stickinessPercentFormatter', () => {
+ it.each([
+ [0, '0.0%'],
+ [50, '50.0%'],
+ [85.16, '85.2%'],
+ [100, '100.0%'],
+ ])('formats %s → %s', (value, expected) => {
+ expect(stickinessPercentFormatter(value)).toBe(expected)
+ })
+ })
+
+ describe('buildStickinessLineTimeSeriesConfig', () => {
+ const TOOLTIP: TooltipConfig = { pinnable: true, placement: 'top' }
+
+ it('returns yAxis with percent tick formatter and a linear scale by default', () => {
+ const config = buildStickinessLineTimeSeriesConfig({})
+ expect(config.yAxis).not.toBeUndefined()
+ expect(config.yAxis!.scale).toBe('linear')
+ expect(config.yAxis!.showGrid).toBe(true)
+ expect(config.yAxis!.tickFormatter).not.toBeUndefined()
+ expect(config.yAxis!.tickFormatter!(50)).toBe('50.0%')
+ })
+
+ it('switches the y-scale to log when yAxisScaleType is log10', () => {
+ const config = buildStickinessLineTimeSeriesConfig({ yAxisScaleType: 'log10' })
+ expect(config.yAxis).not.toBeUndefined()
+ expect(config.yAxis!.scale).toBe('log')
+ })
+
+ it('omits an xAxis date config — labels are pre-formatted interval counts', () => {
+ const config = buildStickinessLineTimeSeriesConfig({})
+ expect(config.xAxis).toBeUndefined()
+ })
+
+ it('passes through valueLabels, showCrosshair, and tooltip', () => {
+ const formatter = (v: number): string => `${v}!`
+ const config = buildStickinessLineTimeSeriesConfig({
+ valueLabels: { formatter },
+ showCrosshair: true,
+ tooltip: TOOLTIP,
+ })
+ expect(config.valueLabels).toEqual({ formatter })
+ expect(config.showCrosshair).toBe(true)
+ expect(config.tooltip).toBe(TOOLTIP)
+ })
+
+ it('does not enable percentStackView (stickiness already pre-percents data)', () => {
+ const config = buildStickinessLineTimeSeriesConfig({})
+ expect(config.percentStackView).toBeUndefined()
+ })
+
+ it('does not emit derived CI / MA / trendLine configs (stickiness gates those out upstream)', () => {
+ const config = buildStickinessLineTimeSeriesConfig({})
+ expect(config.confidenceIntervals).toBeUndefined()
+ expect(config.movingAverage).toBeUndefined()
+ expect(config.trendLines).toBeUndefined()
+ })
+
+ it('does not emit goal lines (stickiness does not support them)', () => {
+ const config = buildStickinessLineTimeSeriesConfig({})
+ expect(config.goalLines).toBeUndefined()
+ })
+ })
+})
diff --git a/products/product_analytics/frontend/insights/trends/StickinessLineChart/stickinessChartTransforms.ts b/products/product_analytics/frontend/insights/trends/StickinessLineChart/stickinessChartTransforms.ts
new file mode 100644
index 000000000000..c28800f27ffe
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/StickinessLineChart/stickinessChartTransforms.ts
@@ -0,0 +1,95 @@
+import { DEFAULT_Y_AXIS_ID } from 'lib/hog-charts'
+import type { Series, TimeSeriesLineChartConfig, TooltipConfig, YAxisConfig } from 'lib/hog-charts'
+
+// Shape both IndexedTrendResult (kea) and StickinessResultItem (MCP) satisfy.
+export interface StickinessResultLike {
+ id?: string | number
+ label?: string | null
+ data: number[]
+ count: number
+ days?: Array<string | number>
+ action?: { order?: number } | null
+ breakdown_value?: unknown
+ filter?: unknown
+}
+
+export interface BuildStickinessSeriesOpts<R extends StickinessResultLike, M = unknown> {
+ showMultipleYAxes?: boolean
+ getColor: (r: R, index: number) => string
+ getHidden?: (r: R, index: number) => boolean
+ buildMeta?: (r: R, index: number) => M
+}
+
+/** Convert raw counts to percentages of `count`. Mirrors the legacy `showPercentView`
+ * behavior in LineGraph: each y-value becomes its share of the series total. */
+export function toPercentData(data: number[], count: number): number[] {
+ if (!count) {
+ return data.slice()
+ }
+ return data.map((v) => (v / count) * 100)
+}
+
+export function buildStickinessMainSeries<R extends StickinessResultLike, M = unknown>(
+ r: R,
+ index: number,
+ opts: BuildStickinessSeriesOpts<R, M>
+): Series<M> {
+ const yAxisId = opts.showMultipleYAxes && index > 0 ? `y${index}` : DEFAULT_Y_AXIS_ID
+ const excluded = opts.getHidden ? opts.getHidden(r, index) : false
+ const meta: M | undefined = opts.buildMeta ? opts.buildMeta(r, index) : undefined
+ return {
+ key: String(r.id),
+ label: r.label ?? '',
+ data: toPercentData(r.data, r.count),
+ color: opts.getColor(r, index),
+ yAxisId,
+ meta,
+ visibility: excluded ? { excluded: true } : undefined,
+ }
+}
+
+export function buildStickinessSeries<R extends StickinessResultLike, M = unknown>(
+ results: R[],
+ opts: BuildStickinessSeriesOpts<R, M>
+): Series<M>[] {
+ return results.map((r, index) => buildStickinessMainSeries(r, index, opts))
+}
+
+/** Produce per-bucket labels ("Day 0", "Day 1", …). The API's own "X day(s)" labels
+ * duplicate the interval prefix when paired with a stickiness-style axis, so we
+ * synthesize them from the bucket count. Mirrors `formatIntervalLabels` in the legacy LineGraph. */
+export function buildStickinessLabels(count: number, interval: string | null | undefined): string[] {
+ const unit = interval ?? 'day'
+ const prefix = `${unit.slice(0, 1).toUpperCase()}${unit.slice(1)}`
+ return Array.from({ length: count }, (_, i) => `${prefix} ${i}`)
+}
+
+/** Emit `85.0%`-style ticks — legacy parity with `${value.toFixed(1)}%` in LineGraph. */
+export function stickinessPercentFormatter(value: number): string {
+ return `${value.toFixed(1)}%`
+}
+
+export interface BuildStickinessLineTimeSeriesConfigOpts {
+ yAxisScaleType?: string | null
+ showGrid?: boolean
+ valueLabels?: TimeSeriesLineChartConfig['valueLabels']
+ showCrosshair?: boolean
+ tooltip?: TooltipConfig
+}
+
+export function buildStickinessLineTimeSeriesConfig(
+ opts: BuildStickinessLineTimeSeriesConfigOpts
+): TimeSeriesLineChartConfig {
+ const yAxis: YAxisConfig = {
+ scale: opts.yAxisScaleType === 'log10' ? 'log' : 'linear',
+ showGrid: opts.showGrid ?? true,
+ tickFormatter: stickinessPercentFormatter,
+ }
+ return {
+ // No xAxis date config — labels are pre-formatted interval counts (Day 0, Day 1, …).
+ yAxis,
+ valueLabels: opts.valueLabels,
+ showCrosshair: opts.showCrosshair,
+ tooltip: opts.tooltip,
+ }
+}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
index eafa5e52e6aa..f455a5cc417a 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
@@ -22,7 +22,7 @@ import { AnnotationsLayer } from '../shared/AnnotationsLayer'
import { makeChartErrorHandler } from '../shared/chartErrorHandler'
import { handleTrendsChartClick } from '../shared/handleTrendsChartClick'
import { TrendsAlertOverlays } from '../shared/TrendsAlertOverlays'
-import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
+import { buildTrendsSeriesMeta, resolveGroupTypeLabel, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
import { TrendsTooltip } from '../shared/TrendsTooltip'
import { buildTrendsLineTimeSeriesConfig, buildTrendsSeries } from './trendsChartTransforms'
@@ -72,13 +72,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
const { aggregationLabel } = useValues(groupsModel)
const isPercentStackView = !!showPercentStackView && !!supportsPercentStackView
- const resolvedGroupTypeLabel =
- context?.groupTypeLabel ??
- (labelGroupType === 'people'
- ? 'people'
- : labelGroupType === 'none'
- ? ''
- : aggregationLabel(labelGroupType).plural)
+ const resolvedGroupTypeLabel = context?.groupTypeLabel ?? resolveGroupTypeLabel(labelGroupType, aggregationLabel)
const labels = currentPeriodResult?.labels ?? []
diff --git a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx
index 03ec28ee4a83..06457e18c7a5 100644
--- a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx
+++ b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx
@@ -28,6 +28,10 @@ interface TrendsTooltipProps {
formatCompareLabel?: (label: string, dateLabel?: string) => string
onRowClick?: (datum: SeriesDatum) => void
showHeader?: boolean
+ /** Override the auto-derived date header. Stickiness needs this since its `date`
+ * is an interval-count integer, not a date — letting InsightTooltip format it as
+ * a calendar date produces a wrong "Thursday, 1 Jan 1970" header. */
+ altTitle?: string | ((tooltipData: SeriesDatum[], formattedDate: string) => React.ReactNode)
/** Overrides the default value formatter — needed for the pie chart, which renders the
* raw aggregation plus the slice's share of the total. */
renderCount?: (value: number) => string
@@ -56,6 +60,7 @@ export function TrendsTooltip({
formatCompareLabel,
onRowClick,
showHeader,
+ altTitle,
renderCount: renderCountOverride,
renderSeriesOverride,
}: TrendsTooltipProps): React.ReactElement {
@@ -147,6 +152,7 @@ export function TrendsTooltip({
onRowClick={onRowClick}
hideInspectActorsSection={!onRowClick}
showHeader={showHeader}
+ altTitle={altTitle}
/>
)
}
diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts b/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts
index f8b9bb0fbee3..dd8b730cd9c7 100644
--- a/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts
@@ -1,6 +1,7 @@
import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
import type { IndexedTrendResult } from 'scenes/trends/types'
+import type { Noun } from '~/models/groupsModel'
import type { ActionFilter, LifecycleToggle } from '~/types'
export type TrendsSeriesMeta = {
@@ -26,3 +27,19 @@ export const buildTrendsSeriesMeta = (r: IndexedTrendResult): TrendsSeriesMeta =
order: r.action?.order ?? r.id,
filter: r.filter,
})
+
+/** Resolve the `groupTypeLabel` shown by tooltips and persons-modal titles.
+ * `'people'` is the default; `'none'` suppresses the noun; anything else
+ * defers to the team's group-type plural. */
+export function resolveGroupTypeLabel(
+ labelGroupType: 'people' | 'none' | number,
+ aggregationLabel: (groupTypeIndex: number | null | undefined) => Noun
+): string {
+ if (labelGroupType === 'people') {
+ return 'people'
+ }
+ if (labelGroupType === 'none') {
+ return ''
+ }
+ return aggregationLabel(labelGroupType).plural
+}