: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
feat(insights): keep an isolated legend series in the saved insight (#82668)
Sam Penningtonba4721aa58f2
diff --git a/frontend/src/scenes/trends/trendsDataLogic.test.ts b/frontend/src/scenes/trends/trendsDataLogic.test.tsindex 5ad227dcd81c..586bbbe7bc72 100644--- a/frontend/src/scenes/trends/trendsDataLogic.test.ts+++ b/frontend/src/scenes/trends/trendsDataLogic.test.ts@@ -313,6 +313,73 @@ describe('trendsDataLogic', () => {})})+ it('setResultsHidden hides exactly the given series in one update', async () => {+ const query: TrendsQuery = {+ kind: NodeKind.TrendsQuery,+ series: [],+ trendsFilter: { display: ChartDisplayType.ActionsPie },+ }+ const insight: Partial<InsightModel> = { result: trendPieResult.result }++ await expectLogic(logic, () => {+ insightVizDataLogic.findMounted(insightProps)?.actions.updateQuerySource(query)+ builtDataNodeLogic.actions.loadDataSuccess(insight)+ }).toFinishAllListeners()++ const indexedResults = logic.values.indexedResults+ const isolated = indexedResults[0]+ const others = indexedResults.slice(1)++ await expectLogic(logic, () => {+ logic.actions.setResultsHidden(others.map((r) => String(r.id)))+ }).toFinishAllListeners()++ const { getTrendsHidden, getIsOnlyVisibleSeriesInLegend } = logic.values+ expect(getTrendsHidden(isolated)).toBe(false)+ expect(others.map((r) => getTrendsHidden(r))).toEqual(others.map(() => true))+ expect(getIsOnlyVisibleSeriesInLegend(isolated)).toBe(true)++ await expectLogic(logic, () => {+ logic.actions.setResultsHidden([])+ }).toFinishAllListeners()++ await expectLogic(logic).toMatchValues({ areAllSeriesVisible: true })+ })++ it('setResultsHidden keeps a shared customization key visible while any of its results is', async () => {+ // Comparing to the previous period puts a series' current and previous results on one+ // customization key, so hiding one row cannot hide the other out from under it.+ const query: TrendsQuery = {+ kind: NodeKind.TrendsQuery,+ series: [],+ compareFilter: { compare: true },+ }+ const [current] = trendResult.result+ const insight: Partial<InsightModel> = {+ result: [+ { ...current, compare: true, compare_label: 'current' },+ { ...current, compare: true, compare_label: 'previous' },+ ],+ }++ await expectLogic(logic, () => {+ insightVizDataLogic.findMounted(insightProps)?.actions.updateQuerySource(query)+ builtDataNodeLogic.actions.loadDataSuccess(insight)+ }).toFinishAllListeners()++ const [currentRow, previousRow] = logic.values.indexedResults+ expect(getTrendResultCustomizationKey(ResultCustomizationBy.Value, currentRow)).toBe(+ getTrendResultCustomizationKey(ResultCustomizationBy.Value, previousRow)+ )++ await expectLogic(logic, () => {+ logic.actions.setResultsHidden([String(previousRow.id)])+ }).toFinishAllListeners()++ const { getTrendsHidden } = logic.values+ expect([getTrendsHidden(currentRow), getTrendsHidden(previousRow)]).toEqual([false, false])+ })+it('getIsOnlyVisibleSeriesInLegend is true only for the sole visible series', async () => {const query: TrendsQuery = {kind: NodeKind.TrendsQuery,diff --git a/frontend/src/scenes/trends/trendsDataLogic.ts b/frontend/src/scenes/trends/trendsDataLogic.tsindex fc6aa0e2090a..361deefa8a48 100644--- a/frontend/src/scenes/trends/trendsDataLogic.ts+++ b/frontend/src/scenes/trends/trendsDataLogic.ts@@ -254,6 +254,9 @@ export interface trendsDataLogicActions {setHoveredDatasetIndex: (index: number | null) => {index: number | null}+ setResultsHidden: (hiddenIds: string[]) => {+ hiddenIds: string[]+ }toggleAllResultsHidden: (datasets: IndexedTrendResult[],hidden: boolean@@ -497,6 +500,7 @@ export const trendsDataLogic = kea<trendsDataLogicType>([toggleResultHidden: (dataset: IndexedTrendResult) => ({ dataset }),toggleAllResultsHidden: (datasets: IndexedTrendResult[], hidden: boolean) => ({ datasets, hidden }),toggleOtherSeriesHidden: (dataset: IndexedTrendResult) => ({ dataset }),+ setResultsHidden: (hiddenIds: string[]) => ({ hiddenIds }),setHoveredDatasetIndex: (index: number | null) => ({ index }),}),@@ -1105,6 +1109,31 @@ export const trendsDataLogic = kea<trendsDataLogicType>([resultCustomizations,} as Partial<TrendsFilter>)},+ setResultsHidden: ({ hiddenIds }) => {+ const { indexedResults, resultCustomizationBy, resultCustomizations } = 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+ // results is — so isolating one of a pair doesn't hide the other out from under it.+ const visibleKeys = new Set(+ indexedResults+ .filter((r) => !hidden.has(String(r.id)))+ .map((r) => getTrendResultCustomizationKey(resultCustomizationBy, r))+ )++ const next: Record<string, ResultCustomization> = { ...resultCustomizations }+ for (const result of indexedResults) {+ const key = getTrendResultCustomizationKey(resultCustomizationBy, result)+ const existing = getTrendResultCustomization(resultCustomizationBy, result, resultCustomizations)+ next[key] = {+ ...existing,+ assignmentBy: resultCustomizationBy,+ hidden: !visibleKeys.has(key),+ }+ }++ actions.updateInsightFilter({ resultCustomizations: next } as Partial<TrendsFilter>)+ },toggleOtherSeriesHidden: ({ dataset }) => {const { indexedResults, resultCustomizationBy, resultCustomizations, getTrendsHidden } = valuesif (indexedResults.length < 2) {diff --git a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsxindex 61b24dc72fd8..db726a2497a6 100644--- a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx@@ -1,16 +1,24 @@-import { renderHook } from '@testing-library/react'+import { renderHook, waitFor } from '@testing-library/react'import { BindLogic } from 'kea'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'+import { getTrendResultCustomizationKey } from 'scenes/insights/utils'import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'-import { DataNode, NodeKind, TrendsFilter, TrendsQuery } from '~/queries/schema/schema-general'+import {+ CompareFilter,+ DataNode,+ NodeKind,+ ResultCustomizationBy,+ TrendsFilter,+ TrendsQuery,+} from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { InsightLogicProps } from '~/types'+import { InsightLogicProps, InsightModel } from '~/types'import { useInsightsLegendConfig } from './useInsightsLegendConfig'@@ -22,19 +30,44 @@ const wrapper = ({ children }: { children: React.ReactNode }): JSX.Element => (</BindLogic>)-function setup({ trendsFilter }: { trendsFilter?: TrendsFilter } = {}): void {+function setup({+ trendsFilter,+ compareFilter,+ results,+}: {+ trendsFilter?: TrendsFilter+ compareFilter?: CompareFilter+ results?: InsightModel['result']+} = {}): void {initKeaTests()featureFlagLogic.mount()- dataNodeLogic({ key: 'InsightViz.new', query: {} as DataNode }).mount()+ const builtDataNodeLogic = dataNodeLogic({ key: 'InsightViz.new', query: {} as DataNode })+ builtDataNodeLogic.mount()insightDataLogic(insightProps).mount()insightLogic(insightProps).mount()insightVizDataLogic(insightProps).mount()trendsDataLogic(insightProps).mount()- const query: TrendsQuery = { kind: NodeKind.TrendsQuery, series: [], trendsFilter }+ const query: TrendsQuery = { kind: NodeKind.TrendsQuery, series: [], trendsFilter, compareFilter }insightVizDataLogic(insightProps).actions.updateQuerySource(query)+ builtDataNodeLogic.actions.loadDataSuccess({ result: results ?? [] })}+const SERIES: InsightModel['result'] = [+ {+ action: { id: '$pageview', type: 'events', order: 0, name: '$pageview' },+ label: '$pageview',+ data: [1],+ days: [],+ },+ {+ action: { id: '$autocapture', type: 'events', order: 1, name: '$autocapture' },+ label: '$autocapture',+ data: [2],+ days: [],+ },+]+describe('useInsightsLegendConfig', () => {it.each([{ legendPosition: 'left', expected: 'left' },@@ -59,6 +92,39 @@ describe('useInsightsLegendConfig', () => {expect(result.current?.show).toBe(expectedShow)})+ it('persists an isolate through onSetHiddenSeries, so a legend click reaches the query', async () => {+ setup({ trendsFilter: { showLegend: true }, results: SERIES })+ const { result } = renderHook(() => useInsightsLegendConfig({ insightProps }), { wrapper })+ const logic = trendsDataLogic(insightProps)+ const [first, second] = logic.values.indexedResults++ result.current.onSetHiddenSeries!([String(second.id)])++ await waitFor(() => {+ const { getTrendsHidden } = logic.values+ expect([getTrendsHidden(first), getTrendsHidden(second)]).toEqual([false, true])+ })+ })++ it('groups a compared series two rows onto one visibility key', () => {+ const [pageview] = SERIES+ setup({+ trendsFilter: { showLegend: true },+ compareFilter: { compare: true },+ results: [+ { ...pageview, compare: true, compare_label: 'current' },+ { ...pageview, compare: true, compare_label: 'previous' },+ ],+ })+ const { result } = renderHook(() => useInsightsLegendConfig({ insightProps }), { wrapper })+ const [current, previous] = trendsDataLogic(insightProps).values.indexedResults++ 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))+ })+it.each([{ inSharedMode: false, expectedInteractive: true },{ inSharedMode: true, expectedInteractive: false },diff --git a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsxindex 35db0c95ab69..d8c8a33a3183 100644--- a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx@@ -4,6 +4,7 @@ import { useMemo, type ReactNode } from 'react'import type { ChartLegendConfig, LegendItem } from '@posthog/quill-charts'import { insightLogic } from 'scenes/insights/insightLogic'+import { getTrendResultCustomizationKey } from 'scenes/insights/utils'import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'import type { IndexedTrendResult } from 'scenes/trends/types'@@ -24,9 +25,15 @@ export function useInsightsLegendConfig({inSharedMode = false,}: UseInsightsLegendConfigOptions): ChartLegendConfig {const { canEditInsight } = useValues(insightLogic)- const { indexedResults, getTrendsHidden, showLegend, legendPosition, legendSeriesIsolationMenuEligible } =- useValues(trendsDataLogic(insightProps))- const { toggleResultHidden } = useActions(trendsDataLogic(insightProps))+ const {+ indexedResults,+ getTrendsHidden,+ showLegend,+ legendPosition,+ legendSeriesIsolationMenuEligible,+ resultCustomizationBy,+ } = useValues(trendsDataLogic(insightProps))+ const { toggleResultHidden, setResultsHidden } = useActions(trendsDataLogic(insightProps))const resultById = useMemo(() => {const m = new Map<string, IndexedTrendResult>()@@ -50,6 +57,16 @@ export function useInsightsLegendConfig({toggleResultHidden(result)}},+ // Isolating rewrites the whole hidden set, so it lands as one resultCustomizations+ // update rather than a toggle per series.+ onSetHiddenSeries: setResultsHidden,+ // Hidden state is stored per customization key, and comparing to the previous period puts+ // a series' two rows on one key — so quill has to treat them as one series when it+ // 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+ },renderItem: showContextMenu? (node: ReactNode, item: LegendItem) => {const result = resultById.get(item.key)@@ -73,6 +90,8 @@ export function useInsightsLegendConfig({legendSeriesIsolationMenuEligible,resultById,toggleResultHidden,+ setResultsHidden,+ resultCustomizationBy,insightProps,])}