Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(insights): resolve trends result rows to their query series (#116814)

Thomas Obermüllerf76fc32e9171
diff --git a/frontend/src/lib/components/InsightLabel/index.test.tsx b/frontend/src/lib/components/InsightLabel/index.test.tsx
index 94aaef2e4a7a..c562ab0065e4 100644
--- a/frontend/src/lib/components/InsightLabel/index.test.tsx
+++ b/frontend/src/lib/components/InsightLabel/index.test.tsx
@@ -3,8 +3,11 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
import { Provider } from 'kea'
+import type { ResultSeries } from 'scenes/insights/utils/resultSeries'
+
+import { EventsNode, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { ActionFilter } from '~/types'
+import { ActionFilter, HogQLMathType } from '~/types'
import { InsightLabel } from './index'
@@ -22,6 +25,22 @@ function hogqlAction(overrides: Partial<ActionFilter> = {}): ActionFilter {
} as ActionFilter
}
+function hogqlSeries(overrides: Partial<EventsNode> = {}): ResultSeries {
+ const node: EventsNode = {
+ kind: NodeKind.EventsNode,
+ event: '$pageview',
+ name: '$pageview',
+ math: HogQLMathType.HogQL,
+ math_hogql: HOGQL_EXPRESSION,
+ ...overrides,
+ }
+ return {
+ order: 0,
+ node,
+ math: { math: node.math, math_property: node.math_property, math_hogql: node.math_hogql },
+ }
+}
+
describe('InsightLabel — hideHogQLTagWhenCustomName', () => {
beforeEach(() => {
initKeaTests()
@@ -39,8 +58,11 @@ describe('InsightLabel — hideHogQLTagWhenCustomName', () => {
)
}
- it('hides the SQL expression tag when the flag is on, the series is named, and math is hogql', () => {
- renderLabel({ action: hogqlAction({ custom_name: 'Revenue' }), hideHogQLTagWhenCustomName: true })
+ it.each<[string, Parameters<typeof InsightLabel>[0]]>([
+ ['a custom name', { action: hogqlAction({ custom_name: 'Revenue' }) }],
+ ['a query series renamed through its name', { series: hogqlSeries({ name: 'Revenue' }) }],
+ ])('hides the SQL expression tag when the flag is on, the series has %s, and math is hogql', (_, props) => {
+ renderLabel({ ...props, hideHogQLTagWhenCustomName: true })
expect(screen.queryByText(HOGQL_EXPRESSION)).not.toBeInTheDocument()
})
diff --git a/frontend/src/lib/components/InsightLabel/index.tsx b/frontend/src/lib/components/InsightLabel/index.tsx
index 73fd2347d916..0f472901eaa9 100644
--- a/frontend/src/lib/components/InsightLabel/index.tsx
+++ b/frontend/src/lib/components/InsightLabel/index.tsx
@@ -5,7 +5,7 @@ import { useValues } from 'kea'
import { LemonTag } from '@posthog/lemon-ui'
-import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
+import { DisplayableEntity, EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import { parseAliasToReadable } from 'lib/components/PathCleanFilters/PathCleanFilterItem'
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { SeriesLetter } from 'lib/components/SeriesGlyph'
@@ -13,6 +13,7 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { hexToRGBA } from 'lib/utils/colors'
import { capitalizeFirstLetter, midEllipsis } from 'lib/utils/strings'
import { formatEventName } from 'scenes/insights/utils'
+import { ResultSeries, getResultSeriesCustomName } from 'scenes/insights/utils/resultSeries'
import { groupsModel } from '~/models/groupsModel'
import { ActionFilter, BreakdownKeyType } from '~/types'
@@ -30,6 +31,8 @@ export enum IconSize {
// InsightsLabel pretty prints the action (or event) returned from /insights
interface InsightsLabelProps {
seriesColor?: string
+ /** The result row's series, from `getResultSeries`. Takes precedence over `action`. */
+ series?: ResultSeries | null
action?: ActionFilter | null
value?: string
className?: string
@@ -41,9 +44,9 @@ interface InsightsLabelProps {
iconSize?: IconSize // Size of the series color icon
iconStyle?: Record<string, any> // style on series color icon
seriesStatus?: string // Used by lifecycle chart to display the series name
- fallbackName?: string // Name to display for the series if it can be determined from `action`
+ fallbackName?: string // Name to display when the label has no series to name, e.g. on a formula row
hasMultipleSeries?: boolean // Whether the query defines multiple series (not breakdown values). Derived from !isSingleSeriesDefinition.
- showCountedByTag?: boolean // Force 'counted by' tag to show (always shown when action.math is set)
+ showCountedByTag?: boolean // Force 'counted by' tag to show (always shown when the series math is set)
allowWrap?: boolean // Allow wrapping to multiple lines (useful for long values like URLs)
onLabelClick?: () => void // Click handler for inner label
showEventName?: boolean // Override internally calculated to always show event name
@@ -104,6 +107,7 @@ function MathTag({ math, mathProperty, mathHogQL, mathGroupTypeIndex }: MathTagP
export function InsightLabel({
seriesColor = '#000000',
+ series,
action,
value,
className,
@@ -129,16 +133,15 @@ export function InsightLabel({
}: InsightsLabelProps): JSX.Element {
const showEventName = _showEventName || !breakdownValue || (hasMultipleSeries && !Array.isArray(breakdownValue))
- const displayAction = action
- ? {
- ...action,
- name: formatEventName(action.name),
- }
- : undefined
+ const entity: DisplayableEntity | null | undefined = series ? series.node : action
+ const math = series ? series.math : action
+ const seriesIndex = series ? (series.node ? series.order : undefined) : action?.order
+ const customName = series ? series.node && getResultSeriesCustomName(series.node) : action?.custom_name
+ const displayEntity = entity ? { ...entity, name: formatEventName(entity.name) } : undefined
const eventName = seriesStatus
? capitalizeFirstLetter(seriesStatus)
- : displayAction?.name || formatEventName(fallbackName) || ''
+ : displayEntity?.name || formatEventName(fallbackName) || ''
const iconSizePx = iconSize === IconSize.Large ? 14 : iconSize === IconSize.Medium ? 12 : 10
const pillValues = [...(hideBreakdown ? [] : [breakdownValue].flat()), hideCompare ? null : compareValue].filter(
@@ -163,12 +166,8 @@ export function InsightLabel({
}}
/>
)}
- {hasMultipleSeries && !hideIcon && action?.order !== undefined && (
- <SeriesLetter
- seriesIndex={action.order}
- seriesColor={seriesColor}
- hasBreakdown={!!breakdownValue}
- />
+ {hasMultipleSeries && !hideIcon && seriesIndex !== undefined && (
+ <SeriesLetter seriesIndex={seriesIndex} seriesColor={seriesColor} hasBreakdown={!!breakdownValue} />
)}
<div
className={clsx('flex items-center w-fit gap-x-2', allowWrap && 'flex-wrap')}
@@ -176,9 +175,9 @@ export function InsightLabel({
>
{showEventName && (
<>
- {displayAction ? (
+ {displayEntity ? (
<EntityFilterInfo
- filter={displayAction}
+ filter={displayEntity}
allowWrap={allowWrap}
showSingleName={showSingleName}
/>
@@ -194,14 +193,14 @@ export function InsightLabel({
</>
)}
- {((action?.math && action.math !== 'total') || showCountedByTag) &&
- !(hideHogQLTagWhenCustomName && action?.custom_name && action?.math === 'hogql') && (
+ {((math?.math && math.math !== 'total') || showCountedByTag) &&
+ !(hideHogQLTagWhenCustomName && customName && math?.math === 'hogql') && (
<div className="insights-label__math flex flex-nowrap items-center gap-x-1">
<MathTag
- math={action?.math}
- mathProperty={action?.math_property}
- mathHogQL={action?.math_hogql}
- mathGroupTypeIndex={action?.math_group_type_index}
+ math={math?.math}
+ mathProperty={math?.math_property}
+ mathHogQL={math?.math_hogql}
+ mathGroupTypeIndex={math?.math_group_type_index}
/>
</div>
)}
diff --git a/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx b/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
index 419af134cc00..097feb7de49f 100644
--- a/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
+++ b/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
@@ -10,6 +10,7 @@ import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
import { formatBreakdownLabel, getTrendResultCustomizationKey } from 'scenes/insights/utils'
+import { getResultSeries } from 'scenes/insights/utils/resultSeries'
import { teamLogic } from 'scenes/teamLogic'
import { cohortsModel } from '~/models/cohortsModel'
@@ -42,6 +43,7 @@ export function InsightLegendRow({ item, readOnly = false }: InsightLegendRowPro
areAllSeriesVisible,
legendSeriesIsolationMenuEligible,
getIsOnlyVisibleSeriesInLegend,
+ querySource,
} = useValues(trendsDataLogic(insightProps))
const { toggleResultHidden, toggleOtherSeriesHidden, toggleAllResultsHidden } = useActions(
trendsDataLogic(insightProps)
@@ -49,8 +51,8 @@ export function InsightLegendRow({ item, readOnly = false }: InsightLegendRowPro
let highlighted = false
if (highlightedSeries) {
- const currentKey = getTrendResultCustomizationKey(resultCustomizationBy, item)
- const highlightedKey = getTrendResultCustomizationKey(resultCustomizationBy, highlightedSeries)
+ const currentKey = getTrendResultCustomizationKey(resultCustomizationBy, item, querySource)
+ const highlightedKey = getTrendResultCustomizationKey(resultCustomizationBy, highlightedSeries, querySource)
highlighted = currentKey === highlightedKey
}
const highlightStyle: Record<string, any> = highlighted
@@ -98,7 +100,7 @@ export function InsightLegendRow({ item, readOnly = false }: InsightLegendRowPro
<InsightLabel
key={item.id}
seriesColor={mainColor}
- action={item.action}
+ series={getResultSeries(querySource, item)}
fallbackName={item.breakdown_value === '' ? 'None' : item.label}
hasMultipleSeries={!isSingleSeriesDefinition}
breakdownValue={formattedBreakdownValue}
diff --git a/frontend/src/queries/nodes/InsightViz/ResultCustomizationsModal.tsx b/frontend/src/queries/nodes/InsightViz/ResultCustomizationsModal.tsx
index 9c75a993cb10..3a4c0a648643 100644
--- a/frontend/src/queries/nodes/InsightViz/ResultCustomizationsModal.tsx
+++ b/frontend/src/queries/nodes/InsightViz/ResultCustomizationsModal.tsx
@@ -9,6 +9,7 @@ import { dataThemeLogic } from 'scenes/dataThemeLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { formatBreakdownLabel } from 'scenes/insights/utils'
+import { getResultSeries } from 'scenes/insights/utils/resultSeries'
import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
@@ -85,11 +86,12 @@ type TrendsInfoProps = {
function TrendsInfo({ dataset, resultCustomizationBy }: TrendsInfoProps): JSX.Element {
const { allCohorts } = useValues(cohortsModel)
const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
- const { breakdownFilter } = useValues(insightVizDataLogic)
+ const { breakdownFilter, querySource } = useValues(insightVizDataLogic)
- // Formula series carry no entity (`action` is null), so fall back to the series label.
- const seriesName = dataset.action ? (
- <EntityFilterInfo filter={dataset.action} allowWrap={true} showSingleName={true} />
+ // A formula row has no series node, so fall back to the row label.
+ const seriesNode = getResultSeries(querySource, dataset).node
+ const seriesName = seriesNode ? (
+ <EntityFilterInfo filter={seriesNode} allowWrap={true} showSingleName={true} />
) : (
dataset.label
)
diff --git a/frontend/src/queries/nodes/InsightViz/resultCustomizationsModalLogic.ts b/frontend/src/queries/nodes/InsightViz/resultCustomizationsModalLogic.ts
index 20a0353b1957..51ae6ae72c8f 100644
--- a/frontend/src/queries/nodes/InsightViz/resultCustomizationsModalLogic.ts
+++ b/frontend/src/queries/nodes/InsightViz/resultCustomizationsModalLogic.ts
@@ -20,9 +20,18 @@ import { IndexedTrendResult } from 'products/product_analytics/frontend/insights
import type { DataColorTheme } from '../../../lib/colors'
import type { FunnelStepWithConversionMetrics } from '../../../types'
import type {
+ FunnelsQuery,
InsightFilter,
+ LifecycleQuery,
+ PathsQuery,
+ PathsV2Query,
ResultCustomizationByPosition,
ResultCustomizationByValue,
+ RetentionQuery,
+ StickinessQuery,
+ TrendsQuery,
+ WebOverviewQuery,
+ WebStatsTableQuery,
} from '../../schema/schema-general'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -35,6 +44,17 @@ export interface resultCustomizationsModalLogicValues {
isFunnels: boolean // insightVizDataLogic
isStickiness: boolean // insightVizDataLogic
isTrends: boolean // insightVizDataLogic
+ querySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null // insightVizDataLogic
getTrendsColorToken: (dataset: IndexedTrendResult) => [DataColorTheme | null, DataColorToken | null] // trendsDataLogic
resultCustomizationBy: ResultCustomizationBy // trendsDataLogic
trendsResultCustomizations:
@@ -128,7 +148,7 @@ export const resultCustomizationsModalLogic = kea<resultCustomizationsModalLogic
connect((props: InsightLogicProps) => ({
values: [
insightVizDataLogic,
- ['isTrends', 'isStickiness', 'isFunnels', 'insightFilter'],
+ ['isTrends', 'isStickiness', 'isFunnels', 'insightFilter', 'querySource'],
trendsDataLogic(props),
['resultCustomizationBy', 'resultCustomizations as trendsResultCustomizations', 'getTrendsColorToken'],
funnelDataLogic(props),
@@ -256,12 +276,14 @@ export const resultCustomizationsModalLogic = kea<resultCustomizationsModalLogic
if (values.isTrends || values.isStickiness) {
const resultCustomizationKey = getTrendResultCustomizationKey(
values.resultCustomizationBy,
- values.dataset as IndexedTrendResult
+ values.dataset as IndexedTrendResult,
+ values.querySource
)
const resultCustomization = getTrendResultCustomization(
values.resultCustomizationBy,
values.dataset as IndexedTrendResult,
- values.resultCustomizations
+ values.resultCustomizations,
+ values.querySource
)
actions.updateInsightFilter({
resultCustomizations: {
diff --git a/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts b/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts
index 8a47703a42f2..d40ee10bfb90 100644
--- a/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts
+++ b/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts
@@ -239,7 +239,7 @@ function extractTileBreakdownValues(tile: DashboardTile): BreakdownValueAndType[
const propertyKey = getBreakdownPropertyKey(querySource.breakdownFilter)
breakdownValues =
tile.insight?.result?.map((result: any): BreakdownValueAndType | null => {
- const key = getTrendDatasetKey(result)
+ const key = getTrendDatasetKey(result, querySource)
const breakdownValue = normalizeBreakdownValue(JSON.parse(key)['breakdown_value'])
return breakdownValue == null ? null : makeBreakdownValue(breakdownValue, breakdownType, propertyKey)
}) || []
diff --git a/frontend/src/scenes/insights/utils.test.ts b/frontend/src/scenes/insights/utils.test.ts
index 0452d7fa4c9d..93206f6b074d 100644
--- a/frontend/src/scenes/insights/utils.test.ts
+++ b/frontend/src/scenes/insights/utils.test.ts
@@ -19,6 +19,7 @@ import {
InsightQueryNode,
InsightVizNode,
NodeKind,
+ TrendsQuery,
} from '~/queries/schema/schema-general'
import { isEventsNode } from '~/queries/utils'
import { initKeaTests } from '~/test/init'
@@ -618,31 +619,33 @@ describe('formatBreakdownType()', () => {
})
describe('getTrendDatasetKey()', () => {
+ const seriesQuery: TrendsQuery = {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ }
+ const formulaQuery: TrendsQuery = {
+ ...seriesQuery,
+ series: [
+ { kind: NodeKind.EventsNode, event: '$pageview' },
+ { kind: NodeKind.EventsNode, event: '$autocapture' },
+ ],
+ trendsFilter: { formulaNodes: [{ formula: 'A+B' }, { formula: 'A-B' }] },
+ }
+
it('handles a simple insight', () => {
- const dataset: Partial<IndexedTrendResult> = {
- label: '$pageview',
- action: {
- id: '$pageview',
- type: 'events',
- order: 0,
- },
- }
+ const dataset: Partial<IndexedTrendResult> = { label: '$pageview', order: 0 }
- expect(getTrendDatasetKey(dataset as IndexedTrendResult)).toEqual('{"series":0}')
+ expect(getTrendDatasetKey(dataset as IndexedTrendResult, seriesQuery)).toEqual('{"series":0}')
})
it('handles insights with breakdowns', () => {
const dataset: Partial<IndexedTrendResult> = {
label: 'Opera::US',
- action: {
- id: '$pageview',
- type: 'events',
- order: 0,
- },
+ order: 0,
breakdown_value: ['Opera', 'US'],
}
- expect(getTrendDatasetKey(dataset as IndexedTrendResult)).toEqual(
+ expect(getTrendDatasetKey(dataset as IndexedTrendResult, seriesQuery)).toEqual(
'{"series":0,"breakdown_value":["Opera","US"]}'
)
})
@@ -650,27 +653,26 @@ describe('getTrendDatasetKey()', () => {
it('ignores compare periods, so that current and previous share a key', () => {
const current: Partial<IndexedTrendResult> = {
label: '$pageview',
- action: {
- id: '$pageview',
- type: 'events',
- order: 0,
- },
+ order: 0,
compare: true,
compare_label: CompareLabelType.Current,
}
const previous: Partial<IndexedTrendResult> = { ...current, compare_label: CompareLabelType.Previous }
- expect(getTrendDatasetKey(current as IndexedTrendResult)).toEqual('{"series":0}')
- expect(getTrendDatasetKey(previous as IndexedTrendResult)).toEqual('{"series":0}')
+ expect(getTrendDatasetKey(current as IndexedTrendResult, seriesQuery)).toEqual('{"series":0}')
+ expect(getTrendDatasetKey(previous as IndexedTrendResult, seriesQuery)).toEqual('{"series":0}')
})
- it('handles insights with formulas', () => {
+ it('keys a formula by its position, not the series its order would index', () => {
+ // a formula row's order indexes the formulas, so the second formula carries order 1
const dataset: Partial<IndexedTrendResult> = {
- label: 'Formula (A+B)',
- action: undefined,
+ label: 'Formula (A-B)',
+ order: 1,
+ seriesIndex: 1,
+ colorIndex: 1,
}
- expect(getTrendDatasetKey(dataset as IndexedTrendResult)).toEqual('{"series":"formula"}')
+ expect(getTrendDatasetKey(dataset as IndexedTrendResult, formulaQuery)).toEqual('{"series":"formula2"}')
})
it('keys compare periods of a formula by their shared position, not the raw series index', () => {
@@ -679,28 +681,22 @@ describe('getTrendDatasetKey()', () => {
// the colorIndex with their current-period counterpart
const previous: Partial<IndexedTrendResult> = {
label: 'Formula (A+B)',
- action: undefined,
+ order: 0,
seriesIndex: 2,
colorIndex: 0,
compare: true,
compare_label: CompareLabelType.Previous,
}
- expect(getTrendDatasetKey(previous as IndexedTrendResult)).toEqual('{"series":"formula"}')
+ expect(getTrendDatasetKey(previous as IndexedTrendResult, formulaQuery)).toEqual('{"series":"formula"}')
})
it('handles insights with non-array breakdown values', () => {
- const dataset: Partial<IndexedTrendResult> = {
- label: 'Opera',
- action: {
- id: '$pageview',
- type: 'events',
- order: 0,
- },
- breakdown_value: 'Opera',
- }
+ const dataset: Partial<IndexedTrendResult> = { label: 'Opera', order: 0, breakdown_value: 'Opera' }
- expect(getTrendDatasetKey(dataset as IndexedTrendResult)).toEqual('{"series":0,"breakdown_value":["Opera"]}')
+ expect(getTrendDatasetKey(dataset as IndexedTrendResult, seriesQuery)).toEqual(
+ '{"series":0,"breakdown_value":["Opera"]}'
+ )
})
})
diff --git a/frontend/src/scenes/insights/utils.tsx b/frontend/src/scenes/insights/utils.tsx
index 30f91f9eec1a..50941257a29d 100644
--- a/frontend/src/scenes/insights/utils.tsx
+++ b/frontend/src/scenes/insights/utils.tsx
@@ -32,6 +32,7 @@ import {
HogQLQuery,
HogQLQueryModifiers,
HogQLVariable,
+ InsightQueryNode,
InsightVizNode,
Node,
NodeKind,
@@ -53,6 +54,7 @@ import {
isNodeWithSource,
} from '~/queries/utils'
import { cleanInsightQuery } from '~/scenes/insights/utils/queryUtils'
+import { getResultSeriesIndex } from '~/scenes/insights/utils/resultSeries'
import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'
import {
ActionFilter,
@@ -610,17 +612,18 @@ export function getFunnelDatasetKey(dataset: { breakdown_value?: BreakdownKeyTyp
/** Identifies the base series — deliberately excludes `compare_label`, so that current and
* previous period datasets share a single result customization. */
-export function getTrendDatasetKey(dataset: IndexedTrendResult): string {
+export function getTrendDatasetKey(
+ dataset: IndexedTrendResult,
+ querySource: InsightQueryNode | null | undefined
+): string {
// for formulas, the position (not seriesIndex) identifies the base series: with compare
// enabled, previous-period datasets have offset series indexes, but share the position
// with their current-period counterpart
const formulaPosition = getTrendDatasetPosition(dataset)
const payload = {
- series: Number.isInteger(dataset.action?.order)
- ? dataset.action?.order
- : formulaPosition > 0
- ? `formula${formulaPosition + 1}`
- : 'formula',
+ series:
+ getResultSeriesIndex(querySource, dataset) ??
+ (formulaPosition > 0 ? `formula${formulaPosition + 1}` : 'formula'),
breakdown_value:
dataset.breakdown_value !== undefined && !Array.isArray(dataset.breakdown_value)
? [dataset.breakdown_value]
@@ -658,10 +661,11 @@ export function getFunnelDatasetPosition(
export function getTrendResultCustomizationKey(
resultCustomizationBy: ResultCustomizationBy | null | undefined,
- dataset: IndexedTrendResult
+ dataset: IndexedTrendResult,
+ querySource: InsightQueryNode | null | undefined
): string {
const assignmentByValue = resultCustomizationBy == null || resultCustomizationBy === ResultCustomizationBy.Value
- return assignmentByValue ? getTrendDatasetKey(dataset) : getTrendDatasetPosition(dataset).toString()
+ return assignmentByValue ? getTrendDatasetKey(dataset, querySource) : getTrendDatasetPosition(dataset).toString()
}
export function getTrendResultCustomization(
@@ -671,9 +675,10 @@ export function getTrendResultCustomization(
| Record<string, ResultCustomizationByValue>
| Record<number, ResultCustomizationByPosition>
| null
- | undefined
+ | undefined,
+ querySource: InsightQueryNode | null | undefined
): ResultCustomization | undefined {
- const resultCustomizationKey = getTrendResultCustomizationKey(resultCustomizationBy, dataset)
+ const resultCustomizationKey = getTrendResultCustomizationKey(resultCustomizationBy, dataset, querySource)
return resultCustomizations && Object.keys(resultCustomizations).includes(resultCustomizationKey)
? (resultCustomizations as any)[resultCustomizationKey]
: undefined
@@ -697,9 +702,15 @@ export function getTrendResultCustomizationColorToken(
| null
| undefined,
theme: DataColorTheme,
- dataset: IndexedTrendResult
+ dataset: IndexedTrendResult,
+ querySource: InsightQueryNode | null | undefined
): DataColorToken {
- const resultCustomization = getTrendResultCustomization(resultCustomizationBy, dataset, resultCustomizations)
+ const resultCustomization = getTrendResultCustomization(
+ resultCustomizationBy,
+ dataset,
+ resultCustomizations,
+ querySource
+ )
// for result customizations without a configuration, the color is determined
// by the position in the dataset (shared by current/previous period pairs).
diff --git a/frontend/src/scenes/insights/utils/resultSeries.test.ts b/frontend/src/scenes/insights/utils/resultSeries.test.ts
new file mode 100644
index 000000000000..9896735b4720
--- /dev/null
+++ b/frontend/src/scenes/insights/utils/resultSeries.test.ts
@@ -0,0 +1,94 @@
+import { InsightQueryNode, NodeKind } from '~/queries/schema/schema-general'
+import { BaseMathType, ChartDisplayType, FilterLogicalOperator } from '~/types'
+
+import { ResultSeries, ResultSeriesRow, getResultSeries } from './resultSeries'
+
+describe('getResultSeries()', () => {
+ const pageviews = { kind: NodeKind.EventsNode as const, event: '$pageview', name: '$pageview' }
+ const signups = { kind: NodeKind.ActionsNode as const, id: 7, name: 'Signed up' }
+
+ it.each<{ case: string; query: InsightQueryNode; row: ResultSeriesRow; expected: ResultSeries }>([
+ {
+ case: 'a formula row to no series, although its order is a valid series index',
+ query: {
+ kind: NodeKind.TrendsQuery,
+ series: [pageviews, signups],
+ trendsFilter: { formulaNodes: [{ formula: 'A+B' }, { formula: 'A/B' }] },
+ },
+ row: { order: 1, action: null },
+ expected: { order: 1, node: null, math: null },
+ },
+ {
+ case: 'a calendar heatmap row to series 0, although the query keeps its formulas',
+ query: {
+ kind: NodeKind.TrendsQuery,
+ series: [pageviews, signups],
+ trendsFilter: { display: ChartDisplayType.CalendarHeatmap, formulaNodes: [{ formula: 'A+B' }] },
+ },
+ row: { action: { order: 0, name: '$pageview' } },
+ expected: { order: 0, node: pageviews, math: {} },
+ },
+ {
+ case: 'a stickiness row by the order it carries only on action',
+ query: { kind: NodeKind.StickinessQuery, series: [pageviews, signups] },
+ row: { action: { order: 1, name: 'Signed up' } },
+ expected: { order: 1, node: signups, math: {} },
+ },
+ {
+ case: 'weekly active users on a weekly interval to the daily math the runner applies',
+ query: {
+ kind: NodeKind.TrendsQuery,
+ interval: 'week',
+ series: [{ ...pageviews, math: BaseMathType.WeeklyActiveUsers }],
+ },
+ row: { order: 0 },
+ expected: {
+ order: 0,
+ node: { ...pageviews, math: BaseMathType.WeeklyActiveUsers },
+ math: { math: BaseMathType.UniqueUsers },
+ },
+ },
+ {
+ case: 'an events series saved without a name to its event',
+ query: { kind: NodeKind.TrendsQuery, series: [{ kind: NodeKind.EventsNode, event: '$autocapture' }] },
+ row: { order: 0 },
+ expected: {
+ order: 0,
+ node: { kind: NodeKind.EventsNode, event: '$autocapture', name: '$autocapture' },
+ math: {},
+ },
+ },
+ {
+ case: 'an action series saved without a name to the name the runner resolved',
+ query: { kind: NodeKind.TrendsQuery, series: [{ kind: NodeKind.ActionsNode, id: 7 }] },
+ row: { order: 0, action: { order: 0, name: 'Signed up' } },
+ expected: { order: 0, node: { kind: NodeKind.ActionsNode, id: 7, name: 'Signed up' }, math: {} },
+ },
+ {
+ case: 'a group series saved without a name to its members, as the runner labels it',
+ query: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.GroupNode,
+ operator: FilterLogicalOperator.Or,
+ nodes: [pageviews, { kind: NodeKind.EventsNode, event: '$screen' }],
+ },
+ ],
+ },
+ row: { order: 0 },
+ expected: {
+ order: 0,
+ node: {
+ kind: NodeKind.GroupNode,
+ operator: FilterLogicalOperator.Or,
+ nodes: [pageviews, { kind: NodeKind.EventsNode, event: '$screen' }],
+ name: '$pageview, $screen',
+ },
+ math: {},
+ },
+ },
+ ])('resolves $case', ({ query, row, expected }) => {
+ expect(getResultSeries(query, row)).toEqual(expected)
+ })
+})
diff --git a/frontend/src/scenes/insights/utils/resultSeries.ts b/frontend/src/scenes/insights/utils/resultSeries.ts
new file mode 100644
index 000000000000..b7a45259b44f
--- /dev/null
+++ b/frontend/src/scenes/insights/utils/resultSeries.ts
@@ -0,0 +1,169 @@
+import { ensureStringIsNotBlank } from 'lib/utils/strings'
+import {
+ SeriesNode,
+ isActionsSeriesNode,
+ isEventsSeriesNode,
+ isGroupSeriesNode,
+ isWarehouseSeriesNode,
+} from 'scenes/insights/filters/ActionFilter/seriesNode'
+
+import { InsightQueryNode } from '~/queries/schema/schema-general'
+import { isInsightQueryWithSeries, isLifecycleQuery, isTrendsQuery } from '~/queries/utils'
+import { ActionFilter, BaseMathType, ChartDisplayType, IntervalType } from '~/types'
+
+export type ResultSeriesMath = Pick<SeriesNode, 'math' | 'math_property' | 'math_hogql' | 'math_group_type_index'>
+
+export interface ResultSeries {
+ /** The index of the row's query series, or of its formula on a formula row. */
+ order: number
+ /**
+ * The query series the row reports, carrying the name the row displays under. Null on a formula row, and on a
+ * row whose series the query no longer holds, which happens while results for an edited query load.
+ */
+ node: SeriesNode | null
+ math: ResultSeriesMath | null
+}
+
+export interface ResultSeriesRow {
+ order?: number | null
+ action?: Pick<ActionFilter, 'order' | 'name'> | null
+}
+
+const WEEK_OR_LONGER_INTERVALS = new Set<IntervalType>(['week', 'month', 'quarter', 'year'])
+const MONTH_OR_LONGER_INTERVALS = new Set<IntervalType>(['month', 'quarter', 'year'])
+
+/**
+ * The row's series or formula index. Stickiness, lifecycle and calendar heatmap rows carry it only on the legacy
+ * `action`, so this reads `action.order` for them until those runners emit `order` at the top level.
+ */
+export function getResultOrder(result: ResultSeriesRow): number {
+ return result.order ?? result.action?.order ?? 0
+}
+
+/**
+ * Whether the query returns formula rows in place of series rows. This mirrors the trends runner, which reads
+ * `formulaNodes`, then `formulas`, then `formula`, and ignores an empty list or string. The calendar heatmap runner
+ * ignores formulas and reports series 0, so its query keeps its formulas without returning formula rows.
+ */
+export function hasFormulaResults(querySource: InsightQueryNode | null | undefined): boolean {
+ if (
+ !isTrendsQuery(querySource) ||
+ !querySource.trendsFilter ||
+ querySource.trendsFilter.display === ChartDisplayType.CalendarHeatmap
+ ) {
+ return false
+ }
+ const { formulaNodes, formulas, formula } = querySource.trendsFilter
+ return !!formulaNodes?.length || !!formulas?.length || !!formula
+}
+
+/** The query series index of a series row. Undefined on a formula row, because its `order` indexes the formulas. */
+export function getResultSeriesIndex(
+ querySource: InsightQueryNode | null | undefined,
+ result: ResultSeriesRow
+): number | undefined {
+ return hasFormulaResults(querySource) ? undefined : getResultOrder(result)
+}
+
+export function getResultSeries(
+ querySource: InsightQueryNode | null | undefined,
+ result: ResultSeriesRow
+): ResultSeries {
+ const order = getResultOrder(result)
+ const node =
+ querySource && !hasFormulaResults(querySource) && isInsightQueryWithSeries(querySource)
+ ? (querySource.series[order] as SeriesNode | undefined)
+ : undefined
+ if (!node) {
+ return { order, node: null, math: null }
+ }
+ return { order, node: withDisplayName(node, result), math: getRunnerMath(querySource, node) }
+}
+
+/**
+ * The key the runner labels a series with: its event, its table, or a group's member keys joined by commas. Null for
+ * an all-events series, an action, and a group that holds an action saved without a name.
+ */
+function getSeriesKey(node: SeriesNode): string | null {
+ if (isEventsSeriesNode(node)) {
+ return node.event ?? null
+ }
+ if (isWarehouseSeriesNode(node)) {
+ return node.table_name
+ }
+ if (!isGroupSeriesNode(node)) {
+ return null
+ }
+ const memberKeys = node.nodes.map((member) =>
+ isEventsSeriesNode(member)
+ ? (member.event ?? 'All events')
+ : isActionsSeriesNode(member)
+ ? ensureStringIsNotBlank(member.name)
+ : getSeriesKey(member)
+ )
+ return memberKeys.every((key) => key !== null) ? memberKeys.join(', ') : null
+}
+
+/**
+ * The series' rename, by the rule the runner applies to `custom_name`: the custom name, or a `name` other than the
+ * key the series queries. An action's key is its database name, which the query does not hold, so only its
+ * `custom_name` counts.
+ */
+export function getResultSeriesCustomName(node: SeriesNode): string | null {
+ const customName = ensureStringIsNotBlank(node.custom_name)
+ if (customName) {
+ return customName
+ }
+ const name = ensureStringIsNotBlank(node.name)
+ return name && !isActionsSeriesNode(node) && name !== getSeriesKey(node) ? name : null
+}
+
+/**
+ * A series saved without a `name` displays the raw key it queries, as the runner's label does. A nameless action
+ * has no key worth showing, so it takes the name the runner resolved from the database while responses still
+ * carry `action`. So does a group that holds a nameless action.
+ */
+function withDisplayName(node: SeriesNode, result: ResultSeriesRow): SeriesNode {
+ if (ensureStringIsNotBlank(node.name)) {
+ return node
+ }
+ const runnerName = ensureStringIsNotBlank(result.action?.name)
+ const name = isEventsSeriesNode(node)
+ ? node.event
+ : isGroupSeriesNode(node)
+ ? (getSeriesKey(node) ?? runnerName)
+ : isActionsSeriesNode(node)
+ ? runnerName
+ : null
+ return name ? { ...node, name } : node
+}
+
+function getRunnerMath(querySource: InsightQueryNode | null | undefined, node: SeriesNode): ResultSeriesMath {
+ if (isLifecycleQuery(querySource)) {
+ return { math: BaseMathType.TotalCount }
+ }
+ if (!isTrendsQuery(querySource)) {
+ // The stickiness runner applies the series math but does not report it, so its labels never show a math tag.
+ return {}
+ }
+ return {
+ math: getTrendsRunnerMath(node.math, querySource.interval ?? 'day'),
+ math_property: node.math_property,
+ math_hogql: node.math_hogql,
+ math_group_type_index: node.math_group_type_index,
+ }
+}
+
+/**
+ * The trends runner counts weekly or monthly active users as daily active users when one interval bucket already
+ * spans the trailing window, so the series math is the daily one for those intervals.
+ */
+function getTrendsRunnerMath(math: ResultSeriesMath['math'], interval: IntervalType): ResultSeriesMath['math'] {
+ if (
+ (math === BaseMathType.WeeklyActiveUsers && WEEK_OR_LONGER_INTERVALS.has(interval)) ||
+ (math === BaseMathType.MonthlyActiveUsers && MONTH_OR_LONGER_INTERVALS.has(interval))
+ ) {
+ return BaseMathType.UniqueUsers
+ }
+ return math
+}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 719db7573d65..8d1edb1044c1 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5482,6 +5482,7 @@ export type GraphDataset = Partial<
| 'status'
| 'action'
| 'actions'
+ | 'order'
| 'breakdown_value'
| 'persons_urls'
| 'persons'
diff --git a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx
index 484ac1c37588..4565756c4008 100644
--- a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx
@@ -121,7 +121,13 @@ describe('useInsightsLegendConfig', () => {
const groupOf = result.current.visibilityGroupKey!
expect(groupOf(String(current.id))).toBe(groupOf(String(previous.id)))
- expect(groupOf(String(current.id))).toBe(getTrendResultCustomizationKey(ResultCustomizationBy.Value, current))
+ expect(groupOf(String(current.id))).toBe(
+ getTrendResultCustomizationKey(
+ ResultCustomizationBy.Value,
+ current,
+ trendsDataLogic(insightProps).values.querySource
+ )
+ )
})
it.each([
diff --git a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
index 9a306f76525f..2d40b0f219d4 100644
--- a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
+++ b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
@@ -25,9 +25,8 @@ export function useInsightsLegendConfig({
inSharedMode = false,
}: UseInsightsLegendConfigOptions): ChartLegendConfig {
const { canEditInsight } = useValues(insightLogic)
- const { indexedResults, getTrendsHidden, showLegend, legendPosition, resultCustomizationBy } = useValues(
- trendsDataLogic(insightProps)
- )
+ const { indexedResults, getTrendsHidden, showLegend, legendPosition, resultCustomizationBy, querySource } =
+ useValues(trendsDataLogic(insightProps))
const { toggleResultHidden, setResultsHidden } = useActions(trendsDataLogic(insightProps))
const resultById = useMemo(() => {
@@ -60,7 +59,7 @@ export function useInsightsLegendConfig({
// isolates, or the twin row it deliberately leaves visible would read as "not isolated".
visibilityGroupKey: (key: string) => {
const result = resultById.get(key)
- return result ? getTrendResultCustomizationKey(resultCustomizationBy, result) : key
+ return result ? getTrendResultCustomizationKey(resultCustomizationBy, result, querySource) : key
},
renderItem: legendInteractive ? renderItem : undefined,
}
@@ -74,6 +73,7 @@ export function useInsightsLegendConfig({
toggleResultHidden,
setResultsHidden,
resultCustomizationBy,
+ querySource,
renderItem,
])
}
diff --git a/products/product_analytics/frontend/insights/trends/trendsDataLogic.test.ts b/products/product_analytics/frontend/insights/trends/trendsDataLogic.test.ts
index 4751452b12ab..63222addbea4 100644
--- a/products/product_analytics/frontend/insights/trends/trendsDataLogic.test.ts
+++ b/products/product_analytics/frontend/insights/trends/trendsDataLogic.test.ts
@@ -393,8 +393,8 @@ describe('trendsDataLogic', () => {
const indexedResults = logic.values.indexedResults
const [currentRow, previousRow] = indexedResults
- expect(getTrendResultCustomizationKey(ResultCustomizationBy.Value, currentRow)).toBe(
- getTrendResultCustomizationKey(ResultCustomizationBy.Value, previousRow)
+ expect(getTrendResultCustomizationKey(ResultCustomizationBy.Value, currentRow, query)).toBe(
+ getTrendResultCustomizationKey(ResultCustomizationBy.Value, previousRow, query)
)
await expectLogic(logic, () => {
@@ -457,7 +457,7 @@ describe('trendsDataLogic', () => {
const indexedResults = logic.values.indexedResults
const { resultCustomizationBy } = logic.values
- const key0 = getTrendResultCustomizationKey(resultCustomizationBy, indexedResults[0])
+ const key0 = getTrendResultCustomizationKey(resultCustomizationBy, indexedResults[0], query)
await expectLogic(logic, () => {
insightVizDataLogic.findMounted(insightProps)?.actions.updateInsightFilter({
diff --git a/products/product_analytics/frontend/insights/trends/trendsDataLogic.ts b/products/product_analytics/frontend/insights/trends/trendsDataLogic.ts
index 6e396fc4bea9..9b180ac794df 100644
--- a/products/product_analytics/frontend/insights/trends/trendsDataLogic.ts
+++ b/products/product_analytics/frontend/insights/trends/trendsDataLogic.ts
@@ -27,6 +27,7 @@ import {
getTrendResultCustomizationColorToken,
getTrendResultCustomizationKey,
} from 'scenes/insights/utils'
+import { getResultSeriesIndex } from 'scenes/insights/utils/resultSeries'
import { isSharedView } from '~/exporter/exporterViewLogic'
import {
@@ -312,7 +313,18 @@ export interface trendsDataLogicMeta {
indexedResults: (
results: TrendResult[],
display: ChartDisplayType | null | undefined,
- lifecycleFilter: LifecycleFilter | null | undefined
+ lifecycleFilter: LifecycleFilter | null | undefined,
+ querySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null
) => IndexedTrendResult[]
currentPeriodResult: (indexedResults: IndexedTrendResult[]) => IndexedTrendResult | undefined
labelGroupType: (
@@ -413,7 +425,18 @@ export interface trendsDataLogicMeta {
resultCustomizations:
| Record<string, ResultCustomizationByValue>
| Record<number, ResultCustomizationByPosition>
- | undefined
+ | undefined,
+ querySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null
) => (dataset: IndexedTrendResult) => boolean
areAllSeriesVisible: (
indexedResults: IndexedTrendResult[],
@@ -423,7 +446,18 @@ export interface trendsDataLogicMeta {
getIsOnlyVisibleSeriesInLegend: (
indexedResults: IndexedTrendResult[],
resultCustomizationBy: ResultCustomizationBy,
- getTrendsHidden: (dataset: IndexedTrendResult) => boolean
+ getTrendsHidden: (dataset: IndexedTrendResult) => boolean,
+ querySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null
) => (dataset: IndexedTrendResult) => boolean
}
}
@@ -587,11 +621,12 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
],
indexedResults: [
- (s) => [s.results, s.display, s.lifecycleFilter],
+ (s) => [s.results, s.display, s.lifecycleFilter, s.querySource],
(
results: TrendResult[],
display: ChartDisplayType | null | undefined,
- lifecycleFilter: null | import('~/queries/schema/schema-general').LifecycleFilter | undefined
+ lifecycleFilter: null | import('~/queries/schema/schema-general').LifecycleFilter | undefined,
+ querySource: InsightQueryNode | null
): IndexedTrendResult[] => {
const defaultLifecyclesOrder = ['new', 'resurrecting', 'returning', 'dormant']
let indexedResults = results.map((result, index) => ({ ...result, seriesIndex: index }))
@@ -648,19 +683,24 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
)
}
+ const colorIndexKey = (item: TrendResult): string =>
+ `${item.label}_${getResultSeriesIndex(querySource, item)}_${item?.breakdown_value}`
const colorIndexMap = new Map<string, number>()
indexedResults
.slice()
- .sort((a, b) => (a.action?.order ?? 0) - (b.action?.order ?? 0))
+ .sort(
+ (a, b) =>
+ (getResultSeriesIndex(querySource, a) ?? 0) - (getResultSeriesIndex(querySource, b) ?? 0)
+ )
.forEach((item) => {
- const key = `${item.label}_${item.action?.order}_${item?.breakdown_value}`
+ const key = colorIndexKey(item)
if (!colorIndexMap.has(key)) {
colorIndexMap.set(key, colorIndexMap.size)
}
})
return indexedResults.map((item, index) => {
- const key = `${item.label}_${item.action?.order}_${item?.breakdown_value}`
+ const key = colorIndexKey(item)
const colorIndex = colorIndexMap.get(key) ?? 0
return { ...item, colorIndex, id: index }
})
@@ -920,7 +960,7 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
const overrideToken =
findBreakdownColorConfig(
overrides,
- JSON.parse(getTrendDatasetKey(result))['breakdown_value'],
+ JSON.parse(getTrendDatasetKey(result, querySource))['breakdown_value'],
breakdownFilter?.breakdown_type,
breakdownPropertyKey
)?.colorToken ?? null
@@ -929,8 +969,12 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
position: getTrendDatasetPosition(result),
overrideToken:
overrideToken ??
- getTrendResultCustomization(resultCustomizationBy, result, resultCustomizations)
- ?.color ??
+ getTrendResultCustomization(
+ resultCustomizationBy,
+ result,
+ resultCustomizations,
+ querySource
+ )?.color ??
null,
}
})
@@ -942,7 +986,7 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
}
return (dataset: IndexedTrendResult): [DataColorTheme | null, DataColorToken | null] => {
- const breakdownValue = JSON.parse(getTrendDatasetKey(dataset))['breakdown_value']
+ const breakdownValue = JSON.parse(getTrendDatasetKey(dataset, querySource))['breakdown_value']
// dashboard color overrides
const logic = dashboardLogic.findMounted({ id: props.dashboardId })
@@ -973,7 +1017,8 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
const customizationColor = getTrendResultCustomization(
resultCustomizationBy,
dataset,
- resultCustomizations
+ resultCustomizations,
+ querySource
)?.color
const fallbackToken = customizationColor
? undefined
@@ -989,7 +1034,8 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
resultCustomizationBy,
resultCustomizations,
theme,
- dataset
+ dataset,
+ querySource
),
]
}
@@ -1005,19 +1051,21 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
},
],
getTrendsHidden: [
- (s) => [s.resultCustomizationBy, s.resultCustomizations],
+ (s) => [s.resultCustomizationBy, s.resultCustomizations, s.querySource],
(
resultCustomizationBy: ResultCustomizationBy,
resultCustomizations:
| Record<string, import('~/queries/schema/schema-general').ResultCustomizationByValue>
| Record<number, import('~/queries/schema/schema-general').ResultCustomizationByPosition>
- | undefined
+ | undefined,
+ querySource: InsightQueryNode | null
) => {
return (dataset: IndexedTrendResult): boolean => {
const resultCustomization = getTrendResultCustomization(
resultCustomizationBy,
dataset,
- resultCustomizations
+ resultCustomizations,
+ querySource
)
return resultCustomization?.hidden || false
}
@@ -1038,11 +1086,12 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
],
getIsOnlyVisibleSeriesInLegend: [
- (s) => [s.indexedResults, s.resultCustomizationBy, s.getTrendsHidden],
+ (s) => [s.indexedResults, s.resultCustomizationBy, s.getTrendsHidden, s.querySource],
(
indexedResults: IndexedTrendResult[],
resultCustomizationBy: ResultCustomizationBy,
- getTrendsHidden: (dataset: IndexedTrendResult) => boolean
+ getTrendsHidden: (dataset: IndexedTrendResult) => boolean,
+ querySource: InsightQueryNode | null
) => {
if (indexedResults.length < 2) {
return (): boolean => false
@@ -1051,25 +1100,30 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
const visibleKeys = new Set(
indexedResults
.filter((r) => !getTrendsHidden(r))
- .map((r) => getTrendResultCustomizationKey(resultCustomizationBy, r))
+ .map((r) => getTrendResultCustomizationKey(resultCustomizationBy, r, querySource))
)
const soloKey = visibleKeys.size === 1 ? [...visibleKeys][0] : null
return (dataset: IndexedTrendResult): boolean =>
soloKey !== null &&
!getTrendsHidden(dataset) &&
- getTrendResultCustomizationKey(resultCustomizationBy, dataset) === soloKey
+ getTrendResultCustomizationKey(resultCustomizationBy, dataset, querySource) === soloKey
},
],
})),
listeners(({ actions, values }) => ({
toggleResultHidden: ({ dataset }) => {
- const resultCustomizationKey = getTrendResultCustomizationKey(values.resultCustomizationBy, dataset)
+ const resultCustomizationKey = getTrendResultCustomizationKey(
+ values.resultCustomizationBy,
+ dataset,
+ values.querySource
+ )
const resultCustomization = getTrendResultCustomization(
values.resultCustomizationBy,
dataset,
- values.resultCustomizations
+ values.resultCustomizations,
+ values.querySource
)
actions.updateInsightFilter({
resultCustomizations: {
@@ -1085,11 +1139,16 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
toggleAllResultsHidden: ({ datasets, hidden }) => {
const resultCustomizations: Record<string, ResultCustomization> = { ...values.resultCustomizations }
for (const dataset of datasets) {
- const resultCustomizationKey = getTrendResultCustomizationKey(values.resultCustomizationBy, dataset)
+ const resultCustomizationKey = getTrendResultCustomizationKey(
+ values.resultCustomizationBy,
+ dataset,
+ values.querySource
+ )
const existing = getTrendResultCustomization(
values.resultCustomizationBy,
dataset,
- values.resultCustomizations
+ values.resultCustomizations,
+ values.querySource
)
resultCustomizations[resultCustomizationKey] = {
...existing,
@@ -1103,7 +1162,7 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
} as Partial<TrendsFilter>)
},
setResultsHidden: ({ hiddenIds }) => {
- const { indexedResults, resultCustomizationBy, resultCustomizations } = values
+ const { indexedResults, resultCustomizationBy, resultCustomizations, querySource } = values
const hidden = new Set(hiddenIds)
// Customizations are keyed per series identity, which several results can share when
// assigning by value. Resolve visibility per key — a key stays visible while any of its
@@ -1111,13 +1170,18 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
const visibleKeys = new Set(
indexedResults
.filter((r) => !hidden.has(String(r.id)))
- .map((r) => getTrendResultCustomizationKey(resultCustomizationBy, r))
+ .map((r) => getTrendResultCustomizationKey(resultCustomizationBy, r, querySource))
)
const next: Record<string, ResultCustomization> = { ...resultCustomizations }
for (const result of indexedResults) {
- const key = getTrendResultCustomizationKey(resultCustomizationBy, result)
- const existing = getTrendResultCustomization(resultCustomizationBy, result, resultCustomizations)
+ const key = getTrendResultCustomizationKey(resultCustomizationBy, result, querySource)
+ const existing = getTrendResultCustomization(
+ resultCustomizationBy,
+ result,
+ resultCustomizations,
+ querySource
+ )
next[key] = {
...existing,
assignmentBy: resultCustomizationBy,
@@ -1128,14 +1192,14 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
actions.updateInsightFilter({ resultCustomizations: next } as Partial<TrendsFilter>)
},
toggleOtherSeriesHidden: ({ dataset }) => {
- const { indexedResults, resultCustomizationBy, resultCustomizations, getTrendsHidden } = values
+ const { indexedResults, resultCustomizationBy, resultCustomizations, getTrendsHidden, querySource } = values
if (indexedResults.length < 2) {
return
}
- const clickedKey = getTrendResultCustomizationKey(resultCustomizationBy, dataset)
+ const clickedKey = getTrendResultCustomizationKey(resultCustomizationBy, dataset, querySource)
const others = indexedResults.filter(
- (d) => getTrendResultCustomizationKey(resultCustomizationBy, d) !== clickedKey
+ (d) => getTrendResultCustomizationKey(resultCustomizationBy, d, querySource) !== clickedKey
)
const isSoloMode = others.length > 0 && !getTrendsHidden(dataset) && others.every((d) => getTrendsHidden(d))
@@ -1143,8 +1207,13 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
if (isSoloMode) {
for (const r of indexedResults) {
- const key = getTrendResultCustomizationKey(resultCustomizationBy, r)
- const existing = getTrendResultCustomization(resultCustomizationBy, r, resultCustomizations)
+ const key = getTrendResultCustomizationKey(resultCustomizationBy, r, querySource)
+ const existing = getTrendResultCustomization(
+ resultCustomizationBy,
+ r,
+ resultCustomizations,
+ querySource
+ )
next[key] = {
...existing,
assignmentBy: values.resultCustomizationBy,
@@ -1153,8 +1222,13 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
}
} else {
for (const r of indexedResults) {
- const key = getTrendResultCustomizationKey(resultCustomizationBy, r)
- const existing = getTrendResultCustomization(resultCustomizationBy, r, resultCustomizations)
+ const key = getTrendResultCustomizationKey(resultCustomizationBy, r, querySource)
+ const existing = getTrendResultCustomization(
+ resultCustomizationBy,
+ r,
+ resultCustomizations,
+ querySource
+ )
const isClicked = key === clickedKey
next[key] = {
...existing,