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(dashboards): persist list filters across navigation (#89556)

Matt Pua3fe2b69b933e
diff --git a/frontend/src/lib/logic/persistence.test.ts b/frontend/src/lib/logic/persistence.test.ts
index 5595b1ca5353..7ec2b03b5887 100644
--- a/frontend/src/lib/logic/persistence.test.ts
+++ b/frontend/src/lib/logic/persistence.test.ts
@@ -1,19 +1,26 @@
-import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { getCurrentTeamId, getCurrentUserIdOrNone } from 'lib/utils/getAppContext'
-import { buildTeamScopedPersistenceConfig, buildTeamScopedStorageConfig } from './persistence'
+import {
+ buildTeamScopedPersistenceConfig,
+ buildTeamScopedStorageConfig,
+ buildUserScopedPersistenceConfig,
+} from './persistence'
jest.mock('lib/utils/getAppContext')
const mockGetCurrentTeamId = getCurrentTeamId as jest.MockedFunction<typeof getCurrentTeamId>
+const mockGetCurrentUserIdOrNone = getCurrentUserIdOrNone as jest.MockedFunction<typeof getCurrentUserIdOrNone>
-describe('team-scoped persistence', () => {
+describe('persistence scoping', () => {
beforeEach(() => {
mockGetCurrentTeamId.mockReset()
+ mockGetCurrentUserIdOrNone.mockReset()
})
it.each([
['prefix config', () => buildTeamScopedPersistenceConfig('filters__')],
['storage config', () => buildTeamScopedStorageConfig('filters')],
+ ['user prefix config', () => buildUserScopedPersistenceConfig('filters__')],
])('fails closed without a project ID for %s', (_, buildConfig) => {
mockGetCurrentTeamId.mockImplementation(() => {
throw new Error('Project ID is not known.')
@@ -21,4 +28,31 @@ describe('team-scoped persistence', () => {
expect(buildConfig).toThrow('Project ID is not known.')
})
+
+ it('scopes persisted values to the current user and project', () => {
+ mockGetCurrentUserIdOrNone.mockReturnValue('user-1')
+ mockGetCurrentTeamId.mockReturnValue(2)
+
+ expect(buildUserScopedPersistenceConfig('filters__')).toEqual({
+ persist: true,
+ prefix: 'user-1__2__filters__',
+ })
+
+ mockGetCurrentTeamId.mockReturnValue(3)
+
+ expect(buildUserScopedPersistenceConfig('filters__')).toEqual({
+ persist: true,
+ prefix: 'user-1__3__filters__',
+ })
+ })
+
+ it('uses an anonymous key when no user ID is available', () => {
+ mockGetCurrentUserIdOrNone.mockReturnValue(null)
+ mockGetCurrentTeamId.mockReturnValue(2)
+
+ expect(buildUserScopedPersistenceConfig('filters__')).toEqual({
+ persist: true,
+ prefix: 'anonymous__2__filters__',
+ })
+ })
})
diff --git a/frontend/src/lib/logic/persistence.ts b/frontend/src/lib/logic/persistence.ts
index bbbe964f4372..91b3af4c3527 100644
--- a/frontend/src/lib/logic/persistence.ts
+++ b/frontend/src/lib/logic/persistence.ts
@@ -1,4 +1,4 @@
-import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { getCurrentTeamId, getCurrentUserIdOrNone } from 'lib/utils/getAppContext'
interface TeamScopedPersistenceConfig {
persist: true
@@ -10,10 +10,19 @@ interface TeamScopedStorageConfig {
storageKey: string
}
+interface UserScopedPersistenceConfig {
+ persist: true
+ prefix: string
+}
+
const getTeamStoragePrefix = (): string => {
return `${getCurrentTeamId()}__`
}
+const getUserStoragePrefix = (): string => {
+ return `${getCurrentUserIdOrNone() ?? 'anonymous'}__${getTeamStoragePrefix()}`
+}
+
export const buildTeamScopedPersistenceConfig = (prefix: string = ''): TeamScopedPersistenceConfig => ({
persist: true,
prefix: `${getTeamStoragePrefix()}${prefix}`,
@@ -23,3 +32,8 @@ export const buildTeamScopedStorageConfig = (storageKey: string): TeamScopedStor
persist: true,
storageKey: `${getTeamStoragePrefix()}${storageKey}`,
})
+
+export const buildUserScopedPersistenceConfig = (prefix: string = ''): UserScopedPersistenceConfig => ({
+ persist: true,
+ prefix: `${getUserStoragePrefix()}${prefix}`,
+})
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index 3902f97453e4..a4e58d25b059 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -4,7 +4,12 @@ import { router } from 'kea-router'
import { expectLogic, truth } from 'kea-test-utils'
import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
-import { DashboardsFilters, DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
+import {
+ DashboardsFilters,
+ DashboardsTab,
+ DEFAULT_FILTERS,
+ dashboardsLogic,
+} from 'scenes/dashboard/dashboards/dashboardsLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -75,6 +80,7 @@ describe('dashboardsLogic', () => {
beforeEach(async () => {
jest.clearAllMocks()
+ localStorage.clear()
window.POSTHOG_APP_CONTEXT = { current_user: MOCK_DEFAULT_USER } as unknown as AppContext
useMocks({
@@ -98,6 +104,62 @@ describe('dashboardsLogic', () => {
logic.mount()
})
+ it('restores list filters after navigating away and returning', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ createdBy: [OTHER_USER.id], pinned: true, shared: true, tags: ['finance'] })
+ }).toFinishAllListeners()
+
+ logic.unmount()
+ router.actions.push('/settings')
+ router.actions.push('/dashboard')
+
+ logic = dashboardsLogic({ tabId: '1' })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters).toEqual(
+ expect.objectContaining({ createdBy: [OTHER_USER.id], pinned: true, shared: true, tags: ['finance'] })
+ )
+ expect(router.values.searchParams).toEqual(
+ expect.objectContaining({ created_by: [OTHER_USER.id], pinned: true, shared: true, tags: ['finance'] })
+ )
+ })
+
+ it('does not restore filters saved by another user', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ pinned: true })
+ }).toFinishAllListeners()
+
+ logic.unmount()
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ current_user: { ...MOCK_DEFAULT_USER, uuid: 'ANOTHER_USER_UUID' },
+ } as unknown as AppContext
+ router.actions.push('/settings')
+ router.actions.push('/dashboard')
+
+ logic = dashboardsLogic({ tabId: '1' })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters).toEqual(DEFAULT_FILTERS)
+ })
+
+ it('clears the created by filter when switching to my dashboards', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ createdBy: [OTHER_USER.id] })
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setCurrentTab(DashboardsTab.Yours)
+ }).toFinishAllListeners()
+
+ expect(logic.values.filters.createdBy).toBe('All users')
+ expect(router.values.searchParams.created_by).toBeUndefined()
+ })
+
describe('reflecting a completed move', () => {
it('updates the moved dashboard to its new folder', async () => {
await expectLogic(logic, () => {
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index b984f795ed3e..9f442290a374 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -6,6 +6,7 @@ import api, { PaginatedResponse } from 'lib/api'
import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { buildUserScopedPersistenceConfig } from 'lib/logic/persistence'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectClean, objectsEqual } from 'lib/utils/objects'
@@ -237,45 +238,51 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
setTagSearch: (search: string) => ({ search }),
setShowTagPopover: (visible: boolean) => ({ visible }),
}),
- reducers({
- tableSorting: [
- DEFAULT_SORTING,
- { persist: true },
- {
- tableSortingChanged: (_, { sorting }) => sorting || DEFAULT_SORTING,
- },
- ],
- currentTab: [
- DashboardsTab.All as DashboardsTab,
- {
- setCurrentTab: (_, { tab }) => tab,
- },
- ],
+ reducers(() => {
+ const filtersPersistence = buildUserScopedPersistenceConfig('dashboard_list_filters__')
+ return {
+ tableSorting: [
+ DEFAULT_SORTING,
+ { persist: true },
+ {
+ tableSortingChanged: (_, { sorting }) => sorting || DEFAULT_SORTING,
+ },
+ ],
+ currentTab: [
+ DashboardsTab.All as DashboardsTab,
+ {
+ setCurrentTab: (_, { tab }) => tab,
+ },
+ ],
- filters: [
- DEFAULT_FILTERS,
- {
- setFilters: (state, { filters }) =>
- objectClean({
- ...state,
- ...filters,
- }),
- setSearch: (state, { search }) => ({ ...state, search }),
- },
- ],
- tagSearch: [
- '',
- {
- setTagSearch: (_, { search }) => search,
- setShowTagPopover: (state, { visible }) => (visible ? state : ''),
- },
- ],
- showTagPopover: [
- false,
- {
- setShowTagPopover: (_, { visible }) => visible,
- },
- ],
+ filters: [
+ DEFAULT_FILTERS,
+ filtersPersistence,
+ {
+ setFilters: (state, { filters }) =>
+ objectClean({
+ ...state,
+ ...filters,
+ }),
+ setSearch: (state, { search }) => ({ ...state, search }),
+ setCurrentTab: (state, { tab }) =>
+ tab === DashboardsTab.Yours ? { ...state, createdBy: DEFAULT_FILTERS.createdBy } : state,
+ },
+ ],
+ tagSearch: [
+ '',
+ {
+ setTagSearch: (_, { search }) => search,
+ setShowTagPopover: (state, { visible }) => (visible ? state : ''),
+ },
+ ],
+ showTagPopover: [
+ false,
+ {
+ setShowTagPopover: (_, { visible }) => visible,
+ },
+ ],
+ }
}),
loaders({
@@ -435,14 +442,15 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
trackedActionToUrl(({ values }) => ({
setCurrentTab: () => {
const tab = values.currentTab === DashboardsTab.All ? undefined : values.currentTab
- if (router.values.searchParams['tab'] === tab) {
+ const searchParams: Record<string, any> = { ...router.values.searchParams, tab }
+ if (values.currentTab === DashboardsTab.Yours) {
+ delete searchParams['created_by']
+ }
+ if (objectsEqual(searchParams, router.values.searchParams)) {
return
}
- router.actions.push(router.values.location.pathname, {
- ...router.values.searchParams,
- tab,
- })
+ router.actions.push(router.values.location.pathname, searchParams)
},
setSearch: ({ search }) => {
const nextSearch = search ?? ''
@@ -512,6 +520,32 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
actions.setCurrentTab(tab)
}
+ const hasFilterParams = ['created_by', 'pinned', 'shared', 'tags', 'folder', 'search'].some(
+ (key) => key in searchParams
+ )
+ if (tab === DashboardsTab.Yours && values.filters.createdBy !== DEFAULT_FILTERS.createdBy) {
+ actions.setFilters({ createdBy: DEFAULT_FILTERS.createdBy })
+ }
+ if (!hasFilterParams) {
+ const { search: _search, ...filtersWithoutSearch } = values.filters
+ const { search: _defaultSearch, ...defaultsWithoutSearch } = DEFAULT_FILTERS
+ let filtersToRestore: Partial<DashboardsFilters> = filtersWithoutSearch
+ let defaultFilters: Partial<DashboardsFilters> = defaultsWithoutSearch
+ if (tab === DashboardsTab.Yours) {
+ const { createdBy: _createdBy, ...filtersWithoutCreatedBy } = filtersToRestore
+ const { createdBy: _defaultCreatedBy, ...defaultsWithoutCreatedBy } = defaultFilters
+ filtersToRestore = filtersWithoutCreatedBy
+ defaultFilters = defaultsWithoutCreatedBy
+ }
+ if (!objectsEqual(filtersToRestore, defaultFilters)) {
+ actions.setFilters(filtersToRestore)
+ }
+ if (values.filters.search) {
+ actions.setSearch(values.filters.search)
+ }
+ return
+ }
+
// Apply non-search filters before search so the setSearch listener's server fetch
// sees the freshly-restored tags. Guard each dispatch on a real change so that the
// actionToUrl -> locationChanged -> urlToAction round trip doesn't re-fire listeners