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.

fix(funnels): keep compare filter when sorting detailed results (#72534)

Xander19cd50e11ec0
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx
new file mode 100644
index 000000000000..18e70f09f34e
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx
@@ -0,0 +1,55 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { router } from 'kea-router'
+
+import { initKeaTests } from '~/test/init'
+
+import { LemonTable } from './LemonTable'
+
+interface Row {
+ id: number
+ name: string
+ value: number
+}
+
+const DATA: Row[] = [
+ { id: 1, name: 'alpha', value: 3 },
+ { id: 2, name: 'beta', value: 1 },
+ { id: 3, name: 'gamma', value: 2 },
+]
+
+const COLUMNS = [
+ {
+ title: 'Value',
+ key: 'value',
+ render: (_: any, row: Row) => <span data-attr="cell-name">{row.name}</span>,
+ sorter: (a: Row, b: Row) => a.value - b.value,
+ },
+]
+
+describe('LemonTable', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(cleanup)
+
+ const renderedOrder = (): string[] => screen.getAllByTestId('cell-name').map((el) => el.textContent ?? '')
+
+ it.each([
+ [true, ['alpha', 'gamma', 'beta']],
+ [false, ['alpha', 'beta', 'gamma']],
+ ])('useURLForSorting=%s reads the order search param only when enabled', (useURLForSorting, expectedOrder) => {
+ router.actions.push(router.values.location.pathname, { order: '-value' })
+ render(
+ <LemonTable
+ rowKey="id"
+ dataSource={DATA}
+ columns={COLUMNS}
+ useURLForSorting={useURLForSorting as boolean}
+ />
+ )
+ expect(renderedOrder()).toEqual(expectedOrder)
+ })
+})
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
index 5fc586031d70..a4c18e3a189f 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
@@ -210,11 +210,12 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
columns: baseColumns,
})
- /** Sorting. */
+ /** Sorting. `useURLForSorting` gates both writing and reading the URL — when off, a stale
+ * `order` param must not resurrect a sort the consumer isn't controlling. */
const currentSorting =
sorting ||
internalSorting ||
- (searchParams[currentSortingParam]
+ (useURLForSorting && searchParams[currentSortingParam]
? searchParams[currentSortingParam].startsWith('-')
? {
columnKey: searchParams[currentSortingParam].substr(1),
diff --git a/frontend/src/scenes/funnels/funnelDataLogic.test.ts b/frontend/src/scenes/funnels/funnelDataLogic.test.ts
index ac51ec0affa4..3aac8d443264 100644
--- a/frontend/src/scenes/funnels/funnelDataLogic.test.ts
+++ b/frontend/src/scenes/funnels/funnelDataLogic.test.ts
@@ -1,3 +1,4 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import timekeeper from 'timekeeper'
@@ -806,6 +807,26 @@ describe('funnelDataLogic', () => {
expect(order).toEqual(expectedOrder)
})
+ it('setBreakdownSorting updates the query without clobbering compareFilter or the URL', async () => {
+ const query: FunnelsQuery = {
+ kind: NodeKind.FunnelsQuery,
+ series: [],
+ funnelsFilter: { funnelVizType: FunnelVizType.Steps },
+ compareFilter: { compare: true },
+ }
+
+ await expectLogic(logic, () => {
+ logic.actions.updateQuerySource(query)
+ logic.actions.setBreakdownSorting('-total_conversion')
+ }).toFinishAllListeners()
+
+ expect(logic.values.querySource).toMatchObject({
+ funnelsFilter: { funnelVizType: FunnelVizType.Steps, breakdownSorting: '-total_conversion' },
+ compareFilter: { compare: true },
+ })
+ expect(router.values.searchParams.order).toBeUndefined()
+ })
+
it('visibleStepsWithConversionMetrics matches flattenedBreakdowns order', async () => {
const query: FunnelsQuery = {
kind: NodeKind.FunnelsQuery,
diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.ts
index 2c417847d453..c74a788a0be3 100644
--- a/frontend/src/scenes/funnels/funnelDataLogic.ts
+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts
@@ -1,5 +1,4 @@
-import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
-import { router } from 'kea-router'
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { DataColorTheme, DataColorToken } from 'lib/colors'
import { BIN_COUNT_AUTO } from 'lib/constants'
@@ -208,7 +207,6 @@ export interface funnelDataLogicValues {
| WebStatsTableQuery
| null // insightVizDataLogic
vizSeries: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined // insightVizDataLogic
- searchParams: Record<string, any> // router
advancedOptionsUsedCount: number
aggregationTargetLabel: Noun
breakdownSorting: string | undefined
@@ -289,15 +287,6 @@ export interface funnelDataLogicActions {
updateQuerySource: (querySource: QuerySourceUpdate) => {
querySource: QuerySourceUpdate
} // insightVizDataLogic
- push: (
- url: string,
- searchInput?: string | Record<string, any>,
- hashInput?: string | Record<string, any>
- ) => {
- hashInput: string | Record<string, any>
- searchInput: string | Record<string, any>
- url: string
- } // router
commitConversionWindow: () => {
value: true
}
@@ -538,16 +527,12 @@ export const funnelDataLogic = kea<funnelDataLogicType>([
['aggregationLabel'],
featureFlagLogic,
['featureFlags'],
- router,
- ['searchParams'],
],
actions: [
insightVizDataLogic(props),
['updateInsightFilter', 'updateQuerySource'],
insightDataLogic(props),
['cancelChanges'],
- router,
- ['push'],
],
})),
@@ -1401,18 +1386,11 @@ export const funnelDataLogic = kea<funnelDataLogicType>([
}
},
setBreakdownSorting: ({ breakdownSorting }) => {
- actions.updateInsightFilter({ breakdownSorting })
+ // updateInsightFilter debounces 300ms, too slow for the table's controlled sort indicator
+ const update: Partial<FunnelsQuery> = {
+ funnelsFilter: { ...values.funnelsFilter, breakdownSorting },
+ }
+ actions.updateQuerySource(update)
},
})),
-
- afterMount(({ actions, values }) => {
- // Sync URL with saved sorting on mount
- if (values.breakdownSorting && !values.searchParams.order) {
- actions.push(
- window.location.pathname,
- { ...values.searchParams, order: values.breakdownSorting },
- window.location.hash
- )
- }
- }),
])
diff --git a/frontend/src/scenes/insights/views/Funnels/FunnelStepsTable.tsx b/frontend/src/scenes/insights/views/Funnels/FunnelStepsTable.tsx
index 817aa0f3ac68..a336124bc1ef 100644
--- a/frontend/src/scenes/insights/views/Funnels/FunnelStepsTable.tsx
+++ b/frontend/src/scenes/insights/views/Funnels/FunnelStepsTable.tsx
@@ -7,7 +7,7 @@ import { LemonColorButton, LemonTag } from '@posthog/lemon-ui'
import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { LemonRow } from 'lib/lemon-ui/LemonRow'
-import { LemonTable, LemonTableColumn, LemonTableColumnGroup } from 'lib/lemon-ui/LemonTable'
+import { LemonTable, LemonTableColumn, LemonTableColumnGroup, Sorting } from 'lib/lemon-ui/LemonTable'
import { Lettermark, LettermarkColor } from 'lib/lemon-ui/Lettermark'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
@@ -30,9 +30,8 @@ import { getActionFilterFromFunnelStep, getSignificanceFromBreakdownStep } from
export function FunnelStepsTable(): JSX.Element | null {
const { insightProps, insightLoading, editingDisabledReason } = useValues(insightLogic)
const { breakdownFilter } = useValues(insightVizDataLogic(insightProps))
- const { steps, flattenedBreakdowns, hiddenLegendBreakdowns, getFunnelsColor, isStepOptional } = useValues(
- funnelDataLogic(insightProps)
- )
+ const { steps, flattenedBreakdowns, hiddenLegendBreakdowns, getFunnelsColor, isStepOptional, breakdownSorting } =
+ useValues(funnelDataLogic(insightProps))
const { setHiddenLegendBreakdowns, toggleLegendBreakdownVisibility, setBreakdownSorting } = useActions(
funnelDataLogic(insightProps)
)
@@ -60,6 +59,15 @@ export function FunnelStepsTable(): JSX.Element | null {
queries. */
const showCustomizationIcon = !insightProps.cachedInsight?.disable_baseline
+ // Sorting is controlled by the query's `funnelsFilter.breakdownSorting`, so it survives
+ // saving/reloading and never touches the URL (a router push here would make the insight
+ // scene reload the saved insight, discarding unsaved changes like the compare filter).
+ const sorting: Sorting | null = breakdownSorting
+ ? breakdownSorting.startsWith('-')
+ ? { columnKey: breakdownSorting.slice(1), order: -1 }
+ : { columnKey: breakdownSorting, order: 1 }
+ : null
+
const columnsGrouped = [
{
children: [
@@ -403,7 +411,8 @@ export function FunnelStepsTable(): JSX.Element | null {
rowStatus={(record) => (record.significant ? 'highlighted' : null)}
rowRibbonColor={getFunnelsColor}
firstColumnSticky
- useURLForSorting
+ sorting={sorting}
+ useURLForSorting={false}
onSort={(newSorting) => {
if (!newSorting) {
setBreakdownSorting(undefined)