: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
fix(data-table): apply the auto-selected saved view to the table (#96280)
Ben Lead38221b57aa5
diff --git a/frontend/src/queries/nodes/DataTable/TableView/TableViewSelector.tsx b/frontend/src/queries/nodes/DataTable/TableView/TableViewSelector.tsxindex d666d31b2194..e17e1a2118ad 100644--- a/frontend/src/queries/nodes/DataTable/TableView/TableViewSelector.tsx+++ b/frontend/src/queries/nodes/DataTable/TableView/TableViewSelector.tsx@@ -91,10 +91,10 @@ export function TableViewSelector({ contextKey, query, setQuery }: TableViewSelereturn (<BindLogic logic={tableViewLogic} props={tableViewLogicProps}><div className="flex items-center gap-2">- {currentView ? (+ {views.length > 0 ? (<LemonMenu items={menuItems} closeOnClickInside={true}><LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>- {currentView.name ? (+ {currentView?.name ? (<><ViewVisibilityIcon view={currentView} />{' '}<span className="ml-2">{currentView.name}</span>diff --git a/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.test.ts b/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.test.tsnew file mode 100644index 000000000000..a1269e2cceee--- /dev/null+++ b/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.test.ts@@ -0,0 +1,112 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'+import { ActorsQuery, NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { PEOPLE_LIST_CONTEXT_KEY, PEOPLE_LIST_DEFAULT_QUERY } from 'products/persons/frontend/logics/personsSceneLogic'++import { tableViewLogic } from './tableViewLogic'++const SHARED_VIEW = {+ id: '01234567-89ab-cdef-0123-456789abcdef',+ context_key: PEOPLE_LIST_CONTEXT_KEY,+ name: 'Distinct IDs',+ columns: ['person_display_name -- Person', 'pdi.distinct_id'],+ filters: [],+ order_by: [],+ visibility: 'shared',+ created_by: 4242,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+}++describe('tableViewLogic', () => {+ const defaultSelect = [...defaultDataTableColumns(NodeKind.ActorsQuery, false), 'person.$delete']++ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/column_configurations/': () => [200, { results: [SHARED_VIEW] }],+ },+ })+ initKeaTests()+ // Start each case as a browser that never picked a view, which is where a teammate is+ // when someone else created the view.+ localStorage.clear()+ })++ // `currentView` persists per team and context, so a test seeds it the way a browser that+ // already picked a view would have it.+ const persistSelection = (view: typeof SHARED_VIEW): void => {+ localStorage.setItem(+ `queries.nodes.DataTable.TableView.tableViewLogic.${MOCK_TEAM_ID}.${PEOPLE_LIST_CONTEXT_KEY}.currentView`,+ JSON.stringify(view)+ )+ }++ const mountLogic = (select: string[]): { logic: ReturnType<typeof tableViewLogic.build>; setQuery: jest.Mock } => {+ const setQuery = jest.fn()+ const logic = tableViewLogic({+ contextKey: PEOPLE_LIST_CONTEXT_KEY,+ query: { ...PEOPLE_LIST_DEFAULT_QUERY.source, select } as ActorsQuery,+ setQuery,+ })+ logic.mount()+ return { logic, setQuery }+ }++ it('leaves the table and the selection alone when this user never picked a view', async () => {+ const { logic, setQuery } = mountLogic(defaultSelect)++ await expectLogic(logic, () => {+ logic.actions.loadViews()+ }).toFinishAllListeners()++ expect(logic.values.views.map((view) => view.id)).toEqual([SHARED_VIEW.id])+ expect(logic.values.currentView).toBeNull()+ expect(setQuery).not.toHaveBeenCalled()+ })++ it('reapplies the picked view once the list confirms it, when the query is the untouched default', async () => {+ persistSelection(SHARED_VIEW)+ const { logic, setQuery } = mountLogic(defaultSelect)++ await expectLogic(logic, () => {+ logic.actions.loadViews()+ }).toFinishAllListeners()++ expect(logic.values.currentView?.id).toEqual(SHARED_VIEW.id)+ expect(setQuery).toHaveBeenCalledTimes(1)+ expect(setQuery.mock.calls[0][0].select).toEqual(SHARED_VIEW.columns)+ })++ it('keeps the picked view but leaves a query the user already changed', async () => {+ persistSelection(SHARED_VIEW)+ const { logic, setQuery } = mountLogic([...defaultSelect, 'properties.email'])++ await expectLogic(logic, () => {+ logic.actions.loadViews()+ }).toFinishAllListeners()++ expect(logic.values.currentView?.id).toEqual(SHARED_VIEW.id)+ expect(setQuery).not.toHaveBeenCalled()+ })++ // The untouched default is the only query shape a view gets applied to, so a deleted view+ // paired with a changed query would pass whether or not the list is consulted first.+ it('clears a picked view the list no longer returns without touching the table', async () => {+ persistSelection({ ...SHARED_VIEW, id: 'fedcba98-7654-3210-fedc-ba9876543210', name: 'Deleted view' })+ const { logic, setQuery } = mountLogic(defaultSelect)++ await expectLogic(logic, () => {+ logic.actions.loadViews()+ }).toFinishAllListeners()++ expect(logic.values.currentView).toBeNull()+ expect(setQuery).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.ts b/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.tsindex 0ad6822e9a02..743984074bf4 100644--- a/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.ts+++ b/frontend/src/queries/nodes/DataTable/TableView/tableViewLogic.ts@@ -1,5 +1,5 @@import { deepEqual as equal } from 'fast-equals'-import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { lazyLoaders } from 'kea-loaders'@@ -17,7 +17,7 @@ import { AnyPropertyFilter, PropertyOperator } from '~/types'import { GROUPS_LIST_DEFAULT_QUERY } from 'products/groups/frontend/logics/groupsListLogic'import { PERSON_EVENTS_CONTEXT_KEY } from 'products/persons/frontend/logics/personsLogic'-import { PEOPLE_LIST_CONTEXT_KEY, PEOPLE_LIST_DEFAULT_QUERY } from 'products/persons/frontend/logics/personsSceneLogic'+import { PEOPLE_LIST_CONTEXT_KEY, isPeopleListDefaultQuery } from 'products/persons/frontend/logics/personsSceneLogic'import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'import type { UserType } from '../../../../types'@@ -91,6 +91,27 @@ function isInitialPersonEventsQuery(query: TableViewSupportedQueryType): booleanreturn equal(query.select, defaultColumns) && !query.properties?.length && !query.event && !query.events?.length}+// Applying a remembered view is only safe while the table still shows its default query.+// Anywhere else it would overwrite columns the user picked, or a query that arrived in the URL.+function isUntouchedDefaultQuery(contextKey: string, query: TableViewSupportedQueryType): boolean {+ switch (contextKey) {+ case PEOPLE_LIST_CONTEXT_KEY:+ return isPeopleListDefaultQuery(query)+ case 'group-0-list':+ case 'group-1-list':+ case 'group-2-list':+ case 'group-3-list':+ case 'group-4-list': {+ const groupTypeIndex = parseInt(contextKey.split('-')[1])+ return equal(query, GROUPS_LIST_DEFAULT_QUERY(groupTypeIndex).source)+ }+ case PERSON_EVENTS_CONTEXT_KEY:+ return isInitialPersonEventsQuery(query)+ default:+ return false+ }+}+function getQueryFromView(query: TableViewSupportedQueryType,view: ColumnConfigurationApi@@ -415,15 +436,11 @@ export const tableViewLogic = kea<tableViewLogicType>([{setCurrentView: (_, { view }) => view,applyView: (_, { view }) => view,- loadViewsSuccess: (state, { views }) => {- if (views.length === 0) {- return null- }- if (!state) {- return views[0] || null- }- return state- },+ // Keep only a view this user picked, and only while the list still has it. Falling+ // back to the first view would select the shared view a teammate created most+ // recently, because the API lists shared views newest first.+ loadViewsSuccess: (state, { views }) =>+ state && views.some((view) => view.id === state.id) ? state : null,deleteViewSuccess: (state, { views }) => {if (state && !views.find((v) => v.id === state.id)) {return null@@ -491,7 +508,7 @@ export const tableViewLogic = kea<tableViewLogicType>([},})),- listeners(({ props, actions, values }) => ({+ listeners(({ props, actions, values, cache }) => ({applyView: ({ view }) => {props.setQuery(getQueryFromView(props.query, view))},@@ -527,6 +544,22 @@ export const tableViewLogic = kea<tableViewLogicType>([lemonToast.error('Error deleting view')},+ loadViewsSuccess: () => {+ // Restoring on mount would apply the columns of a view its creator has since deleted,+ // because the pick lives in this browser's storage, and clearing the pick afterwards+ // does not take those columns back off the table. The reducer runs before this, so+ // currentView is already null when the list dropped the view. Restore on the first+ // list only, so the refresh after saving a view does not apply the pick again.+ if (cache.restoredStoredView) {+ return+ }+ cache.restoredStoredView = true++ if (values.currentView && isUntouchedDefaultQuery(props.contextKey, props.query)) {+ actions.applyView(values.currentView)+ }+ },+loadViewsFailure: (error) => {posthog.captureException(error)lemonToast.error('Error loading views')@@ -545,33 +578,4 @@ export const tableViewLogic = kea<tableViewLogicType>([lemonToast.error('Error creating view')},})),-- afterMount(({ values, actions, props }) => {- if (!values.currentView) {- return- }-- switch (props.contextKey) {- case PEOPLE_LIST_CONTEXT_KEY:- if (equal(props.query, PEOPLE_LIST_DEFAULT_QUERY.source)) {- actions.applyView(values.currentView)- }- break- case 'group-0-list':- case 'group-1-list':- case 'group-2-list':- case 'group-3-list':- case 'group-4-list':- const groupTypeIndex = parseInt(props.contextKey.split('-')[1])- if (equal(props.query, GROUPS_LIST_DEFAULT_QUERY(groupTypeIndex).source)) {- actions.applyView(values.currentView)- }- break- case PERSON_EVENTS_CONTEXT_KEY:- if (isInitialPersonEventsQuery(props.query)) {- actions.applyView(values.currentView)- }- break- }- }),])diff --git a/products/persons/frontend/logics/personsSceneLogic.test.ts b/products/persons/frontend/logics/personsSceneLogic.test.tsindex e5e68d913522..d9cb93c9d5fc 100644--- a/products/persons/frontend/logics/personsSceneLogic.test.ts+++ b/products/persons/frontend/logics/personsSceneLogic.test.ts@@ -5,10 +5,11 @@ import { Scene } from 'scenes/sceneTypes'import { useMocks } from '~/mocks/jest'import { MockSignature } from '~/mocks/utils'+import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { PEOPLE_LIST_DEFAULT_QUERY, personsSceneLogic } from './personsSceneLogic'+import { PEOPLE_LIST_DEFAULT_QUERY, isPeopleListDefaultQuery, personsSceneLogic } from './personsSceneLogic'const blankScene = (): any => ({ scene: { component: () => null, logic: null } })const scenes: any = { [Scene.Persons]: blankScene }@@ -116,4 +117,18 @@ describe('personsSceneLogic', () => {expect(spy).toHaveBeenCalledTimes(1)})})++ describe('isPeopleListDefaultQuery', () => {+ const defaultSelect = [...defaultDataTableColumns(NodeKind.ActorsQuery, false), 'person.$delete']+ const lastSeenAtSelect = [...defaultDataTableColumns(NodeKind.ActorsQuery, true), 'person.$delete']++ it.each<[string, string[], boolean]>([+ ['the default columns', defaultSelect, true],+ ['the default columns for a team that tracks last seen at', lastSeenAtSelect, true],+ ['an extra column the user added', [...defaultSelect, 'pdi.distinct_id'], false],+ ['a narrower set of columns', ['id'], false],+ ])('%s', (_label, select, expected) => {+ expect(isPeopleListDefaultQuery({ ...PEOPLE_LIST_DEFAULT_QUERY.source, select })).toBe(expected)+ })+ })})diff --git a/products/persons/frontend/logics/personsSceneLogic.ts b/products/persons/frontend/logics/personsSceneLogic.tsindex da92712f5779..d77a043aba52 100644--- a/products/persons/frontend/logics/personsSceneLogic.ts+++ b/products/persons/frontend/logics/personsSceneLogic.ts@@ -36,6 +36,18 @@ function buildDefaultQuery(personLastSeenAtEnabled: boolean): DataTableNode {export const PEOPLE_LIST_DEFAULT_QUERY = buildDefaultQuery(false)+// The scene's real default gains a `last_seen_at` column when the team turns on that setting,+// so a caller that checks for an untouched default has to accept both shapes.+const PEOPLE_LIST_DEFAULT_QUERY_WITH_LAST_SEEN_AT = buildDefaultQuery(true)++/** Takes an `ActorsQuery` source, not the whole `DataTableNode`. */+export function isPeopleListDefaultQuery(source: unknown): boolean {+ return (+ equal(source, PEOPLE_LIST_DEFAULT_QUERY.source) ||+ equal(source, PEOPLE_LIST_DEFAULT_QUERY_WITH_LAST_SEEN_AT.source)+ )+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface personsSceneLogicValues {currentTeam: TeamPublicType | TeamType | null // teamLogic