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.

perf(insights): lazy load tag filter options (#101779)

Matt Puacf4b4fb16b05
diff --git a/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx b/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx
index d056b1ab7198..01ac168675a6 100644
--- a/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx
@@ -121,6 +121,20 @@ describe('SavedInsightsFilters Created by dropdown', () => {
})
})
+ it('shows tag skeletons while tags load', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/tags/': () => new Promise(() => {}),
+ },
+ })
+ renderFilters()
+ await userEvent.click(screen.getByText('Tags'))
+
+ await waitFor(() => {
+ expect(screen.getAllByText('Loading…')).toHaveLength(5)
+ })
+ })
+
it('toggles member selection and calls setFilters', async () => {
renderFilters()
await userEvent.click(screen.getByText('Created by'))
diff --git a/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx b/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
index 1d3b455a775a..897359f88d2c 100644
--- a/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx
@@ -3,7 +3,6 @@ import posthog from 'posthog-js'
import { IconFlag, IconHeart, IconHeartFilled } from '@posthog/icons'
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'
import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
@@ -13,6 +12,8 @@ import { cn } from 'lib/utils/css-classes'
import { INSIGHT_TYPE_OPTIONS } from 'scenes/saved-insights/SavedInsights'
import { SavedInsightFilters } from 'scenes/saved-insights/savedInsightsLogic'
+import { SavedInsightsTagSelect } from './SavedInsightsTagSelect'
+
export type QuickFilterKind = 'insightType' | 'tags' | 'createdBy' | 'favorites' | 'featureFlags'
const ALL_QUICK_FILTERS: QuickFilterKind[] = ['insightType', 'tags', 'createdBy', 'favorites', 'featureFlags']
@@ -59,24 +60,14 @@ export function SavedInsightsFilters({
/>
)}
{quickFilterSet.has('tags') && (
- <TagSelect
+ <SavedInsightsTagSelect
value={tags || []}
+ borderless={borderless}
onChange={(tags) => {
setFilters({ tags: tags.length > 0 ? tags : [] })
posthog.capture('saved insights filtered', { filter_type: 'tags', value: tags })
}}
- >
- {(selectedTags) => (
- <LemonButton
- size="small"
- type="secondary"
- active={selectedTags.length > 0}
- status={borderless && selectedTags.length === 0 ? 'alt' : 'default'}
- >
- {selectedTags.length > 0 ? `Tags (${selectedTags.length})` : 'Tags'}
- </LemonButton>
- )}
- </TagSelect>
+ />
)}
{quickFilterSet.has('createdBy') && (
<MemberSelectMultiplePopover
diff --git a/frontend/src/scenes/saved-insights/SavedInsightsTagSelect.tsx b/frontend/src/scenes/saved-insights/SavedInsightsTagSelect.tsx
new file mode 100644
index 000000000000..dce535b9c28b
--- /dev/null
+++ b/frontend/src/scenes/saved-insights/SavedInsightsTagSelect.tsx
@@ -0,0 +1,131 @@
+import { useActions, useValues } from 'kea'
+import { useId } from 'react'
+
+import { LemonButton, LemonDropdown, LemonInput } from '@posthog/lemon-ui'
+
+import { useScrollObserver } from 'lib/hooks/useScrollObserver'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+
+import { savedInsightsTagFilterLogic } from './savedInsightsTagFilterLogic'
+
+export function SavedInsightsTagSelect({
+ value,
+ onChange,
+ borderless = false,
+}: {
+ value: string[]
+ onChange: (value: string[]) => void
+ borderless?: boolean
+}): JSX.Element {
+ const fallbackKey = useId()
+ const logic = savedInsightsTagFilterLogic({ logicKey: fallbackKey })
+ const { tagPageError, tagPageLoading, tagResults, tagSearch } = useValues(logic)
+ const { loadMoreTagResults, retryTagResults, setTagPopoverOpen, setTagSearch } = useActions(logic)
+ const tagListScrollRef = useScrollObserver({ onScrollBottom: loadMoreTagResults })
+ const displayedTags = Array.from(new Set([...value, ...tagResults]))
+
+ const handleTagToggle = (tag: string): void => {
+ const selected = new Set(value)
+ if (selected.has(tag)) {
+ selected.delete(tag)
+ } else {
+ selected.add(tag)
+ }
+ onChange(Array.from(selected))
+ }
+
+ return (
+ <LemonDropdown
+ closeOnClickInside={false}
+ matchWidth={false}
+ actionable
+ onVisibilityChange={setTagPopoverOpen}
+ overlay={
+ <div className="max-w-100 deprecated-space-y-2">
+ <LemonInput
+ type="search"
+ placeholder="Search tags"
+ autoFocus
+ value={tagSearch}
+ onChange={setTagSearch}
+ fullWidth
+ className="max-w-full"
+ />
+ <div
+ ref={tagListScrollRef}
+ className="max-h-80 overflow-y-auto"
+ data-attr="saved-insights-tags-list"
+ >
+ <ul className="deprecated-space-y-px">
+ {displayedTags.map((tag) => (
+ <li key={tag}>
+ <LemonButton
+ fullWidth
+ role="menuitem"
+ size="small"
+ onClick={() => handleTagToggle(tag)}
+ >
+ <span className="flex items-center gap-2 max-w-full">
+ <input
+ type="checkbox"
+ className="cursor-pointer"
+ checked={value.includes(tag)}
+ readOnly
+ />
+ <span>{tag}</span>
+ </span>
+ </LemonButton>
+ </li>
+ ))}
+ {!tagPageLoading && !tagPageError && tagResults.length === 0 ? (
+ <li className="p-2 text-secondary italic truncate border-t">
+ {tagSearch ? 'No matching tags' : 'No tags'}
+ </li>
+ ) : null}
+ {tagPageLoading ? (
+ <li className="p-1" aria-label="Loading tags">
+ <LemonSkeleton.Row
+ className="h-8 mb-1"
+ repeat={tagResults.length === 0 ? 5 : 2}
+ fade
+ />
+ </li>
+ ) : null}
+ </ul>
+ </div>
+ {tagPageError && (
+ <LemonButton
+ fullWidth
+ size="small"
+ type="secondary"
+ loading={tagPageLoading}
+ onClick={retryTagResults}
+ >
+ Couldn't load tags. Try again.
+ </LemonButton>
+ )}
+ {value.length > 0 && (
+ <LemonButton
+ fullWidth
+ role="menuitem"
+ size="small"
+ onClick={() => onChange([])}
+ type="secondary"
+ >
+ Clear selection
+ </LemonButton>
+ )}
+ </div>
+ }
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ active={value.length > 0}
+ status={borderless && value.length === 0 ? 'alt' : 'default'}
+ >
+ {value.length > 0 ? `Tags (${value.length})` : 'Tags'}
+ </LemonButton>
+ </LemonDropdown>
+ )
+}
diff --git a/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.test.ts b/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.test.ts
new file mode 100644
index 000000000000..d6f96ff3a6d9
--- /dev/null
+++ b/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.test.ts
@@ -0,0 +1,41 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { savedInsightsTagFilterLogic } from './savedInsightsTagFilterLogic'
+
+describe('savedInsightsTagFilterLogic', () => {
+ it('replaces the first tag page and appends the next one', async () => {
+ initKeaTests()
+ const logic = savedInsightsTagFilterLogic({ logicKey: 'test' })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.loadTagResultsSuccess(
+ { next: 'next-page', previous: null, results: ['alpha', 'beta'] },
+ { search: '', offset: 0 }
+ )
+ }).toMatchValues({ hasMoreTagResults: true, tagResults: ['alpha', 'beta'] })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadTagResultsSuccess(
+ { next: null, previous: 'previous-page', results: ['gamma'] },
+ { search: '', offset: 2 }
+ )
+ }).toMatchValues({ hasMoreTagResults: false, tagResults: ['alpha', 'beta', 'gamma'] })
+ })
+
+ it('keeps loaded tags and exposes a failed page for retry', async () => {
+ initKeaTests()
+ const logic = savedInsightsTagFilterLogic({ logicKey: 'failure' })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.loadTagResultsSuccess(
+ { next: 'next-page', previous: null, results: ['alpha'] },
+ { search: '', offset: 0 }
+ )
+ logic.actions.loadTagResultsFailure('Unable to load tags')
+ }).toMatchValues({ tagPageError: 'Unable to load tags', tagResults: ['alpha'] })
+ })
+})
diff --git a/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.ts
new file mode 100644
index 000000000000..f2e5d5521ad2
--- /dev/null
+++ b/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.ts
@@ -0,0 +1,162 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api, { PaginatedResponse } from 'lib/api'
+import { teamLogic } from 'scenes/teamLogic'
+
+const TAGS_PER_PAGE = 50
+
+export interface SavedInsightsTagFilterLogicProps {
+ logicKey: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface savedInsightsTagFilterLogicValues {
+ currentTeamId: number | null // teamLogic
+ hasMoreTagResults: boolean
+ tagPage: PaginatedResponse<string> | null
+ tagPageError: string | null
+ tagPageLoading: boolean
+ tagResults: string[]
+ tagSearch: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface savedInsightsTagFilterLogicActions {
+ loadMoreTagResults: () => {
+ value: true
+ }
+ loadTagResults: ({ search, offset }: { offset: number; search: string }) => {
+ search: string
+ offset: number
+ }
+ loadTagResultsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTagResultsSuccess: (
+ tagPage: PaginatedResponse<string>,
+ payload?: {
+ search: string
+ offset: number
+ }
+ ) => {
+ tagPage: PaginatedResponse<string>
+ payload?: {
+ search: string
+ offset: number
+ }
+ }
+ retryTagResults: () => {
+ value: true
+ }
+ setTagPopoverOpen: (open: boolean) => {
+ open: boolean
+ }
+ setTagSearch: (search: string) => {
+ search: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface savedInsightsTagFilterLogicMeta {
+ key: string
+}
+
+export type savedInsightsTagFilterLogicType = MakeLogicType<
+ savedInsightsTagFilterLogicValues,
+ savedInsightsTagFilterLogicActions,
+ SavedInsightsTagFilterLogicProps,
+ savedInsightsTagFilterLogicMeta
+>
+
+export const savedInsightsTagFilterLogic = kea<savedInsightsTagFilterLogicType>([
+ props({} as SavedInsightsTagFilterLogicProps),
+ key((props) => props.logicKey),
+ path((logicKey) => ['scenes', 'saved-insights', 'savedInsightsTagFilterLogic', logicKey]),
+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
+ actions({
+ loadMoreTagResults: true,
+ retryTagResults: true,
+ setTagSearch: (search: string) => ({ search }),
+ setTagPopoverOpen: (open: boolean) => ({ open }),
+ }),
+ loaders(({ values }) => ({
+ tagPage: [
+ null as PaginatedResponse<string> | null,
+ {
+ loadTagResults: async ({ search, offset }: { search: string; offset: number }, breakpoint) => {
+ if (offset === 0) {
+ await breakpoint(250)
+ }
+ if (values.currentTeamId == null) {
+ return { results: [], next: null }
+ }
+ const params = new URLSearchParams({ search, limit: String(TAGS_PER_PAGE), offset: String(offset) })
+ const tagPage: PaginatedResponse<string> = await api.get(
+ `api/projects/${values.currentTeamId}/tags?${params.toString()}`
+ )
+ breakpoint()
+ return tagPage
+ },
+ },
+ ],
+ })),
+ reducers({
+ tagSearch: [
+ '',
+ {
+ setTagSearch: (_, { search }) => search,
+ setTagPopoverOpen: (state, { open }) => (open ? state : ''),
+ },
+ ],
+ tagResults: [
+ [] as string[],
+ {
+ setTagSearch: () => [],
+ setTagPopoverOpen: (state, { open }) => (open ? [] : state),
+ loadTagResultsSuccess: (state, { tagPage, payload }) =>
+ payload?.offset === 0 ? (tagPage.results ?? []) : [...state, ...(tagPage.results ?? [])],
+ },
+ ],
+ hasMoreTagResults: [
+ false,
+ {
+ setTagSearch: () => false,
+ setTagPopoverOpen: (_, { open }) => open,
+ loadTagResultsSuccess: (_, { tagPage }) => tagPage.next != null,
+ },
+ ],
+ tagPageError: [
+ null as string | null,
+ {
+ setTagSearch: () => null,
+ setTagPopoverOpen: () => null,
+ loadTagResultsSuccess: () => null,
+ retryTagResults: () => null,
+ loadTagResultsFailure: (_, { error }) => error,
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ setTagPopoverOpen: ({ open }) => {
+ if (open) {
+ actions.loadTagResults({ search: '', offset: 0 })
+ }
+ },
+ setTagSearch: ({ search }) => {
+ actions.loadTagResults({ search, offset: 0 })
+ },
+ loadMoreTagResults: () => {
+ if (values.hasMoreTagResults && !values.tagPageLoading) {
+ actions.loadTagResults({ search: values.tagSearch, offset: values.tagResults.length })
+ }
+ },
+ retryTagResults: () => {
+ actions.loadTagResults({ search: values.tagSearch, offset: values.tagResults.length })
+ },
+ })),
+])