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.

feat(dashboards): persist list filters in the URL (#64008)

Xander099e0f8f745b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c7f4c6685ee1..d24645d27d4c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4805,9 +4805,9 @@ snapshots:
scenes-app-dashboards--erroring--light:
hash: v1.k794b7964.5b99ae7b5f3126b06df72ccc0388ac72f1638137bb78cabeb47e9b597deb4dfc.FGPopoAtkZvSgIq_4yhg85qh1yBD3WbPV2uxNT_oK3s
scenes-app-dashboards--list--dark:
- hash: v1.k794b7964.c6e2c063609be338de448715f18780d83c3e46d2e5d30000be1f840a01208cc8.aUThuAoBngtbgLeJADx0flGzPr9M8pIkMGCihBqaSZg
+ hash: v1.k794b7964.a735e8364147e1b3f94e285b473354d1f2acdbec0114558ea1dccbee35b3dc0b.69WhwAmN_fgLTVDxuCaMhH_TCax8-LYi9uXPgAmq7jA
scenes-app-dashboards--list--light:
- hash: v1.k794b7964.8830085244294e0998f75b7805e31997fe3f8e902e8ce6ed520bafd4f89eccfe.zZFHNK5bnATbtkmxX4tXzkG5HpFV5aDc7mPJFh-ziaI
+ hash: v1.k794b7964.eb29aeae3999f033ac12af7daf526f26d622beaf9fe4e4c982ac5d7308820df6.41aiVSN5mLFsmMLGFmWfKO1u9T6A8aNv5wCsYVoaJdY
scenes-app-dashboards--new--dark:
hash: v1.k794b7964.48cc5953ac30948bad06bb245aeea3d1ac2698c7b583997d5d33c176f18af9d2.fvPhi1TnDZJLEJK4_HKUdO91VkcFZIFR1ybw-qq69dg
scenes-app-dashboards--new--light:
diff --git a/frontend/src/lib/components/MemberSelectMultiplePopover.tsx b/frontend/src/lib/components/MemberSelectMultiplePopover.tsx
new file mode 100644
index 000000000000..014eb811fc7e
--- /dev/null
+++ b/frontend/src/lib/components/MemberSelectMultiplePopover.tsx
@@ -0,0 +1,136 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonDropdown, ProfilePicture } from '@posthog/lemon-ui'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
+import { fullName } from 'lib/utils/strings'
+import { membersLogic } from 'scenes/organization/membersLogic'
+
+export type MemberSelectMultiplePopoverProps = {
+ /** Currently selected member user ids. */
+ value: number[]
+ onChange: (value: number[]) => void
+ /** Trigger button label, also used in the "<label> you" / "<label> (N)" summaries. */
+ label?: string
+ /** When true, the trigger appears borderless (alt status) while nothing is selected. */
+ borderless?: boolean
+}
+
+/**
+ * Multi-select of organization members rendered as a labeled dropdown with a searchable,
+ * checkbox member list. Shared by the dashboards and insights "Created by" filters.
+ *
+ * For a single-select member picker use `MemberSelect`; for a chip-style multi-select input
+ * use `MemberSelectMultiple`.
+ */
+export function MemberSelectMultiplePopover({
+ value,
+ onChange,
+ label = 'Created by',
+ borderless = false,
+}: MemberSelectMultiplePopoverProps): JSX.Element {
+ const { meFirstMembers, filteredMembers, membersLoading, search } = useValues(membersLogic)
+ const { ensureAllMembersLoaded, setSearch } = useActions(membersLogic)
+
+ const hasSelection = value.length > 0
+ const currentUserId = meFirstMembers[0]?.user.id
+ const isFilteredToCurrentUser = hasSelection && value.length === 1 && value[0] === currentUserId
+
+ const toggleMember = (userId: number): void => {
+ const selected = new Set(value)
+ if (selected.has(userId)) {
+ selected.delete(userId)
+ } else {
+ selected.add(userId)
+ }
+ onChange(Array.from(selected))
+ }
+
+ return (
+ <LemonDropdown
+ closeOnClickInside={false}
+ matchWidth={false}
+ placement="bottom-end"
+ actionable
+ onVisibilityChange={(visible) => {
+ if (visible) {
+ ensureAllMembersLoaded()
+ setSearch('')
+ }
+ }}
+ overlay={
+ <div className="max-w-100 deprecated-space-y-2">
+ <LemonInput
+ type="search"
+ placeholder="Search"
+ autoFocus
+ value={search}
+ onChange={setSearch}
+ fullWidth
+ />
+ <ul className="deprecated-space-y-px">
+ {filteredMembers.map((member) => (
+ <li key={member.user.uuid}>
+ <LemonButton
+ fullWidth
+ role="menuitem"
+ size="small"
+ icon={<ProfilePicture size="md" user={member.user} />}
+ onClick={() => toggleMember(member.user.id)}
+ >
+ <span className="flex items-center justify-between gap-2 flex-1">
+ <span className="flex items-center gap-2 max-w-full">
+ <input
+ type="checkbox"
+ className="cursor-pointer"
+ checked={value.includes(member.user.id)}
+ readOnly
+ />
+ <span>{fullName(member.user)}</span>
+ </span>
+ <span className="text-secondary">
+ {meFirstMembers[0] === member && `(you)`}
+ </span>
+ </span>
+ </LemonButton>
+ </li>
+ ))}
+ {membersLoading ? (
+ <div className="p-2 text-secondary italic truncate border-t">Loading...</div>
+ ) : filteredMembers.length === 0 ? (
+ <div className="p-2 text-secondary italic truncate border-t">
+ {search ? <span>No matches</span> : <span>No users</span>}
+ </div>
+ ) : null}
+ {hasSelection && (
+ <>
+ <div className="my-1 border-t" />
+ <li>
+ <LemonButton
+ fullWidth
+ role="menuitem"
+ size="small"
+ onClick={() => onChange([])}
+ type="tertiary"
+ >
+ Clear selection
+ </LemonButton>
+ </li>
+ </>
+ )}
+ </ul>
+ </div>
+ }
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ status={borderless && !hasSelection ? 'alt' : 'default'}
+ active={hasSelection}
+ >
+ {isFilteredToCurrentUser ? `${label} you` : hasSelection ? `${label} (${value.length})` : label}
+ </LemonButton>
+ </LemonDropdown>
+ )
+}
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx
index 36eb9c268d01..dd7b9bce74c5 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx
@@ -4,7 +4,7 @@ import { useDebouncedCallback } from 'use-debounce'
import { IconChevronDown, IconFolder, IconPin, IconPinFilled, IconShare, IconX } from '@posthog/icons'
import { LemonInput, Popover } from '@posthog/lemon-ui'
-import { MemberSelect } from 'lib/components/MemberSelect'
+import { MemberSelectMultiplePopover } from 'lib/components/MemberSelectMultiplePopover'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
@@ -16,6 +16,8 @@ export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarProps
const { filters, currentTab, filteredTags, tagSearch, showTagPopover } = useValues(dashboardsLogic)
const { setFilters, setTagSearch, setShowTagPopover, setSearch } = useActions(dashboardsLogic)
+ const createdByIds = filters.createdBy === 'All users' ? [] : filters.createdBy
+
const debouncedSetSearch = useDebouncedCallback((value: string) => {
setSearch(value)
}, 300)
@@ -160,13 +162,10 @@ export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarProps
)}
</div>
{currentTab !== DashboardsTab.Yours && (
- <div className="flex items-center gap-2">
- <span>Created by:</span>
- <MemberSelect
- value={filters.createdBy === 'All users' ? null : filters.createdBy}
- onChange={(user) => setFilters({ createdBy: user?.uuid || 'All users' })}
- />
- </div>
+ <MemberSelectMultiplePopover
+ value={createdByIds}
+ onChange={(ids) => setFilters({ createdBy: ids.length > 0 ? ids : 'All users' })}
+ />
)}
{extraActions}
</div>
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index 4f6fd6fbbd64..c8d461966e3a 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -3,7 +3,7 @@ import { MOCK_DEFAULT_USER } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic, truth } from 'kea-test-utils'
-import { DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
+import { DashboardsFilters, DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -32,28 +32,31 @@ const scenes: any = { [Scene.Dashboards]: blankScene }
describe('dashboardsLogic', () => {
let logic: ReturnType<typeof dashboardsLogic.build>
+ const CURRENT_USER = { id: 178, uuid: 'USER_UUID' } as UserBasicType
+ const OTHER_USER = { id: 2, uuid: 'user2' } as UserBasicType
+
const allDashboards = [
- { ...dashboard({ created_by: { uuid: 'USER_UUID' } as UserBasicType, is_shared: true }) },
- { ...dashboard({ created_by: { uuid: 'USER_UUID' } as UserBasicType, pinned: true }) },
- { ...dashboard({ created_by: { uuid: 'user2' } as UserBasicType, pinned: true }) },
+ { ...dashboard({ created_by: CURRENT_USER, is_shared: true }) },
+ { ...dashboard({ created_by: CURRENT_USER, pinned: true }) },
+ { ...dashboard({ created_by: OTHER_USER, pinned: true }) },
{
...dashboard({
- created_by: { uuid: 'USER_UUID' } as UserBasicType,
+ created_by: CURRENT_USER,
is_shared: true,
pinned: true,
}),
},
- { ...dashboard({ created_by: { uuid: 'USER_UUID' } as UserBasicType, folder: 'Marketing/Website' }) },
+ { ...dashboard({ created_by: CURRENT_USER, folder: 'Marketing/Website' }) },
{
...dashboard({
- created_by: { uuid: 'user2' } as UserBasicType,
+ created_by: OTHER_USER,
name: 'needle',
folder: 'Marketing/Website',
}),
},
{
...dashboard({
- created_by: { uuid: 'USER_UUID' } as UserBasicType,
+ created_by: CURRENT_USER,
name: 'VMS Feature - History Browser - Nova',
}),
},
@@ -112,7 +115,7 @@ describe('dashboardsLogic', () => {
it('shows correct dashboards when filtering by name', async () => {
expectLogic(logic, () => {
- logic.actions.setFilters({ createdBy: 'user2' })
+ logic.actions.setFilters({ createdBy: [OTHER_USER.id] })
}).toMatchValues({
dashboards: truth((dashboards: DashboardType[]) => {
return (
@@ -136,9 +139,19 @@ describe('dashboardsLogic', () => {
})
})
+ it('shows dashboards from all selected creators when multiple are chosen', async () => {
+ // Multi-select is a union: selecting both users returns every dashboard, since each was
+ // created by one of them.
+ expectLogic(logic, () => {
+ logic.actions.setFilters({ createdBy: [CURRENT_USER.id, OTHER_USER.id] })
+ }).toMatchValues({
+ dashboards: truth((dashboards: DashboardType[]) => dashboards.length === allDashboards.length),
+ })
+ })
+
it('shows correct dashboards when filtering by name and shared', async () => {
expectLogic(logic, () => {
- logic.actions.setFilters({ createdBy: 'user2', shared: true })
+ logic.actions.setFilters({ createdBy: [OTHER_USER.id], shared: true })
}).toMatchValues({
dashboards: [],
})
@@ -147,7 +160,7 @@ describe('dashboardsLogic', () => {
it('shows correct dashboards when filtering by name and on pinned tab', async () => {
expectLogic(logic, () => {
logic.actions.setCurrentTab(DashboardsTab.Pinned)
- logic.actions.setFilters({ createdBy: 'user2' })
+ logic.actions.setFilters({ createdBy: [OTHER_USER.id] })
}).toMatchValues({
dashboards: truth((dashboards: DashboardType[]) => {
return dashboards.length === 1 && dashboards[0].pinned
@@ -224,7 +237,7 @@ describe('dashboardsLogic', () => {
await expectLogic(logic, () => {
logic.actions.setFilters({ pinned: true })
logic.actions.setFilters({ shared: true })
- logic.actions.setFilters({ createdBy: 'someone-uuid' })
+ logic.actions.setFilters({ createdBy: [999] })
}).toNotHaveDispatchedActions(['loadSearchedDashboards'])
})
@@ -316,4 +329,111 @@ describe('dashboardsLogic', () => {
filters: expect.objectContaining({ search: '33333333' }),
})
})
+
+ const urlWriteCases: Array<{
+ name: string
+ set: Partial<DashboardsFilters>
+ reset: Partial<DashboardsFilters>
+ param: string
+ expected: unknown
+ }> = [
+ {
+ name: 'created_by',
+ set: { createdBy: [2] },
+ reset: { createdBy: 'All users' },
+ param: 'created_by',
+ expected: [2],
+ },
+ { name: 'pinned', set: { pinned: true }, reset: { pinned: false }, param: 'pinned', expected: true },
+ { name: 'shared', set: { shared: true }, reset: { shared: false }, param: 'shared', expected: true },
+ { name: 'tags', set: { tags: ['finance'] }, reset: { tags: [] }, param: 'tags', expected: ['finance'] },
+ ]
+
+ it.each(urlWriteCases)(
+ 'syncs $name to the URL and removes it on reset',
+ async ({ set, reset, param, expected }) => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters(set)
+ })
+ expect(router.values.searchParams[param]).toEqual(expected)
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilters(reset)
+ })
+ expect(router.values.searchParams[param]).toBeUndefined()
+ }
+ )
+
+ const urlReadCases: Array<{
+ name: string
+ params: Record<string, unknown>
+ expected: Partial<DashboardsFilters>
+ }> = [
+ { name: 'created_by', params: { created_by: [2] }, expected: { createdBy: [2] } },
+ { name: 'pinned', params: { pinned: true }, expected: { pinned: true } },
+ { name: 'shared', params: { shared: true }, expected: { shared: true } },
+ { name: 'tags', params: { tags: ['finance', 'q4'] }, expected: { tags: ['finance', 'q4'] } },
+ ]
+
+ it.each(urlReadCases)('loads $name from the URL into filters on mount', async ({ params, expected }) => {
+ logic.unmount()
+ router.actions.push(urls.dashboards(), params)
+ logic = dashboardsLogic({ tabId: '1' })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({
+ filters: expect.objectContaining(expected),
+ })
+ })
+
+ it('restores both search and tags from the URL and fetches with the restored tags', async () => {
+ let lastRequestUrl: URL | null = null
+ useMocks({
+ get: {
+ '/api/environments/:team_id/dashboards/': ({ request }) => {
+ lastRequestUrl = new URL(request.url)
+ return [200, { count: 0, next: null, previous: null, results: [] }]
+ },
+ },
+ })
+
+ logic.unmount()
+ router.actions.push(urls.dashboards(), { search: 'sales', tags: ['finance'] })
+ logic = dashboardsLogic({ tabId: '1' })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadSearchedDashboardsSuccess'])
+
+ expect(logic.values.filters).toEqual(expect.objectContaining({ search: 'sales', tags: ['finance'] }))
+ expect(lastRequestUrl).not.toBeNull()
+ expect(lastRequestUrl!.searchParams.get('search')).toBe('sales')
+ expect(lastRequestUrl!.searchParams.getAll('tags')).toEqual(['finance'])
+ })
+
+ it('does not refetch when toggling pinned while a search is active on the /dashboard URL', async () => {
+ // Toggling pinned writes ?pinned=true to the URL, which round-trips back through
+ // urlToAction. The guard there must not re-dispatch setSearch and trigger a redundant
+ // server search. (The earlier regression test runs on pathname '/' so it never matches
+ // urlToAction — this one mounts on /dashboard to exercise that round trip.)
+ useMocks({
+ get: {
+ '/api/environments/:team_id/dashboards/': () => {
+ return [200, { count: 0, next: null, previous: null, results: [] }]
+ },
+ },
+ })
+
+ logic.unmount()
+ router.actions.push(urls.dashboards())
+ logic = dashboardsLogic({ tabId: '1' })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.setSearch('sales')
+ }).toDispatchActions(['loadSearchedDashboardsSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ pinned: true })
+ }).toNotHaveDispatchedActions(['loadSearchedDashboards'])
+ })
})
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index 06c52ea53720..4f66f3e7a837 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -6,7 +6,7 @@ import api, { PaginatedResponse } from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
-import { objectClean } from 'lib/utils/objects'
+import { objectClean, objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
@@ -28,7 +28,7 @@ const DEFAULT_SORTING: Sorting = { columnKey: 'name', order: 1 }
export interface DashboardsFilters {
search: string
- createdBy: string
+ createdBy: number[] | 'All users'
pinned: boolean
shared: boolean
tags?: string[]
@@ -211,7 +211,8 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
if (currentTab === DashboardsTab.Yours) {
haystack = haystack.filter((d) => d.created_by?.uuid === user?.uuid)
} else if (filters.createdBy !== 'All users') {
- haystack = haystack.filter((d) => d.created_by?.uuid === filters.createdBy)
+ const createdByIds = filters.createdBy
+ haystack = haystack.filter((d) => d.created_by != null && createdByIds.includes(d.created_by.id))
}
if (filters.tags && filters.tags.length > 0) {
haystack = haystack.filter((d) => filters.tags?.some((tag) => d.tags?.includes(tag)))
@@ -273,39 +274,85 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
},
setFilters: () => {
- // Persist the folder filter so it survives reloads/sharing. `null` means no filter (param absent);
- // an empty string is a valid value (project root), so we key off the param's presence, not its value.
- const folder = values.filters.folder ?? null
- const hadFolder = 'folder' in router.values.searchParams
- const currentFolder = hadFolder ? urlSearchParamToString(router.values.searchParams['folder']) : null
+ const { createdBy, pinned, shared, tags } = values.filters
+ const searchParams: Record<string, any> = { ...router.values.searchParams }
- if (folder === currentFolder) {
- return
+ if (createdBy !== DEFAULT_FILTERS.createdBy) {
+ searchParams['created_by'] = createdBy
+ } else {
+ delete searchParams['created_by']
}
-
- const searchParams: Record<string, any> = {
- ...router.values.searchParams,
+ if (pinned) {
+ searchParams['pinned'] = true
+ } else {
+ delete searchParams['pinned']
+ }
+ if (shared) {
+ searchParams['shared'] = true
+ } else {
+ delete searchParams['shared']
+ }
+ if (tags && tags.length > 0) {
+ searchParams['tags'] = tags
+ } else {
+ delete searchParams['tags']
}
+ // Persist the folder filter so it survives reloads/sharing. `null` means no filter (param absent);
+ // an empty string is a valid value (project root), so we key off the param's presence, not its value.
+ const folder = values.filters.folder ?? null
if (folder === null) {
delete searchParams['folder']
} else {
searchParams['folder'] = folder
}
+ if (objectsEqual(searchParams, router.values.searchParams)) {
+ return
+ }
+
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
},
})),
- urlToAction(({ actions }) => ({
+ urlToAction(({ actions, values }) => ({
'/dashboard': (_, searchParams) => {
const tab = (searchParams['tab'] as DashboardsTab | undefined) || DashboardsTab.All
- actions.setCurrentTab(tab)
+ if (values.currentTab !== tab) {
+ actions.setCurrentTab(tab)
+ }
- const search = urlSearchParamToString(searchParams['search'])
- actions.setSearch(search)
+ // 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
+ // (e.g. a redundant server search) for filters that didn't actually move.
+ const createdByParam = searchParams['created_by']
+ const createdByIds = Array.isArray(createdByParam)
+ ? createdByParam.map(Number).filter((id) => !Number.isNaN(id))
+ : typeof createdByParam === 'number'
+ ? [createdByParam]
+ : []
+ const nextFilters = {
+ createdBy: createdByIds.length > 0 ? createdByIds : DEFAULT_FILTERS.createdBy,
+ pinned: searchParams['pinned'] === true || searchParams['pinned'] === 'true',
+ shared: searchParams['shared'] === true || searchParams['shared'] === 'true',
+ tags: Array.isArray(searchParams['tags']) ? searchParams['tags'] : DEFAULT_FILTERS.tags,
+ folder: 'folder' in searchParams ? urlSearchParamToString(searchParams['folder']) : null,
+ }
+ const current = values.filters
+ if (
+ !objectsEqual(current.createdBy, nextFilters.createdBy) ||
+ current.pinned !== nextFilters.pinned ||
+ current.shared !== nextFilters.shared ||
+ !objectsEqual(current.tags ?? [], nextFilters.tags ?? []) ||
+ (current.folder ?? null) !== nextFilters.folder
+ ) {
+ actions.setFilters(nextFilters)
+ }
- const folder = 'folder' in searchParams ? urlSearchParamToString(searchParams['folder']) : null
- actions.setFilters({ folder })
+ const search = urlSearchParamToString(searchParams['search'])
+ if (values.filters.search !== search) {
+ actions.setSearch(search)
+ }
},
})),
listeners(({ actions, values }) => ({
diff --git a/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx b/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
index b95089d33416..1d3b455a775a 100644
--- a/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
@@ -1,9 +1,8 @@
-import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
import { IconFlag, IconHeart, IconHeartFilled } from '@posthog/icons'
-import { LemonDropdown, ProfilePicture } from '@posthog/lemon-ui'
+import { MemberSelectMultiplePopover } from 'lib/components/MemberSelectMultiplePopover'
import { TagSelect } from 'lib/components/TagSelect'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
@@ -11,8 +10,6 @@ import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { cn } from 'lib/utils/css-classes'
-import { fullName } from 'lib/utils/strings'
-import { membersLogic } from 'scenes/organization/membersLogic'
import { INSIGHT_TYPE_OPTIONS } from 'scenes/saved-insights/SavedInsights'
import { SavedInsightFilters } from 'scenes/saved-insights/savedInsightsLogic'
@@ -32,28 +29,8 @@ export function SavedInsightsFilters({
borderless?: boolean
}): JSX.Element {
const { search, hideFeatureFlagInsights, favorited, tags, insightType, createdBy } = filters
- const { meFirstMembers, filteredMembers, membersLoading, search: memberSearch } = useValues(membersLogic)
- const { setSearch: setMemberSearch, ensureAllMembersLoaded } = useActions(membersLogic)
const quickFilterSet = new Set(quickFilters)
const hasInsightTypeSelection = !!insightType && insightType !== 'All types'
- const hasCreatedBySelection = createdBy !== 'All users' && (createdBy as number[]).length > 0
- const currentUserId = meFirstMembers[0]?.user.id
- const isFilteredToCurrentUser =
- hasCreatedBySelection && (createdBy as number[]).length === 1 && (createdBy as number[])[0] === currentUserId
-
- const handleMemberToggle = (userId: number): void => {
- const currentUsers = createdBy !== 'All users' ? (createdBy as number[]) : []
- const selected = new Set(currentUsers)
- if (selected.has(userId)) {
- selected.delete(userId)
- } else {
- selected.add(userId)
- }
- const newValue = Array.from(selected)
- const createdByValue = newValue.length > 0 ? newValue : 'All users'
- setFilters({ createdBy: createdByValue })
- posthog.capture('saved insights filtered', { filter_type: 'created_by', value: createdByValue })
- }
return (
<div className={cn('flex justify-between gap-2 items-center flex-wrap')}>
@@ -102,99 +79,18 @@ export function SavedInsightsFilters({
</TagSelect>
)}
{quickFilterSet.has('createdBy') && (
- <LemonDropdown
- closeOnClickInside={false}
- matchWidth={false}
- placement="bottom-end"
- actionable
- onVisibilityChange={(visible) => {
- if (visible) {
- ensureAllMembersLoaded()
- setMemberSearch('')
- }
+ <MemberSelectMultiplePopover
+ value={createdBy !== 'All users' ? (createdBy as number[]) : []}
+ onChange={(ids) => {
+ const createdByValue = ids.length > 0 ? ids : 'All users'
+ setFilters({ createdBy: createdByValue })
+ posthog.capture('saved insights filtered', {
+ filter_type: 'created_by',
+ value: createdByValue,
+ })
}}
- overlay={
- <div className="max-w-100 deprecated-space-y-2">
- <LemonInput
- type="search"
- placeholder="Search"
- autoFocus
- value={memberSearch}
- onChange={setMemberSearch}
- fullWidth
- />
- <ul className="deprecated-space-y-px">
- {filteredMembers.map((member) => (
- <li key={member.user.uuid}>
- <LemonButton
- fullWidth
- role="menuitem"
- size="small"
- icon={<ProfilePicture size="md" user={member.user} />}
- onClick={() => handleMemberToggle(member.user.id)}
- >
- <span className="flex items-center justify-between gap-2 flex-1">
- <span className="flex items-center gap-2 max-w-full">
- <input
- type="checkbox"
- className="cursor-pointer"
- checked={
- createdBy !== 'All users' &&
- (createdBy as number[]).includes(member.user.id)
- }
- readOnly
- />
- <span>{fullName(member.user)}</span>
- </span>
- <span className="text-secondary">
- {meFirstMembers[0] === member && `(you)`}
- </span>
- </span>
- </LemonButton>
- </li>
- ))}
- {membersLoading ? (
- <div className="p-2 text-secondary italic truncate border-t">
- Loading...
- </div>
- ) : filteredMembers.length === 0 ? (
- <div className="p-2 text-secondary italic truncate border-t">
- {memberSearch ? <span>No matches</span> : <span>No users</span>}
- </div>
- ) : null}
- {hasCreatedBySelection && (
- <>
- <div className="my-1 border-t" />
- <li>
- <LemonButton
- fullWidth
- role="menuitem"
- size="small"
- onClick={() => setFilters({ createdBy: 'All users' })}
- type="tertiary"
- >
- Clear selection
- </LemonButton>
- </li>
- </>
- )}
- </ul>
- </div>
- }
- >
- <LemonButton
- size="small"
- type="secondary"
- status={borderless && !hasCreatedBySelection ? 'alt' : 'default'}
- active={hasCreatedBySelection}
- >
- {isFilteredToCurrentUser
- ? 'Created by you'
- : hasCreatedBySelection
- ? `Created by (${(createdBy as number[]).length})`
- : 'Created by'}
- </LemonButton>
- </LemonDropdown>
+ borderless={borderless}
+ />
)}
{quickFilterSet.has('favorites') && (
<LemonButton