: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
refactor(insights): label trends charts and tooltips from the query series (#116839)
Thomas Obermüller7950f5facaa3
diff --git a/frontend/src/scenes/insights/utils/resultSeriesName.ts b/frontend/src/scenes/insights/utils/resultSeriesName.tsnew file mode 100644index 000000000000..8c9cf240a46e--- /dev/null+++ b/frontend/src/scenes/insights/utils/resultSeriesName.ts@@ -0,0 +1,12 @@+import { toDisplayEntityFilter } from 'lib/components/EntityFilterInfo'+import { getDisplayNameFromEntityFilter } from 'scenes/insights/utils'++import type { ResultSeries } from './resultSeries'++/**+ * The name a result row's series displays under, by the rules `EntityFilterInfo` applies to the same node. Null+ * on a row without a series node, such as a formula row, whose label is its name.+ */+export function getResultSeriesName(series: ResultSeries): string | null {+ return series.node ? getDisplayNameFromEntityFilter(toDisplayEntityFilter(series.node)) : null+}diff --git a/frontend/src/test/insight-testing/mocks.ts b/frontend/src/test/insight-testing/mocks.tsindex 9160939023ef..cb38dcd17d0e 100644--- a/frontend/src/test/insight-testing/mocks.ts+++ b/frontend/src/test/insight-testing/mocks.ts@@ -114,8 +114,7 @@ function buildTrendsResponse(series: SeriesData[], opts: { formulaLabels?: strinreturn {results: series.map((s, i) => {// Breakdown/compare rows carry their parent series' identity (event name and- // order), like the real runner. Plain rows keep their own label as the entity- // name so fixtures can model several distinct series under one canned event.+ // order), like the real runner.const isChildRow = s.compare || s.breakdown_value != nullconst seriesOrder = isChildRow ? (s.seriesIndex ?? 0) : iconst entityName = (isChildRow ? s.eventName : undefined) ?? s.labeldiff --git a/frontend/src/test/insight-testing/test-data.ts b/frontend/src/test/insight-testing/test-data.tsindex ef1c9e5a483c..604d118d4bae 100644--- a/frontend/src/test/insight-testing/test-data.ts+++ b/frontend/src/test/insight-testing/test-data.ts@@ -175,8 +175,6 @@ export const trendsSeries = {interface EventSeriesConfig {default: SeriesData- /** Return multiple series for this event even without a breakdown. */- multi?: SeriesData[]breakdowns?: Record<string, SeriesData[]>}@@ -205,7 +203,8 @@ const seriesByEvent: Record<string, EventSeriesConfig> = {hedgehog: trendsSeries.napsByManyHedgehogs,},},- ZeroCounts: { default: trendsSeries.withZeroCounts[0], multi: trendsSeries.withZeroCounts },+ EmptySeries: { default: trendsSeries.withZeroCounts[0] },+ ActiveSeries: { default: trendsSeries.withZeroCounts[1] },Minimal: { default: trendsSeries.minimal },NoActivity: { default: trendsSeries.noActivity },WeeklyAcrossYears: { default: trendsSeries.weeklyAcrossYears },@@ -234,9 +233,6 @@ export function lookupSeries(eventName: string, breakdownProperty?: string): Serif (breakdownProperty && config.breakdowns?.[breakdownProperty]) {return config.breakdowns[breakdownProperty]}- if (config.multi) {- return config.multi- }return [config.default]}diff --git a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.stories.tsx b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.stories.tsxindex 053b4e080d0e..aba1f152c3f3 100644--- a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.stories.tsx+++ b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.stories.tsx@@ -5,7 +5,7 @@ import { Stage, playHoverAtFraction } from '@posthog/quill-charts/story-helpers'import { useChartTheme } from 'lib/charts/hooks'-import type { BreakdownFilter } from '~/queries/schema/schema-general'+import { type BreakdownFilter, NodeKind } from '~/queries/schema/schema-general'import { CompareLabelType } from '~/types'import type { TrendsSeriesMeta } from '../trends/shared/trendsSeriesMeta'@@ -19,7 +19,7 @@ const BOOLEAN_BREAKDOWN_FILTER: BreakdownFilter = { breakdown: 'is_subscribed',interface FixtureSeries {label: stringdata: number[]- /** Event name — omit for formula rows, which have no `action`. */+ /** Event name — omit for formula rows, which have no series node. */event?: string/** Formula label carried as `series_name` for rows without an event. */seriesName?: string@@ -41,7 +41,11 @@ function buildSeries(fixtures: FixtureSeries[]): {label: f.label,data: f.data,meta: {- action: f.event ? { id: f.event, name: f.event, type: 'events', order: f.seriesOrder } : undefined,+ series: {+ order: f.seriesOrder,+ node: f.event ? { kind: NodeKind.EventsNode, event: f.event, name: f.event } : null,+ math: f.event ? {} : null,+ },series_name: f.seriesName,breakdown_value: f.breakdown_value,compare_label: f.compareLabel,diff --git a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsxindex 1f4210da94e3..7e043506c063 100644--- a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx+++ b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx@@ -9,12 +9,14 @@ import { percentage } from 'lib/utils/numbers'import { alphabet } from 'lib/utils/strings'import { shortTimeZone } from 'lib/utils/timezones'import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'-import { formatAggregationValue, getDisplayNameFromEntityFilter } from 'scenes/insights/utils'+import { formatAggregationValue } from 'scenes/insights/utils'+import type { ResultSeries } from 'scenes/insights/utils/resultSeries'+import { getResultSeriesName } from 'scenes/insights/utils/resultSeriesName'import { teamLogic } from 'scenes/teamLogic'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import { BreakdownFilter, CurrencyCode, DateRange, TrendsFilter } from '~/queries/schema/schema-general'-import { ActionFilter, CompareLabelType, IntervalType } from '~/types'+import { CompareLabelType, IntervalType } from '~/types'import {FormattedDateOptions,@@ -29,8 +31,8 @@ import { getSeriesIdentification, type SeriesIdentification } from './seriesIden// ── Types ──────────────────────────────────────────────────────────────────type InsightSeriesMetaBase = {- action?: ActionFilter- /** Series name for rows without an `action` — formula series carry their formula label here. */+ series?: ResultSeries+ /** Series name for rows without a series node — formula series carry their formula label here. */series_name?: stringbreakdown_value?: string | number | string[] | nullcompare_label?: SeriesDatum['compare_label']@@ -115,7 +117,7 @@ function formatHeaderDate(date: string | undefined, options: FormattedDateOption// ── SeriesLabel ────────────────────────────────────────────────────────────-/** `SeriesDatum` plus the series name for rows whose meta has no `action` (formula series). */+/** `SeriesDatum` plus the series name for rows whose meta has no series node (formula series). */type TooltipSeriesDatum = SeriesDatum & { series_name?: string }interface SeriesLabelProps {@@ -160,7 +162,7 @@ export function SeriesLabel({// eslint-disable-next-line react/forbid-dom-propsstyle={{ color: 'currentColor', borderColor: 'currentColor' }}>- {alphabet[datum.action?.order ?? datum.order]}+ {alphabet[datum.series?.order ?? datum.order]}</SeriesGlyph>) : null@@ -189,7 +191,7 @@ export function SeriesLabel({value is what tells the rows apart, and a long event name would otherwisetruncate it away. The letter and the separator stay put. */}<span className="opacity-50 truncate min-w-0 shrink">- {(datum.action ? getDisplayNameFromEntityFilter(datum.action) : datum.series_name) ?? datum.label}+ {(datum.series ? getResultSeriesName(datum.series) : null) ?? datum.series_name ?? datum.label}</span><span className="opacity-50 shrink-0"> · </span></>@@ -256,7 +258,7 @@ export function InsightSeriesTooltip<Meta extends InsightSeriesMetaBase>({label: entry.series.label,color: entry.color,count: entry.value,- action: meta.action,+ series: meta.series,series_name: meta.series_name,breakdown_value: meta.breakdown_value ?? undefined,compare_label: meta.compare_label,@@ -323,7 +325,7 @@ export function InsightSeriesTooltip<Meta extends InsightSeriesMetaBase>({(value: number, entry: InsightSeriesTooltipEntry<Meta>): React.ReactNode => {const datum = datumByKey.get(entry.series.key)return formatAggregationValue(- datum?.action?.math_property,+ datum?.series?.math?.math_property,value,(v) =>formatRowValue(v, {diff --git a/products/product_analytics/frontend/insights/shared/InsightTooltip/InsightTooltip.stories.tsx b/products/product_analytics/frontend/insights/shared/InsightTooltip/InsightTooltip.stories.tsxindex 40a65c1ddcfe..092a0dc22c88 100644--- a/products/product_analytics/frontend/insights/shared/InsightTooltip/InsightTooltip.stories.tsx+++ b/products/product_analytics/frontend/insights/shared/InsightTooltip/InsightTooltip.stories.tsx@@ -5,7 +5,8 @@ import { SeriesLetter } from 'lib/components/SeriesGlyph'import { humanFriendlyNumber } from 'lib/utils/numbers'import { cohortsModel } from '~/models/cohortsModel'-import { InsightType } from '~/types'+import { NodeKind } from '~/queries/schema/schema-general'+import { BaseMathType, InsightType } from '~/types'import { InsightTooltip } from './InsightTooltip'import { InsightTooltipProps } from './insightTooltipUtils'@@ -19,16 +20,17 @@ const data = {dataIndex: 7,datasetIndex: 2,dotted: true,- action: {- id: '$pageview',- type: 'events',+ series: {order: 0,- name: '$pageview',- custom_name: 'Pageview of people with very long names like this text',- math: 'dau',- math_property: null,- math_group_type_index: null,- properties: {},+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'Pageview of people with very long names like this text',+ },+ math: {+ math: 'dau',+ },},label: '$pageview',color: '#1d4aff',@@ -39,16 +41,14 @@ const data = {dataIndex: 7,datasetIndex: 3,dotted: true,- action: {- id: 'filter added',- type: 'events',+ series: {order: 1,- name: 'filter added',- custom_name: null,- math: null,- math_property: null,- math_group_type_index: null,- properties: {},+ node: {+ kind: NodeKind.EventsNode,+ event: 'filter added',+ name: 'filter added',+ },+ math: {},},label: 'filter added',color: '#621da6',@@ -92,26 +92,16 @@ export const Columns: Story = {order: 1,dotted: false,breakdown_value: 'Safari',- action: {- days: [- '2025-05-29T00:00:00Z',- '2025-05-30T00:00:00Z',- '2025-05-31T00:00:00Z',- '2025-06-01T00:00:00Z',- '2025-06-02T00:00:00Z',- '2025-06-03T00:00:00Z',- '2025-06-04T00:00:00Z',- '2025-06-05T00:00:00Z',- ],- id: '$autocapture',- type: 'events',+ series: {order: 1,- name: '$autocapture',- custom_name: null,- math: 'total',- math_property: null,- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$autocapture',+ name: '$autocapture',+ },+ math: {+ math: BaseMathType.TotalCount,+ },},label: '$autocapture - Safari',color: '#42827e',@@ -135,26 +125,17 @@ export const Columns: Story = {order: 0,dotted: false,breakdown_value: 'Chrome',- action: {- days: [- '2025-05-29T00:00:00Z',- '2025-05-30T00:00:00Z',- '2025-05-31T00:00:00Z',- '2025-06-01T00:00:00Z',- '2025-06-02T00:00:00Z',- '2025-06-03T00:00:00Z',- '2025-06-04T00:00:00Z',- '2025-06-05T00:00:00Z',- ],- id: '$pageview',- type: 'events',+ series: {order: 0,- name: '$pageview',- custom_name: 'Pageview of people with very long names like this text',- math: 'total',- math_property: null,- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'Pageview of people with very long names like this text',+ },+ math: {+ math: BaseMathType.TotalCount,+ },},label: '$pageview - Chrome',color: '#1d4aff',@@ -178,26 +159,17 @@ export const Columns: Story = {order: 0,dotted: false,breakdown_value: 'Safari',- action: {- days: [- '2025-05-29T00:00:00Z',- '2025-05-30T00:00:00Z',- '2025-05-31T00:00:00Z',- '2025-06-01T00:00:00Z',- '2025-06-02T00:00:00Z',- '2025-06-03T00:00:00Z',- '2025-06-04T00:00:00Z',- '2025-06-05T00:00:00Z',- ],- id: '$pageview',- type: 'events',+ series: {order: 0,- name: '$pageview',- custom_name: 'Pageview of people with very long names like this text',- math: 'total',- math_property: null,- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'Pageview of people with very long names like this text',+ },+ math: {+ math: BaseMathType.TotalCount,+ },},label: '$pageview - Safari',color: '#621da6',@@ -236,16 +208,17 @@ export const LongNames: Story = {order: 0,dotted: false,breakdown_value: longBreakdownValue,- action: {- id: '$pageview',- type: 'events',+ series: {order: 0,- name: '$pageview',- custom_name: 'Pageview of people with extremely long custom names that go on and on and on',- math: 'total',- math_property: null,- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'Pageview of people with extremely long custom names that go on and on and on',+ },+ math: {+ math: BaseMathType.TotalCount,+ },},label: '$pageview - long',color: '#1d4aff',@@ -258,16 +231,16 @@ export const LongNames: Story = {order: 1,dotted: false,breakdown_value: longBreakdownValue,- action: {- id: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',- type: 'events',+ series: {order: 1,- name: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',- custom_name: null,- math: 'total',- math_property: null,- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',+ name: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',+ },+ math: {+ math: BaseMathType.TotalCount,+ },},label: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',color: '#621da6',@@ -280,16 +253,17 @@ export const LongNames: Story = {order: 0,dotted: false,breakdown_value: anotherLongBreakdownValue,- action: {- id: '$pageview',- type: 'events',+ series: {order: 0,- name: '$pageview',- custom_name: 'Pageview of people with extremely long custom names that go on and on and on',- math: 'total',- math_property: null,- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'Pageview of people with extremely long custom names that go on and on and on',+ },+ math: {+ math: BaseMathType.TotalCount,+ },},label: '$pageview - long',color: '#1d4aff',@@ -302,16 +276,16 @@ export const LongNames: Story = {order: 1,dotted: false,breakdown_value: anotherLongBreakdownValue,- action: {- id: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',- type: 'events',+ series: {order: 1,- name: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',- custom_name: null,- math: 'total',- math_property: null,- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',+ name: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',+ },+ math: {+ math: BaseMathType.TotalCount,+ },},label: 'some_event_with_an_extremely_long_machine_readable_name_that_keeps_going',color: '#621da6',@@ -335,16 +309,17 @@ export const MathTags: Story = {order: 0,dotted: false,breakdown_value: 'Chrome',- action: {- id: '$pageview',- type: 'events',+ series: {order: 0,- name: '$pageview',- custom_name: null,- math: 'avg',- math_property: 'a_really_long_numeric_property_name_that_overflows',- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ },+ math: {+ math: 'avg',+ math_property: 'a_really_long_numeric_property_name_that_overflows',+ },},label: '$pageview - Chrome',color: '#1d4aff',@@ -357,16 +332,17 @@ export const MathTags: Story = {order: 1,dotted: false,breakdown_value: 'Safari',- action: {- id: '$pageview',- type: 'events',+ series: {order: 1,- name: '$pageview',- custom_name: null,- math: 'avg',- math_property: 'a_really_long_numeric_property_name_that_overflows',- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ },+ math: {+ math: 'avg',+ math_property: 'a_really_long_numeric_property_name_that_overflows',+ },},label: '$pageview - Safari',color: '#621da6',@@ -388,16 +364,18 @@ export const MathTagsAsRows: Story = {datasetIndex: 0,order: 0,dotted: false,- action: {- id: '$pageview',- type: 'events',+ series: {order: 0,- name: '$pageview',- custom_name: 'A really long series name that needs to be truncated',- math: 'avg',- math_property: 'a_really_long_numeric_property_name_that_overflows',- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'A really long series name that needs to be truncated',+ },+ math: {+ math: 'avg',+ math_property: 'a_really_long_numeric_property_name_that_overflows',+ },},label: '$pageview',color: '#1d4aff',@@ -409,16 +387,18 @@ export const MathTagsAsRows: Story = {datasetIndex: 1,order: 1,dotted: false,- action: {- id: '$pageview',- type: 'events',+ series: {order: 1,- name: '$pageview',- custom_name: 'Another long series name that should also be truncated',- math: 'avg',- math_property: 'amount',- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'Another long series name that should also be truncated',+ },+ math: {+ math: 'avg',+ math_property: 'amount',+ },},label: '$pageview',color: '#621da6',@@ -441,16 +421,18 @@ export const MathTagsSingleSeries: Story = {datasetIndex: 0,order: 0,dotted: false,- action: {- id: '$pageview',- type: 'events',+ series: {order: 0,- name: '$pageview',- custom_name: 'Avg widgets per dashboard over the whole period',- math: 'avg',- math_property: 'dashboard_widget_count_property',- math_hogql: null,- math_group_type_index: null,+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'Avg widgets per dashboard over the whole period',+ },+ math: {+ math: 'avg',+ math_property: 'dashboard_widget_count_property',+ },},label: '$pageview',color: '#1d4aff',@@ -478,7 +460,7 @@ export function InWrapper(): JSX.Element {<SeriesLetterclassName="mr-2"hasBreakdown={hasBreakdown}- seriesIndex={datum?.action?.order ?? datum.id}+ seriesIndex={datum?.series?.order ?? datum.id}seriesColor={datum.color}/>{value}diff --git a/products/product_analytics/frontend/insights/shared/InsightTooltip/InsightTooltip.tsx b/products/product_analytics/frontend/insights/shared/InsightTooltip/InsightTooltip.tsxindex 509ee89c9e30..d104ef67b202 100644--- a/products/product_analytics/frontend/insights/shared/InsightTooltip/InsightTooltip.tsx+++ b/products/product_analytics/frontend/insights/shared/InsightTooltip/InsightTooltip.tsx@@ -194,7 +194,7 @@ export function InsightTooltip({render: function renderSingleSeriesValue(_, datum) {const seriesColumnData = datum.seriesData[0]return renderDatumToTableCell(- seriesColumnData?.action?.math_property,+ seriesColumnData?.series?.math?.math_property,seriesColumnData?.count,formatPropertyValueForDisplay,renderCount,@@ -227,7 +227,7 @@ export function InsightTooltip({(!concreteTooltipTitle &&renderSeries(<InsightLabel- action={seriesColumn.action}+ series={seriesColumn.series}fallbackName={seriesColumn.label}showSingleNamehideBreakdown@@ -242,7 +242,7 @@ export function InsightTooltip({(s) => s.order === colIdx)const cell = renderDatumToTableCell(- seriesColumnData?.action?.math_property,+ seriesColumnData?.series?.math?.math_property,seriesColumnData?.count,formatPropertyValueForDisplay,renderCount,@@ -317,7 +317,7 @@ export function InsightTooltip({render: function renderDatum(_, datum, rowIdx) {return renderSeries(<InsightLabel- action={datum.action}+ series={datum.series}fallbackName={datum.label}showSingleNamehideBreakdown@@ -340,7 +340,7 @@ export function InsightTooltip({return (<div>{renderDatumToTableCell(- datum.action?.math_property,+ datum.series?.math?.math_property,datum.count,formatPropertyValueForDisplay,renderCountdiff --git a/products/product_analytics/frontend/insights/shared/InsightTooltip/insightTooltipUtils.tsx b/products/product_analytics/frontend/insights/shared/InsightTooltip/insightTooltipUtils.tsxindex 64ff8917c0ff..6ed89eab9161 100644--- a/products/product_analytics/frontend/insights/shared/InsightTooltip/insightTooltipUtils.tsx+++ b/products/product_analytics/frontend/insights/shared/InsightTooltip/insightTooltipUtils.tsx@@ -5,11 +5,12 @@ import { dayjs } from 'lib/dayjs'import { getConstrainedWeekRange, parseDateInTimezone } from 'lib/utils/datetime'import { capitalizeFirstLetter, midEllipsis, pluralize } from 'lib/utils/strings'import { formatBreakdownLabel } from 'scenes/insights/utils'+import type { ResultSeries } from 'scenes/insights/utils/resultSeries'import { cohortsModel } from '~/models/cohortsModel'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import { BreakdownFilter, DateRange } from '~/queries/schema/schema-general'-import { ActionFilter, CompareLabelType, FilterType, IntervalType } from '~/types'+import { CompareLabelType, FilterType, IntervalType } from '~/types'export interface SeriesDatum {id: number // determines order that series will be displayed in@@ -17,7 +18,7 @@ export interface SeriesDatum {datasetIndex: numberbreakdown_value?: string | number | string[]compare_label?: CompareLabelType- action?: ActionFilter+ series?: ResultSerieslabel?: stringdate_label?: stringorder: numberdiff --git a/products/product_analytics/frontend/insights/shared/seriesIdentification.ts b/products/product_analytics/frontend/insights/shared/seriesIdentification.tsindex 20bac98fd80e..dad15dc0e1d1 100644--- a/products/product_analytics/frontend/insights/shared/seriesIdentification.ts+++ b/products/product_analytics/frontend/insights/shared/seriesIdentification.ts@@ -1,11 +1,10 @@-import { getDisplayNameFromEntityFilter } from 'scenes/insights/utils'--import type { ActionFilter } from '~/types'+import type { ResultSeries } from 'scenes/insights/utils/resultSeries'+import { getResultSeriesName } from 'scenes/insights/utils/resultSeriesName'export type SeriesIdentification = 'none' | 'name' | 'letter-and-name'interface SeriesIdentity {- action?: ActionFilter | null+ series?: ResultSeriesorder?: numberseries_name?: string}@@ -13,9 +12,8 @@ interface SeriesIdentity {export function getSeriesIdentification(series: Iterable<SeriesIdentity>): SeriesIdentification {const nameByEntity = new Map<number | string, string>()for (const item of series) {- if (item.action) {- const entityKey = item.action.order ?? `${item.action.type}:${item.action.id}`- nameByEntity.set(entityKey, getDisplayNameFromEntityFilter(item.action) ?? '')+ if (item.series?.node) {+ nameByEntity.set(item.series.order, getResultSeriesName(item.series) ?? '')} else if (item.series_name != null && item.order != null) {nameByEntity.set(item.order, item.series_name)}diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsxindex 4840323878e7..10331566c24e 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx@@ -73,14 +73,20 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.Elconst { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const buildMeta = useCallback(+ (r: IndexedTrendResult): TrendsSeriesMeta => buildTrendsSeriesMeta(r, querySource),+ [querySource]+ )+const seriesIdentification = useMemo(- () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),- [indexedResults]+ () => getSeriesIdentification((indexedResults ?? []).map(buildMeta)),+ [indexedResults, buildMeta])const getLabel = useCallback((r: IndexedTrendResult): string =>getTrendsSeriesDisplayLabel(r, {+ querySource,breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,@@ -88,6 +94,7 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.ElseriesIdentification,}),[+ querySource,breakdownFilter,allCohorts?.results,formatPropertyValueForDisplay,@@ -114,9 +121,9 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.El// instead of being dropped here, so the legend can restore them.getHidden: undefined,getLabel,- buildMeta: buildTrendsSeriesMeta,+ buildMeta,}),- [indexedResults, getTrendsColor, getLabel]+ [indexedResults, getTrendsColor, getLabel, buildMeta])const chartConfig: TimeSeriesBarChartConfig = useChartConfig(diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsxindex 8d6d92c70677..621810bb4981 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx@@ -76,15 +76,21 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const buildMeta = useCallback(+ (r: IndexedTrendResult): TrendsSeriesMeta => buildTrendsSeriesMeta(r, querySource),+ [querySource]+ )+const seriesIdentification = useMemo(- () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),- [indexedResults]+ () => getSeriesIdentification((indexedResults ?? []).map(buildMeta)),+ [indexedResults, buildMeta])const resolvedGroupTypeLabel = context?.groupTypeLabel ?? resolveGroupTypeLabel(labelGroupType, aggregationLabel)const getLabel = useCallback((r: IndexedTrendResult): string =>getTrendsSeriesDisplayLabel(r, {+ querySource,breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,@@ -92,6 +98,7 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.seriesIdentification,}),[+ querySource,breakdownFilter,allCohorts?.results,formatPropertyValueForDisplay,@@ -114,9 +121,9 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.// instead of being dropped here, so the legend can restore them.getHidden: undefined,getLabel,- buildMeta: buildTrendsSeriesMeta,+ buildMeta,}),- [indexedResults, display, getTrendsColor, getLabel, showMultipleYAxes]+ [indexedResults, display, getTrendsColor, getLabel, buildMeta, showMultipleYAxes])const chartConfig: TimeSeriesLineChartConfig = useChartConfig(diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.tsindex 1d23fed235fd..55bff4da5588 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts@@ -18,7 +18,6 @@ export interface StickinessResultLike {count: numberdays?: Array<string | number>compare_label?: string | null- action?: { order?: number } | nullbreakdown_value?: unknownfilter?: unknown}diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsxindex d1f2f6ab7af8..303cfc32505a 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx@@ -129,9 +129,14 @@ export function TrendsBarChart({const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const buildMeta = useCallback(+ (r: IndexedTrendResult): TrendsSeriesMeta => buildTrendsSeriesMeta(r, querySource),+ [querySource]+ )+const seriesIdentification = useMemo(- () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),- [indexedResults]+ () => getSeriesIdentification((indexedResults ?? []).map(buildMeta)),+ [indexedResults, buildMeta])const isAggregated = display === ChartDisplayType.ActionsBarValue@@ -158,17 +163,19 @@ export function TrendsBarChart({const getAggregatedDisplayLabel = useCallback((r: IndexedTrendResult): string =>getAggregatedDisplayLabelFn(r, {+ querySource,stackBreakdowns,breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,}),- [stackBreakdowns, breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]+ [querySource, stackBreakdowns, breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay])const getLabel = useCallback((r: IndexedTrendResult): string =>getTrendsSeriesDisplayLabel(r, {+ querySource,breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,@@ -176,6 +183,7 @@ export function TrendsBarChart({seriesIdentification,}),[+ querySource,breakdownFilter,allCohorts?.results,formatPropertyValueForDisplay,@@ -189,7 +197,7 @@ export function TrendsBarChart({return buildTrendsBarAggregatedSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {getColor: getTrendsColor,getHidden: getTrendsHidden,- buildMeta: buildTrendsSeriesMeta,+ buildMeta,stackBreakdowns,getDisplayLabel: getAggregatedDisplayLabel,})@@ -200,7 +208,7 @@ export function TrendsBarChart({// instead of being dropped here, so the legend can restore them.getHidden: undefined,getLabel,- buildMeta: buildTrendsSeriesMeta,+ buildMeta,showMultipleYAxes: applyMultipleYAxes,})// Bands are keyed by these strings, so they must be unique per point. Display labels@@ -224,6 +232,7 @@ export function TrendsBarChart({stackBreakdowns,getAggregatedDisplayLabel,getLabel,+ buildMeta,applyMultipleYAxes,])diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.test.tsindex c68966ace398..fd4623618949 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.test.ts@@ -1,4 +1,4 @@-import type { BreakdownFilter } from '~/queries/schema/schema-general'+import { type BreakdownFilter, type EventsNode, NodeKind, type TrendsQuery } from '~/queries/schema/schema-general'import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'@@ -16,7 +16,11 @@ const mkResult = (overrides: Partial<IndexedTrendResult>): IndexedTrendResult =>...overrides,}) as IndexedTrendResult+const jobCreated: EventsNode = { kind: NodeKind.EventsNode, event: 'Job Created', name: 'Job Created' }+const querySource = (node: EventsNode): TrendsQuery => ({ kind: NodeKind.TrendsQuery, series: [node] })+const deps = (overrides?: Partial<AggregatedDisplayLabelDeps>): AggregatedDisplayLabelDeps => ({+ querySource: querySource(jobCreated),stackBreakdowns: false,breakdownFilter: null,cohorts: undefined,@@ -26,34 +30,35 @@ const deps = (overrides?: Partial<AggregatedDisplayLabelDeps>): AggregatedDispladescribe('getAggregatedDisplayLabel', () => {it('prefers the series custom name over the event name when there is no breakdown', () => {- const r = mkResult({- label: 'Job Created',- action: { id: '0', type: 'events', name: 'Job Created', custom_name: 'Articles' },- })- expect(getAggregatedDisplayLabel(r, deps())).toBe('Articles')+ const r = mkResult({ label: 'Job Created', order: 0 })+ expect(+ getAggregatedDisplayLabel(r, deps({ querySource: querySource({ ...jobCreated, custom_name: 'Articles' }) }))+ ).toBe('Articles')})it('falls back to the event name when no custom name is set', () => {- const r = mkResult({ label: 'Job Created', action: { id: '0', type: 'events', name: 'Job Created' } })+ const r = mkResult({ label: 'Job Created', order: 0 })expect(getAggregatedDisplayLabel(r, deps())).toBe('Job Created')})it('uses the breakdown value, not the custom name, when a breakdown is present', () => {const breakdownFilter: BreakdownFilter = { breakdown: '$browser', breakdown_type: 'event' }- const r = mkResult({- label: 'Chrome',- breakdown_value: 'Chrome',- action: { id: '0', type: 'events', name: 'Job Created', custom_name: 'Job Created' },- })- expect(getAggregatedDisplayLabel(r, deps({ breakdownFilter }))).toBe('Chrome')+ const r = mkResult({ label: 'Chrome', breakdown_value: 'Chrome', order: 0 })+ expect(+ getAggregatedDisplayLabel(+ r,+ deps({ breakdownFilter, querySource: querySource({ ...jobCreated, custom_name: 'Job Created' }) })+ )+ ).toBe('Chrome')})it('uses the entity name for the band in stacked-breakdown mode', () => {- const r = mkResult({- label: 'Chrome',- breakdown_value: 'Chrome',- action: { id: '0', type: 'events', name: 'Job Created', custom_name: 'Articles' },- })- expect(getAggregatedDisplayLabel(r, deps({ stackBreakdowns: true }))).toBe('Articles')+ const r = mkResult({ label: 'Chrome', breakdown_value: 'Chrome', order: 0 })+ expect(+ getAggregatedDisplayLabel(+ r,+ deps({ stackBreakdowns: true, querySource: querySource({ ...jobCreated, custom_name: 'Articles' }) })+ )+ ).toBe('Articles')})})diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.tsindex 7def54a21a66..42fa427be7ce 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.ts@@ -1,7 +1,9 @@-import { formatBreakdownLabel, getDisplayNameFromEntityFilter } from 'scenes/insights/utils'+import { formatBreakdownLabel } from 'scenes/insights/utils'+import { getResultSeries } from 'scenes/insights/utils/resultSeries'+import { getResultSeriesName } from 'scenes/insights/utils/resultSeriesName'import { FormatPropertyValueForDisplayFunction } from '~/models/propertyDefinitionsModel'-import { BreakdownFilter } from '~/queries/schema/schema-general'+import { BreakdownFilter, InsightQueryNode } from '~/queries/schema/schema-general'import { CohortType } from '~/types'import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'@@ -9,6 +11,7 @@ import type { IndexedTrendResult } from 'products/product_analytics/frontend/insimport { humanizeSeriesLabel } from '../shared/humanizeSeriesLabel'export interface AggregatedDisplayLabelDeps {+ querySource: InsightQueryNode | null | undefinedstackBreakdowns: booleanbreakdownFilter: BreakdownFilter | null | undefinedcohorts: CohortType[] | undefined@@ -17,9 +20,10 @@ export interface AggregatedDisplayLabelDeps {/** Category-axis label for a single band of the aggregated (Bar chart - Total value) chart. */export function getAggregatedDisplayLabel(r: IndexedTrendResult, deps: AggregatedDisplayLabelDeps): string {+ const seriesName = getResultSeriesName(getResultSeries(deps.querySource, r))if (deps.stackBreakdowns) {// Breakdown values within the band are distinguished by color and the tooltip.- return getDisplayNameFromEntityFilter(r.action) ?? humanizeSeriesLabel(r.label)+ return seriesName ?? humanizeSeriesLabel(r.label)}if (r.breakdown_value != null) {return formatBreakdownLabel(@@ -34,5 +38,5 @@ export function getAggregatedDisplayLabel(r: IndexedTrendResult, deps: Aggregate// Custom name wins over the event name, matching the legacy LineGraph y-axis. Series sharing// an event are differentiated only by their custom name, so falling back to the event name// would collapse them all onto the same label.- return getDisplayNameFromEntityFilter(r.action) ?? humanizeSeriesLabel(r.label)+ return seriesName ?? humanizeSeriesLabel(r.label)}diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.tsindex fdce5bcd2201..f757fecd4177 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts@@ -113,10 +113,8 @@ describe('buildTrendsBarAggregatedSeries', () => {it('splits same-label results into separate bands when they come from different series (no breakdown)', () => {// Four trends series of the same event surface label="$pageview" each but have- // distinct action.order — they should not collapse onto one band.- const results = [0, 1, 2, 3].map((order) =>- mkResult({ id: `r${order}`, label: '$pageview', action: { order } })- )+ // distinct order — they should not collapse onto one band.+ const results = [0, 1, 2, 3].map((order) => mkResult({ id: `r${order}`, label: '$pageview', order }))const { labels, displayLabels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })expect(displayLabels).toEqual(['$pageview', '$pageview', '$pageview', '$pageview'])expect(new Set(labels).size).toBe(4)diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.tsindex 3884c73c183b..0e8c9a22aa2c 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts@@ -17,8 +17,7 @@ export interface TrendsBarResultLike {days?: string[]compare?: booleancompare_label?: string | null- action?: { order?: number } | null- // Formula rows carry a top-level `order` instead of `action.order`.+ // The series index, or the formula index on a formula row.order?: number | nullbreakdown_value?: unknownfilter?: unknown@@ -207,7 +206,7 @@ export function buildTrendsBarAggregatedSeries<R extends TrendsBarResultLike, M// Stacked breakdowns share a band and genuinely stack, so they stay as N sparse series.const labels = visible.map((r) => {- const seriesId = r.action?.order ?? r.order ?? 0+ const seriesId = r.order ?? 0return `${seriesId}${BAND_KEY_SEP}${r.compare_label ?? ''}`})const series = visible.map((r, index) => {diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsxindex 62747a4b7cb7..38b451625339 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx@@ -48,7 +48,7 @@ const handleChartError = makeChartErrorHandler('trends-lifecycle-chart')// Lifecycle rows label themselves by status ("New", "Returning", ...) — not by// the underlying event/action. The row's ribbon color already identifies the// series, so we render the label as plain text and skip InsightLabel (which-// would otherwise prefer `action.name` like "$pageview").+// would otherwise prefer the series name like "Pageview").const renderLifecycleSeriesLabel = (datum: SeriesDatum): React.ReactNode => datum.labelexport function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLifecycleChartProps): JSX.Element | null {@@ -74,7 +74,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi} = useValues(trendsDataLogic(insightProps))const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)- // Lifecycle statuses all share the same resultCustomizationKey (same action.order), so+ // Lifecycle statuses all share the same resultCustomizationKey (same series order), so// useInsightsLegendConfig can't distinguish them — build the config inline and let the// chart manage toggle state internally.const legendRenderItem = useChartLegendSeriesMenu({ surface: 'lifecycle', seriesCount: indexedResults.length })@@ -112,6 +112,11 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi[formatValue, showValuesOnSeries, showPercentagesOnSeries])+ const buildMeta = useCallback(+ (r: IndexedTrendResult): TrendsSeriesMeta => buildTrendsSeriesMeta(r, querySource),+ [querySource]+ )+const {series,labels,@@ -120,7 +125,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi() =>buildLifecycleChartModel<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {getColor: (status) => getBarColorFromStatus((status ?? 'new') as LifecycleToggle),- buildMeta: buildTrendsSeriesMeta,+ buildMeta,// Bands are keyed by these strings, so they must be unique per point. Display// labels are not (week and hour labels omit the year, so multi-year ranges// repeat them); use the ISO days, which ticks and tooltips format from.@@ -140,6 +145,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi}),[indexedResults,+ buildMeta,currentPeriodResult?.labels,currentPeriodResult?.days,isStacked,diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.tsindex 2a20fcabf912..d38ea3e8eb75 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts@@ -23,7 +23,6 @@ export interface TrendsLifecycleResultLike {data: number[]status?: stringdays?: string[]- action?: { order?: number } | null}function lifecycleStatusOrder(status: string | undefined): number {diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsxindex 4e56a6642312..9e9e23411bc6 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx@@ -252,7 +252,10 @@ describe('TrendsLineChart', () => {it('shows zero-count series alongside active ones', async () => {renderInsight({query: buildTrendsQuery({- series: [{ kind: NodeKind.EventsNode, event: 'ZeroCounts', name: 'ZeroCounts' }],+ series: [+ { kind: NodeKind.EventsNode, event: 'EmptySeries', name: 'EmptySeries' },+ { kind: NodeKind.EventsNode, event: 'ActiveSeries', name: 'ActiveSeries' },+ ],}),})@@ -506,7 +509,10 @@ describe('TrendsLineChart', () => {it('renders without crashing when series contain zero values', async () => {renderInsight({query: buildTrendsQuery({- series: [{ kind: NodeKind.EventsNode, event: 'ZeroCounts', name: 'ZeroCounts' }],+ series: [+ { kind: NodeKind.EventsNode, event: 'EmptySeries', name: 'EmptySeries' },+ { kind: NodeKind.EventsNode, event: 'ActiveSeries', name: 'ActiveSeries' },+ ],trendsFilter: { yAxisScaleType: 'log10' },}),})@@ -596,7 +602,10 @@ describe('TrendsLineChart', () => {// later series (here, ActiveSeries) had real counts.renderInsight({query: buildTrendsQuery({- series: [{ kind: NodeKind.EventsNode, event: 'ZeroCounts', name: 'ZeroCounts' }],+ series: [+ { kind: NodeKind.EventsNode, event: 'EmptySeries', name: 'EmptySeries' },+ { kind: NodeKind.EventsNode, event: 'ActiveSeries', name: 'ActiveSeries' },+ ],}),})diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex 4d562cb4f24b..7286cb372a19 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -119,14 +119,20 @@ export function TrendsLineChart({const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const buildMeta = useCallback(+ (r: IndexedTrendResult): TrendsSeriesMeta => buildTrendsSeriesMeta(r, querySource),+ [querySource]+ )+const seriesIdentification = useMemo(- () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),- [indexedResults]+ () => getSeriesIdentification((indexedResults ?? []).map(buildMeta)),+ [indexedResults, buildMeta])const getLabel = useCallback((r: IndexedTrendResult): string =>getTrendsSeriesDisplayLabel(r, {+ querySource,breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,@@ -134,6 +140,7 @@ export function TrendsLineChart({seriesIdentification,}),[+ querySource,breakdownFilter,allCohorts?.results,formatPropertyValueForDisplay,@@ -290,7 +297,7 @@ export function TrendsLineChart({// of being dropped here, so the legend can restore them.getHidden: undefined,getLabel,- buildMeta: buildTrendsSeriesMeta,+ buildMeta,}),[indexedResults,@@ -300,6 +307,7 @@ export function TrendsLineChart({isStickiness,getTrendsColor,getLabel,+ buildMeta,])diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.tsindex 435d805719c3..8d97ec958ca7 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts@@ -23,7 +23,6 @@ export interface TrendsResultLike {days?: string[]compare?: booleancompare_label?: string | null- action?: { order?: number } | nullbreakdown_value?: unknownfilter?: unknown}diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.test.tsindex eb87c6e81c70..9fc43408f1a3 100644--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.test.ts@@ -1,3 +1,5 @@+import { type ActionsNode, NodeKind, type TrendsQuery } from '~/queries/schema/schema-general'+import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'import { buildTrendsPieSeries } from './trendsPieTransforms'@@ -13,7 +15,6 @@ function makeResult(overrides: Partial<IndexedTrendResult> = {}): IndexedTrendRedays: [],labels: [],count: 0,- action: undefined,breakdown_value: undefined,compare_label: undefined,...overrides,@@ -29,7 +30,7 @@ describe('buildTrendsPieSeries', () => {makeResult({ id: 1, label: 'B', aggregated_value: 30 }),makeResult({ id: 2, label: 'C', aggregated_value: 60 }),]- const series = buildTrendsPieSeries(results, { getColor })+ const series = buildTrendsPieSeries(results, { querySource: null, getColor })expect(series).toHaveLength(3)expect(series.map((s) => s.key)).toEqual(['0', '1', '2'])@@ -39,13 +40,14 @@ describe('buildTrendsPieSeries', () => {it('assigns colors via getColor', () => {const results = [makeResult({ id: 0 }), makeResult({ id: 1 }), makeResult({ id: 2 })]- const series = buildTrendsPieSeries(results, { getColor })+ const series = buildTrendsPieSeries(results, { querySource: null, getColor })expect(series.map((s) => s.color)).toEqual(['#001', '#002', '#003'])})it('marks hidden series as visibility.excluded', () => {const results = [makeResult({ id: 0 }), makeResult({ id: 1 }), makeResult({ id: 2 })]const series = buildTrendsPieSeries(results, {+ querySource: null,getColor,getHidden: (_, i) => i === 1,})@@ -58,6 +60,7 @@ describe('buildTrendsPieSeries', () => {makeResult({ id: 1, label: 'raw-b', breakdown_value: 'b' }),]const series = buildTrendsPieSeries(results, {+ querySource: null,getColor,getLabel: (r) => `Breakdown: ${r.breakdown_value}`,})@@ -66,30 +69,34 @@ describe('buildTrendsPieSeries', () => {it('falls back to label when getLabel is omitted', () => {const results = [makeResult({ id: 0, label: 'fallback' })]- const series = buildTrendsPieSeries(results, { getColor })+ const series = buildTrendsPieSeries(results, { querySource: null, getColor })expect(series[0].label).toBe('fallback')})it('clamps missing aggregated_value to 0', () => {// aggregated_value is required by the type, but we want to be defensive against partial data.const results = [makeResult({ id: 0, label: 'A', aggregated_value: undefined as unknown as number })]- const series = buildTrendsPieSeries(results, { getColor })+ const series = buildTrendsPieSeries(results, { querySource: null, getColor })expect(series[0].data).toEqual([0])})- it('carries action / breakdown_value / compare_label through TrendsSeriesMeta', () => {- const action = { id: 7, order: 3 } as unknown as IndexedTrendResult['action']+ it('carries the series / breakdown_value / compare_label through TrendsSeriesMeta', () => {+ const signups: ActionsNode = { kind: NodeKind.ActionsNode, id: 7, name: 'Signed up' }+ const querySource: TrendsQuery = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }, signups],+ }const results = [makeResult({id: 0,label: 'A',- action,+ order: 1,breakdown_value: 'chrome',days: ['2024-01-01'],}),]- const series = buildTrendsPieSeries(results, { getColor })- expect(series[0].meta?.action).toBe(action)+ const series = buildTrendsPieSeries(results, { querySource, getColor })+ expect(series[0].meta?.series.node).toEqual(signups)expect(series[0].meta?.breakdown_value).toBe('chrome')expect(series[0].meta?.days).toEqual(['2024-01-01'])})diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.tsindex e1ea3c357807..a66494f33205 100644--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts@@ -1,11 +1,16 @@import type { Series } from '@posthog/quill-charts'+import { getResultSeries, getResultSeriesIndex } from 'scenes/insights/utils/resultSeries'++import type { InsightQueryNode } from '~/queries/schema/schema-general'+import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'import { humanizeSeriesLabel } from '../shared/humanizeSeriesLabel'import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'export interface BuildTrendsPieSeriesOpts<R> {+ querySource: InsightQueryNode | null | undefined/** Resolved color per result (typically `getTrendsColor`). */getColor: (r: R, index: number) => string/** True when the result should be excluded from rendering. */@@ -36,11 +41,11 @@ export function buildTrendsPieSeries<R extends IndexedTrendResult>(data: [r.aggregated_value ?? 0],color: opts.getColor(r, index),meta: {- action: r.action ?? undefined,+ series: getResultSeries(opts.querySource, r),breakdown_value: r.breakdown_value,compare_label: r.compare_label,days: r.days,- order: r.action?.order ?? r.id,+ order: getResultSeriesIndex(opts.querySource, r) ?? r.id,filter: r.filter,},visibility: excluded ? { excluded: true } : undefined,diff --git a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsxindex 836b7191001a..0f3033ba20a3 100644--- a/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/TrendsTooltip.tsx@@ -44,7 +44,7 @@ interface TrendsTooltipProps {renderCount?: (value: number) => string// Overrides the default SeriesLetter + InsightLabel row renderer. Mirrors the// legacy ActionsLineGraph escape hatch used for lifecycle, where the label- // is the lifecycle status itself (e.g. "New") and InsightLabel's action.name+ // is the lifecycle status itself (e.g. "New") and InsightLabel's series name// would otherwise mask it.renderSeriesOverride?: (datum: SeriesDatum) => React.ReactNode}@@ -73,7 +73,7 @@ export function TrendsTooltip({}: TrendsTooltipProps): React.ReactElement {const seriesData = useMemo<SeriesDatum[]>(() => {const data = context.seriesData.map((entry, idx) => {- const meta = entry.series.meta ?? {}+ const meta: Partial<TrendsSeriesMeta> = entry.series.meta ?? {}return {id: idx,dataIndex: context.dataIndex,@@ -82,7 +82,7 @@ export function TrendsTooltip({label: entry.series.label,color: entry.color,count: entry.value,- action: meta.action,+ series: meta.series,breakdown_value: meta.breakdown_value,compare_label: meta.compare_label,date_label: meta.days?.[context.dataIndex],@@ -138,7 +138,7 @@ export function TrendsTooltip({<SeriesLetterclassName="mr-2"hasBreakdown={hasBreakdown}- seriesIndex={datum.action?.order ?? datum.id}+ seriesIndex={datum.series?.order ?? datum.id}// Previous-period series arrive pre-dimmed (rgba); the ribbon keeps the dim to// mark the period, but the identifier glyph must stay legible — give it the// opaque color.diff --git a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.tsindex 21cf143e08be..b4ea84aee8f0 100644--- a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts+++ b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts@@ -1,48 +1,78 @@+import { FLAG_EVALUATIONS_TABLE } from 'scenes/feature-flags/flagEvaluationsTable'++import { AnyEntityNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'import { getTrendsSeriesDisplayLabel, type TrendsSeriesLabelDeps } from './getTrendsSeriesDisplayLabel'-const NO_BREAKDOWN_DEPS: TrendsSeriesLabelDeps = {+const seriesQuery = (node: AnyEntityNode): TrendsQuery => ({ kind: NodeKind.TrendsQuery, series: [node] })++const signups = seriesQuery({+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'Signups',+})++const formulaQuery: TrendsQuery = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ trendsFilter: { formula: 'A + B' },+}++const NO_BREAKDOWN_DEPS: Omit<TrendsSeriesLabelDeps, 'querySource'> = {breakdownFilter: null,cohorts: undefined,formatPropertyValueForDisplay: undefined,}const BREAKDOWN_DEPS: TrendsSeriesLabelDeps = {+ querySource: signups,breakdownFilter: { breakdown_type: 'event', breakdown: '$browser' },cohorts: undefined,formatPropertyValueForDisplay: undefined,}const makeResult = (overrides: Partial<IndexedTrendResult>): IndexedTrendResult =>- ({ id: 0, label: '$pageview', data: [], ...overrides }) as IndexedTrendResult+ ({ id: 0, label: '$pageview', data: [], order: 0, ...overrides }) as IndexedTrendResultdescribe('getTrendsSeriesDisplayLabel', () => {it.each([- ['custom name wins over the event name', { action: { name: '$pageview', custom_name: 'Signups' } }, 'Signups'],- ['humanizes the event name when no custom name', { action: { name: '$pageview' } }, 'Pageview'],- ['uses the action name when not a built-in event', { action: { name: 'purchase' } }, 'purchase'],+ ['custom name wins over the event name', signups, {}, 'Signups'],[- 'shows a flag calls series as the event',- {- action: {- type: 'events',- id: 'posthog.flag_evaluations',- name: 'posthog.flag_evaluations',- custom_name: null,- },- label: 'posthog.flag_evaluations',- },- 'Feature flag called',+ 'humanizes the event name when no custom name',+ seriesQuery({ kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }),+ {},+ 'Pageview',+ ],+ [+ 'uses the event name when not a built-in event',+ seriesQuery({ kind: NodeKind.EventsNode, event: 'purchase', name: 'purchase' }),+ {},+ 'purchase',],[- 'falls back to the humanized label when there is no action (formula row)',- { action: null, label: 'A + B' },- 'A + B',+ 'shows a flag calls series as the event',+ seriesQuery({+ kind: NodeKind.DataWarehouseNode,+ id: FLAG_EVALUATIONS_TABLE,+ table_name: FLAG_EVALUATIONS_TABLE,+ name: FLAG_EVALUATIONS_TABLE,+ id_field: 'uuid',+ timestamp_field: 'timestamp',+ distinct_id_field: 'distinct_id',+ }),+ { label: FLAG_EVALUATIONS_TABLE },+ 'Feature flag called',],- ])('%s', (_name, overrides, expected) => {+ ['falls back to the humanized label on a formula row', formulaQuery, { label: 'A + B' }, 'A + B'],+ ])('%s', (_name, querySource, overrides, expected) => {expect(- getTrendsSeriesDisplayLabel(makeResult(overrides as Partial<IndexedTrendResult>), NO_BREAKDOWN_DEPS)+ getTrendsSeriesDisplayLabel(makeResult(overrides as Partial<IndexedTrendResult>), {+ ...NO_BREAKDOWN_DEPS,+ querySource,+ })).toBe(expected)})@@ -57,13 +87,12 @@ describe('getTrendsSeriesDisplayLabel', () => {['the breakdown value alone for a single-series query', {}, { isSingleSeriesDefinition: true }, 'Chrome'],['the formula name and breakdown value for a formula row',- { action: null, label: 'A + B' },- {},+ { label: 'A + B' },+ { querySource: formulaQuery },'A + B · Chrome',],])('resolves to %s', (_name, resultOverrides, depOverrides, expected) => {const result = makeResult({- action: { custom_name: 'Signups' } as IndexedTrendResult['action'],breakdown_value: 'Chrome',...(resultOverrides as Partial<IndexedTrendResult>),})diff --git a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.tsindex 9d9d34cf6046..70f50d332b1e 100644--- a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts+++ b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts@@ -1,9 +1,10 @@-import { toDisplayEntityFilter } from 'lib/components/EntityFilterInfo'import { alphabet } from 'lib/utils/strings'-import { formatBreakdownLabel, getDisplayNameFromEntityFilter } from 'scenes/insights/utils'+import { formatBreakdownLabel } from 'scenes/insights/utils'+import { getResultSeries } from 'scenes/insights/utils/resultSeries'+import { getResultSeriesName } from 'scenes/insights/utils/resultSeriesName'import type { FormatPropertyValueForDisplayFunction } from '~/models/propertyDefinitionsModel'-import type { BreakdownFilter } from '~/queries/schema/schema-general'+import type { BreakdownFilter, InsightQueryNode } from '~/queries/schema/schema-general'import type { CohortType } from '~/types'import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'@@ -12,6 +13,7 @@ import type { SeriesIdentification } from '../../shared/seriesIdentification'import { humanizeSeriesLabel } from './humanizeSeriesLabel'export interface TrendsSeriesLabelDeps {+ querySource: InsightQueryNode | null | undefinedbreakdownFilter: BreakdownFilter | null | undefinedcohorts: CohortType[] | undefinedformatPropertyValueForDisplay: FormatPropertyValueForDisplayFunction | undefined@@ -20,8 +22,8 @@ export interface TrendsSeriesLabelDeps {}export function getTrendsSeriesDisplayLabel(r: IndexedTrendResult, deps: TrendsSeriesLabelDeps): string {- const seriesName =- getDisplayNameFromEntityFilter(r.action && toDisplayEntityFilter(r.action)) ?? humanizeSeriesLabel(r.label)+ const series = getResultSeries(deps.querySource, r)+ const seriesName = getResultSeriesName(series) ?? humanizeSeriesLabel(r.label)if (r.breakdown_value != null) {const breakdownLabel = formatBreakdownLabel(r.breakdown_value,@@ -35,9 +37,7 @@ export function getTrendsSeriesDisplayLabel(r: IndexedTrendResult, deps: TrendsSreturn breakdownLabel}const seriesPrefix =- deps.seriesIdentification === 'letter-and-name'- ? `${alphabet[r.action?.order ?? r.order ?? 0]} ${seriesName}`- : seriesName+ deps.seriesIdentification === 'letter-and-name' ? `${alphabet[series.order]} ${seriesName}` : seriesNamereturn `${seriesPrefix} · ${breakdownLabel}`}return seriesNamediff --git a/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts b/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.tsindex b9ad5e6232eb..05a7d09c3847 100644--- a/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts+++ b/products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta.ts@@ -1,12 +1,14 @@+import { ResultSeries, getResultSeries } from 'scenes/insights/utils/resultSeries'+import type { Noun } from '~/models/groupsModel'-import type { ActionFilter } from '~/types'+import type { InsightQueryNode } from '~/queries/schema/schema-general'import type { SeriesDatum } from 'products/product_analytics/frontend/insights/shared/InsightTooltip/insightTooltipUtils'import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'export type TrendsSeriesMeta = {- action?: ActionFilter- /** Series name for results without an `action` — formula results carry their formula label here. */+ series: ResultSeries+ /** Series name for results without a series node — formula results carry their formula label here. */series_name?: stringbreakdown_value?: string | number | string[]compare_label?: SeriesDatum['compare_label']@@ -15,17 +17,23 @@ export type TrendsSeriesMeta = {filter?: SeriesDatum['filter']}-export const buildTrendsSeriesMeta = (r: IndexedTrendResult): TrendsSeriesMeta => ({- action: r.action ?? undefined,- // Formula results have no `action`; their raw label (custom name or "Formula (…)") is the- // only series name available for tooltip attribution.- series_name: r.action ? undefined : r.label,- breakdown_value: r.breakdown_value,- compare_label: r.compare_label,- days: r.days,- order: r.order ?? r.action?.order ?? 0,- filter: r.filter,-})+export const buildTrendsSeriesMeta = (+ r: IndexedTrendResult,+ querySource: InsightQueryNode | null | undefined+): TrendsSeriesMeta => {+ const series = getResultSeries(querySource, r)+ return {+ series,+ // Formula results have no series node; their raw label (custom name or "Formula (…)") is the+ // only series name available for tooltip attribution.+ series_name: series.node ? undefined : r.label,+ breakdown_value: r.breakdown_value,+ compare_label: r.compare_label,+ days: r.days,+ order: series.order,+ filter: r.filter,+ }+}/** Resolve the `groupTypeLabel` shown by tooltips and persons-modal titles.* `'people'` is the default; `'none'` suppresses the noun; anything elsediff --git a/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx b/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsxindex 9f383ecc92a5..d82a3d26a376 100644--- a/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx@@ -77,9 +77,14 @@ export function useTrendsPartOfWholeChart({isSingleSeriesDefinition,} = useValues(trendsDataLogic(insightProps))+ const buildMeta = useCallback(+ (r: IndexedTrendResult): TrendsSeriesMeta => buildTrendsSeriesMeta(r, querySource),+ [querySource]+ )+const seriesIdentification = useMemo(- () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),- [indexedResults]+ () => getSeriesIdentification((indexedResults ?? []).map(buildMeta)),+ [indexedResults, buildMeta])const resolvedGroupTypeLabel =@@ -97,6 +102,7 @@ export function useTrendsPartOfWholeChart({const getLabel = useCallback((r: IndexedTrendResult): string =>getTrendsSeriesDisplayLabel(r, {+ querySource,breakdownFilter,cohorts: allCohorts.results,formatPropertyValueForDisplay,@@ -104,6 +110,7 @@ export function useTrendsPartOfWholeChart({seriesIdentification,}),[+ querySource,breakdownFilter,allCohorts.results,formatPropertyValueForDisplay,@@ -115,13 +122,14 @@ export function useTrendsPartOfWholeChart({const series: Series<TrendsSeriesMeta>[] = useMemo(() =>buildTrendsPieSeries(indexedResults ?? [], {+ querySource,getColor: getTrendsColor,// Hidden series are listed (dimmed) and excluded via config.legend.hiddenKeys instead// of being dropped here, so the legend can restore them.getHidden: undefined,getLabel,}),- [indexedResults, getTrendsColor, getLabel]+ [indexedResults, querySource, getTrendsColor, getLabel])const visibleResults = useMemo(