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(taxonomic-filter): reveal results before expansion counts (#95609)

Paul D'Ambra30965c4c6298
diff --git a/docs/internal/taxonomic-filter-search.md b/docs/internal/taxonomic-filter-search.md
new file mode 100644
index 000000000000..806b969c04da
--- /dev/null
+++ b/docs/internal/taxonomic-filter-search.md
@@ -0,0 +1,11 @@
+# Taxonomic filter search loading
+
+The legacy picker and the rebuilt menu hold aggregated search results until the contributing categories settle. This prevents late category results from moving a choice under the pointer. Only categories offered by the picker contribute to that wait; a category-specific list waits for its own results. Recent and Pinned scopes use pre-resolved entries and never enter this search loading barrier.
+
+A category shows results for the current query only. It clears its earlier rows when the current query cannot fetch, such as a query below the category minimum length or a request that failed.
+
+Scoped property searches return properties associated with the selected events. A separate unscoped request counts matches across the project so the picker can offer an expansion to other properties.
+
+The expansion count must not delay the scoped results or keep the aggregate reveal barrier closed. It can add an expansion option below the results after they appear. A failed count leaves the scoped results usable, and a count from an earlier search must not affect the current search. Expanding explicitly starts a full-results request and uses the normal list loading state.
+
+The legacy implementation separates these requests in `infiniteListLogic.ts`; the rebuilt implementation uses independent resources in `hooks/useGroupList.ts`. Keep this behavior consistent across both implementations.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a1f425698114..b4b8584cae4a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2800,6 +2800,10 @@ snapshots:
hash: v1.k794b7964.6720b50c7ba8f3918a8c142a86467b7a910a5c6f0d88d49ca8042afbf628877e.I5xU7-YqIfvND-ac2n3lc_kN5TEraGL5oLW-VNPkmcI
filters-taxonomic-filter--six-groups-default-layout--light:
hash: v1.k794b7964.2b35cab321e44ea92319f32ba472e98060a16f33a9f78add392558f355fa65f8.WVEXHn1UNrYtkOhxbuTA_AXUp8EZZMeUuxb9nSgBLxg
+ filters-taxonomic-filter--slow-expansion-count--dark:
+ hash: v1.k794b7964.f8bab5e9a170682fbaad198c797d11f9bf4b8ad0c963d15284e275a8288c3103.NBrTJPSNHo80dbma7MGbu1AXsJpkb03Mx-MwAk5DLzU
+ filters-taxonomic-filter--slow-expansion-count--light:
+ hash: v1.k794b7964.949427396f7f328e1312778ebc41c332f662f9b04a3eb767fb626c309f59fd3c.dFGW6CBI5dxi8Lrebe7-Y-z29RGsX7NnmRc16RyJJIM
filters-taxonomic-filter--suggested-filters-five-recents-with-truncation--dark:
hash: v1.k794b7964.40e8f6390fa4df285ef22407eb2e6d3fc8be46ad51c70969d8e7df72292e26db.QbM8TTsW3Nntp4SpQl2u4XLYhVdO6Gr2d0VX84f-qt4
filters-taxonomic-filter--suggested-filters-five-recents-with-truncation--light:
diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
index 9675e9729a52..9642e8b2c39e 100644
--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
@@ -2,6 +2,7 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { Meta, StoryObj } from '@storybook/react'
import { useActions, useMountedLogic } from 'kea'
+import { delay } from 'msw'
import { useEffect } from 'react'
import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__mocks__/taxonomicFilterMocksDecorator'
@@ -167,6 +168,39 @@ export const Properties: Story = {
},
}
+export const SlowExpansionCount: Story = {
+ render: Properties.render,
+ args: {
+ taxonomicFilterLogicKey: 'slow-expansion-count',
+ taxonomicGroupTypes: [TaxonomicFilterGroupType.EventProperties],
+ eventNames: ['page_opened'],
+ initialSearchQuery: 'name',
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/property_definitions': async ({ request }) => {
+ const params = new URL(request.url).searchParams
+ const scoped = params.has('filter_by_event_names')
+ const results = [{ id: 'page_name', name: 'page_name' }].filter((item) =>
+ item.name.includes(params.get('search') ?? '')
+ )
+ await delay(scoped ? 100 : 8000)
+ return { results, count: scoped ? results.length : 9 }
+ },
+ },
+ }),
+ ],
+ parameters: {
+ testOptions: { waitForSelector: '[data-attr="prop-filter-event_properties-0"]' },
+ docs: {
+ description: {
+ story: 'Scoped results appear while the full count is still loading. The expansion option arrives below them after eight seconds.',
+ },
+ },
+ },
+}
+
export const NumericalProperties: Story = {
render: (args) => {
return (
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts
index bd2936038525..999f91da7fe5 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts
@@ -76,12 +76,7 @@ export async function fetchTaxonomicListPage({
const useScoped = group.scopedEndpoint && !isExpanded
const primaryUrl = useScoped ? group.scopedEndpoint! : remoteEndpoint
- const [primary, expandedCount] = await Promise.all([
- api.get(combineUrl(primaryUrl, baseParams).url, { signal }),
- useScoped
- ? api.get(combineUrl(remoteEndpoint, { ...baseParams, limit: 1, offset: 0 }).url, { signal })
- : Promise.resolve(null),
- ])
+ const primary = await api.get(combineUrl(primaryUrl, baseParams).url, { signal })
const results = primary?.results ?? primary ?? []
const count = primary?.count ?? (Array.isArray(primary) ? primary.length : results.length)
@@ -90,6 +85,5 @@ export async function fetchTaxonomicListPage({
results,
searchQuery,
count,
- expandedCount: expandedCount?.count,
}
}
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx
index 54a874f70430..99ba106be7dd 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx
@@ -156,6 +156,38 @@ describe('useGroupList', () => {
expect(apiGet).not.toHaveBeenCalled()
})
+ it('drops the previous page when the query falls below the minimum length', async () => {
+ apiGet.mockResolvedValue({ results: [{ name: 'checkout' }], count: 1 })
+ const group = makeGroup({ endpoint: 'api/projects/1/whatever', minSearchQueryLength: 3 })
+ const { result, rerender } = renderHook(({ q }: { q: string }) => useGroupList({ group, searchQuery: q }), {
+ initialProps: { q: 'checkout' },
+ })
+ await waitFor(() => expect(result.current.items).toEqual([{ name: 'checkout' }]))
+
+ rerender({ q: 'ch' })
+
+ // Nothing fetches below the minimum, so the longer query's rows must go —
+ // otherwise they read as matches for what is on screen now.
+ expect(result.current.items).toEqual([])
+ expect(result.current.needsMoreSearchCharacters).toBe(true)
+ })
+
+ it('drops the previous page when the request for the current query fails', async () => {
+ apiGet
+ .mockResolvedValueOnce({ results: [{ name: 'alpha' }], count: 1 })
+ .mockRejectedValueOnce(new Error('search unavailable'))
+ const group = makeGroup({ endpoint: 'api/projects/1/event_definitions' })
+ const { result, rerender } = renderHook(({ q }: { q: string }) => useGroupList({ group, searchQuery: q }), {
+ initialProps: { q: 'alpha' },
+ })
+ await waitFor(() => expect(result.current.items).toEqual([{ name: 'alpha' }]))
+
+ rerender({ q: 'beta' })
+
+ await waitFor(() => expect(result.current.items).toEqual([]))
+ expect(result.current.isLoading).toBe(false)
+ })
+
it('refires when searchQuery changes', async () => {
apiGet
.mockResolvedValueOnce({ results: [{ name: 'a' }], count: 1 })
@@ -170,20 +202,64 @@ describe('useGroupList', () => {
expect(apiGet).toHaveBeenCalledTimes(2)
})
- it('exposes expandable state when scoped + expandedCount > count', async () => {
+ it.each(['success', 'failure'] as const)(
+ 'reveals scoped results before the full count settles with %s',
+ async (outcome) => {
+ let resolveCount!: (value: { count: number }) => void
+ let rejectCount!: (error: Error) => void
+ const countRequest = new Promise((resolve, reject) => {
+ resolveCount = resolve
+ rejectCount = reject
+ })
+ apiGet.mockResolvedValueOnce({ results: [{ name: 's' }], count: 1 }).mockReturnValueOnce(countRequest)
+ const group = makeGroup({
+ endpoint: 'api/projects/1/property_definitions',
+ scopedEndpoint: 'api/projects/1/property_definitions?scoped',
+ })
+ const { result } = renderHook(() => useGroupList({ group, searchQuery: '' }))
+ await waitFor(() => expect(result.current.totalResultCount).toBe(1))
+ expect(result.current.isLoading).toBe(false)
+ expect(result.current.isFetching).toBe(false)
+ expect(result.current.isExpandable).toBe(false)
+ expect(result.current.rowCount).toBe(1)
+ const visibleItems = result.current.items
+ await act(async () => {
+ if (outcome === 'success') {
+ resolveCount({ count: 9 })
+ } else {
+ rejectCount(new Error('count unavailable'))
+ }
+ })
+ expect(result.current.items).toEqual(visibleItems)
+ expect(result.current.isExpandable).toBe(outcome === 'success')
+ expect(result.current.rowCount).toBe(outcome === 'success' ? 2 : 1)
+ }
+ )
+
+ it('ignores a full count from an earlier search', async () => {
+ let resolveOldCount!: (value: { count: number }) => void
apiGet
- // primary scoped fetch
- .mockResolvedValueOnce({ results: [{ name: 's' }], count: 1 })
- // extra full count fetch
- .mockResolvedValueOnce({ count: 9 })
+ .mockResolvedValueOnce({ results: [{ name: 'alpha' }], count: 1 })
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveOldCount = resolve
+ })
+ )
+ .mockResolvedValueOnce({ results: [{ name: 'beta' }], count: 1 })
+ .mockResolvedValueOnce({ count: 1 })
const group = makeGroup({
endpoint: 'api/projects/1/property_definitions',
scopedEndpoint: 'api/projects/1/property_definitions?scoped',
})
- const { result } = renderHook(() => useGroupList({ group, searchQuery: '' }))
- await waitFor(() => expect(result.current.totalResultCount).toBe(1))
- expect(result.current.isExpandable).toBe(true)
- expect(result.current.rowCount).toBe(2) // results + expand button
+ const { result, rerender } = renderHook(({ q }) => useGroupList({ group, searchQuery: q }), {
+ initialProps: { q: 'alpha' },
+ })
+ await waitFor(() => expect(result.current.items).toEqual([{ name: 'alpha' }]))
+ rerender({ q: 'beta' })
+ await waitFor(() => expect(result.current.items).toEqual([{ name: 'beta' }]))
+ await act(async () => resolveOldCount({ count: 9 }))
+ expect(result.current.isExpandable).toBe(false)
+ expect(result.current.rowCount).toBe(1)
})
it('expand() switches to the unscoped endpoint and refetches', async () => {
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
index 312fdb313dfb..17e6f0add197 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
@@ -277,7 +277,11 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
}
)
- const remoteItemsRaw: ListStorage = remote.data ?? EMPTY_LIST_STORAGE
+ // A previous page must not stand in for the current query: below the group's minimum
+ // search length nothing fetches, and a failed request has no rows, so `keepPreviousData`
+ // would show the earlier query's rows as matches for what is typed now. Aborts are not
+ // errors, so a keystroke still shows the previous page until the next one lands.
+ const remoteItemsRaw: ListStorage = (remoteEnabled && !remote.error ? remote.data : undefined) ?? EMPTY_LIST_STORAGE
// A `clientFilterFirstPage` group can only fuse what it cached — the
// empty-search first page. When the server holds more rows than fit on
@@ -336,6 +340,28 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
{ enabled: serverSearchEnabled, staleTime: 60_000, keepPreviousData: true }
)
+ // The full count only adds an expand row below the results, so it must not hold the reveal barrier.
+ const expandedCount = useTaxonomicResource<ListStorage>(
+ [...(serverSearchEnabled ? serverSearchKey : remoteKey), 'expanded-count'],
+ ({ signal }) =>
+ fetchTaxonomicListPage({
+ group,
+ searchQuery: serverSearchEnabled ? trimmedSearch : remoteSearchQuery,
+ offset: 0,
+ limit: 1,
+ isExpanded: true,
+ showNumericalPropsOnly,
+ hideBehavioralCohorts,
+ excludeStale,
+ signal,
+ }),
+ {
+ enabled: remoteEnabled && !!group.scopedEndpoint && !isExpanded,
+ staleTime: clientFilter ? 5 * 60_000 : 60_000,
+ keepPreviousData: false,
+ }
+ )
+
// Per-fetch Fuse index over the cached first page. Built lazily on
// first non-empty query, then re-used across keystrokes until the
// page changes (refetch / invalidate).
@@ -358,14 +384,23 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
// Dataset bigger than one page: the server search is authoritative.
// Show the local fuse of the cached first page until it resolves so
// there's no blank flash, then swap in the full server result.
- if (serverSearchEnabled && serverSearch.data) {
+ if (serverSearchEnabled && !serverSearch.error && serverSearch.data) {
return serverSearch.data
}
const filtered = remoteFuse
? (remoteFuse.search(trimmedSearch).map((r: any) => r.item.item) as TaxonomicDefinitionTypes[])
: []
return { results: filtered, searchQuery, count: filtered.length }
- }, [clientFilter, trimmedSearch, remoteItemsRaw, remoteFuse, searchQuery, serverSearchEnabled, serverSearch.data])
+ }, [
+ clientFilter,
+ trimmedSearch,
+ remoteItemsRaw,
+ remoteFuse,
+ searchQuery,
+ serverSearchEnabled,
+ serverSearch.data,
+ serverSearch.error,
+ ])
// ---- Combined items + keyword shortcuts --------------------------------
const keywordShortcuts: QuickFilterItem[] = useMemo(() => {
@@ -411,8 +446,9 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
const isExpandable = !!(
group.endpoint &&
group.scopedEndpoint &&
- remoteItems.expandedCount &&
- remoteItems.expandedCount > remoteItems.count
+ !isExpanded &&
+ expandedCount.data &&
+ expandedCount.data.count > remoteItems.count
)
// Match legacy semantics: `count` is the API-reported total + local pool
// size + keyword shortcuts, NOT the loaded array length. Without this,
@@ -503,6 +539,9 @@ export function useGroupList(input: UseGroupListInput): UseGroupListResult {
expand,
refetch: () => {
remote.refetch()
+ if (remoteEnabled && group.scopedEndpoint && !isExpanded) {
+ expandedCount.refetch()
+ }
},
}
}
diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
index 2ebce5d73c01..6af77dd5c95e 100644
--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
@@ -1101,6 +1101,45 @@ describe('infiniteListLogic', () => {
logic.mount()
})
+ it.each([200, 500])('reveals scoped results before the full count returns %s', async (status) => {
+ let resolveCount!: (response: [number, { count: number; results: { name: string }[] }]) => void
+ useMocks({
+ get: {
+ '/api/projects/:team/property_definitions': ({ request }) => {
+ const url = new URL(request.url)
+ if (
+ url.searchParams.get('search') === 'browser' &&
+ !url.searchParams.has('filter_by_event_names')
+ ) {
+ return new Promise((resolve) => {
+ resolveCount = resolve
+ })
+ }
+ return [200, { results: [{ name: '$browser', id: 'browser' }], count: 1 }]
+ },
+ },
+ })
+ await expectLogic(logic, () => logic.actions.setSearchQuery('browser'))
+ .toDispatchActions(['loadRemoteItemsSuccess'])
+ .toMatchValues({
+ remoteItems: partial({ searchQuery: 'browser', count: 1 }),
+ isLoading: false,
+ isExpandable: false,
+ expandedCountResultLoading: true,
+ })
+ const visibleResults = logic.values.results
+ const selectedIndex = logic.values.index
+ await expectLogic(logic, () => resolveCount([status, { count: 9, results: [{ name: '$browser' }] }]))
+ .toDispatchActions(['loadExpandedCountSuccess'])
+ .toMatchValues({
+ isLoading: false,
+ isExpandable: status === 200,
+ expandedCount: status === 200 ? 9 : 0,
+ results: visibleResults,
+ index: selectedIndex,
+ })
+ })
+
it('setting search query filters events', async () => {
await expectLogic(logic, () => {
logic.actions.setSearchQuery('browser')
@@ -1117,7 +1156,6 @@ describe('infiniteListLogic', () => {
expandedCount: 2,
remoteItems: partial({
count: 1,
- expandedCount: 2,
results: partial([partial({ name: '$browser', is_seen_on_filtered_events: true })]),
}),
})
@@ -1137,7 +1175,6 @@ describe('infiniteListLogic', () => {
expandedCount: 0,
remoteItems: partial({
count: 2,
- expandedCount: undefined,
results: partial([
partial({ name: '$browser', is_seen_on_filtered_events: true }),
partial({ name: 'browser_no_dollar_not_on_event', is_seen_on_filtered_events: false }),
@@ -1161,7 +1198,6 @@ describe('infiniteListLogic', () => {
expandedCount: 0,
remoteItems: partial({
count: 2,
- expandedCount: undefined,
results: partial([
partial({ name: '$browser', is_seen_on_filtered_events: true }),
partial({ name: 'browser_no_dollar_not_on_event', is_seen_on_filtered_events: false }),
@@ -1187,7 +1223,6 @@ describe('infiniteListLogic', () => {
index: 0,
remoteItems: partial({
count: 1,
- expandedCount: 2,
results: partial([partial({ name: '$browser', is_seen_on_filtered_events: true })]),
}),
})
@@ -1211,7 +1246,6 @@ describe('infiniteListLogic', () => {
expandedCount: 0,
remoteItems: partial({
count: 2,
- expandedCount: undefined,
results: partial([
partial({ name: '$browser', is_seen_on_filtered_events: true }),
partial({ name: 'browser_no_dollar_not_on_event', is_seen_on_filtered_events: false }),
diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts
index fd848bffd090..334a3e18c53e 100644
--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts
@@ -274,6 +274,11 @@ export interface infiniteListLogicValues {
dedupedTopMatches: (SkeletonItem | TaxonomicDefinitionTypes)[]
excludedProperties: string[] | undefined
expandedCount: number
+ expandedCountResult: {
+ count: number
+ searchQuery: string
+ } | null
+ expandedCountResultLoading: boolean
fuse: ListFuse
group: TaxonomicFilterGroup | undefined
hasAppliedInitialPin: boolean
@@ -290,25 +295,14 @@ export interface infiniteListLogicValues {
isLocalDataLoading: boolean
isSoleSubstantiveGroup: boolean
isSuggestedFilters: boolean
- items:
- | {
- count: number
- expandedCount?: undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: QuickFilterItem[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- | {
- count: number
- expandedCount: number | undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: (SkeletonItem | TaxonomicDefinitionTypes)[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
+ items: {
+ count: number
+ first: boolean | undefined
+ queryChanged: boolean | undefined
+ results: (SkeletonItem | TaxonomicDefinitionTypes)[]
+ searchQuery: string | undefined
+ syntheticSelectedCount: number
+ }
keywordShortcutItems: QuickFilterItem[]
limit: number
listGroupType: TaxonomicFilterGroupType
@@ -391,6 +385,47 @@ export interface infiniteListLogicActions {
expand: () => {
value: true
}
+ loadExpandedCount: ({
+ endpoint,
+ searchParams,
+ searchQuery,
+ }: {
+ endpoint: string
+ searchParams: Record<string, number | string | undefined>
+ searchQuery: string
+ }) => {
+ endpoint: string
+ searchParams: Record<string, string | number | undefined>
+ searchQuery: string
+ }
+ loadExpandedCountFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadExpandedCountSuccess: (
+ expandedCountResult: {
+ count: number
+ searchQuery: string
+ } | null,
+ payload?: {
+ endpoint: string
+ searchParams: Record<string, string | number | undefined>
+ searchQuery: string
+ }
+ ) => {
+ expandedCountResult: {
+ count: number
+ searchQuery: string
+ } | null
+ payload?: {
+ endpoint: string
+ searchParams: Record<string, string | number | undefined>
+ searchQuery: string
+ }
+ }
loadRemoteItems: (options: LoaderOptions) => LoaderOptions
loadRemoteItemsFailure: (
error: string,
@@ -404,7 +439,6 @@ export interface infiniteListLogicActions {
| ListStorage
| {
count: any
- expandedCount: any
loadDurationMs: number | undefined
queryChanged: boolean
results: TaxonomicDefinitionTypes[]
@@ -416,7 +450,6 @@ export interface infiniteListLogicActions {
| ListStorage
| {
count: any
- expandedCount: any
loadDurationMs: number | undefined
queryChanged: boolean
results: TaxonomicDefinitionTypes[]
@@ -548,7 +581,8 @@ export interface infiniteListLogicMeta {
isExpandable: (
remoteEndpoint: string | null,
scopedRemoteEndpoint: string | null,
- remoteItems: ListStorage
+ remoteItems: ListStorage,
+ expandedCount: number
) => boolean
isExpandableButtonSelected: (isExpandable: boolean, index: number, totalListCount: number) => boolean
hasRemoteDataSource: (remoteEndpoint: string | null) => boolean
@@ -678,90 +712,40 @@ export interface infiniteListLogicMeta {
value: TaxonomicFilterValue | undefined
},
arg: boolean | undefined
- ) =>
- | {
- count: number
- expandedCount?: undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: QuickFilterItem[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- | {
- count: number
- expandedCount: number | undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: (SkeletonItem | TaxonomicDefinitionTypes)[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- totalResultCount: (
- items:
- | {
- count: number
- expandedCount: number | undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: (SkeletonItem | TaxonomicDefinitionTypes)[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- | {
- count: number
- expandedCount?: undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: QuickFilterItem[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- ) => number
+ ) => {
+ count: number
+ first: boolean | undefined
+ queryChanged: boolean | undefined
+ results: (SkeletonItem | TaxonomicDefinitionTypes)[]
+ searchQuery: string | undefined
+ syntheticSelectedCount: number
+ }
+ totalResultCount: (items: {
+ count: number
+ first: boolean | undefined
+ queryChanged: boolean | undefined
+ results: (SkeletonItem | TaxonomicDefinitionTypes)[]
+ searchQuery: string | undefined
+ syntheticSelectedCount: number
+ }) => number
totalExtraCount: (isExpandable: boolean, hasRenderFunction: boolean) => number
totalListCount: (totalResultCount: number, totalExtraCount: number) => number
expandedCount: (
- items:
- | {
- count: number
- expandedCount: number | undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: (SkeletonItem | TaxonomicDefinitionTypes)[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- | {
- count: number
- expandedCount?: undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: QuickFilterItem[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
+ expandedCountResult: {
+ count: number
+ searchQuery: string
+ } | null,
+ searchQuery: string,
+ isExpanded: boolean
) => number
- results: (
- items:
- | {
- count: number
- expandedCount: number | undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: (SkeletonItem | TaxonomicDefinitionTypes)[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- | {
- count: number
- expandedCount?: undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: QuickFilterItem[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- ) => QuickFilterItem[] | (SkeletonItem | TaxonomicDefinitionTypes)[]
+ results: (items: {
+ count: number
+ first: boolean | undefined
+ queryChanged: boolean | undefined
+ results: (SkeletonItem | TaxonomicDefinitionTypes)[]
+ searchQuery: string | undefined
+ syntheticSelectedCount: number
+ }) => QuickFilterItem[] | (SkeletonItem | TaxonomicDefinitionTypes)[]
showSuggestedFiltersEmptyState: (
isSuggestedFilters: boolean,
trimmedSearchQuery: string,
@@ -785,25 +769,14 @@ export interface infiniteListLogicMeta {
) => number | null
selectedItem: (
index: number,
- items:
- | {
- count: number
- expandedCount: number | undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: (SkeletonItem | TaxonomicDefinitionTypes)[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- | {
- count: number
- expandedCount?: undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: QuickFilterItem[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
+ items: {
+ count: number
+ first: boolean | undefined
+ queryChanged: boolean | undefined
+ results: (SkeletonItem | TaxonomicDefinitionTypes)[]
+ searchQuery: string | undefined
+ syntheticSelectedCount: number
+ }
) => TaxonomicDefinitionTypes | undefined
selectedItemValue: (
selectedItem: TaxonomicDefinitionTypes | undefined,
@@ -927,7 +900,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
actions.abortAnyRunningQuery()
let response: any
- let expandedCountResponse: any = null
const runAbortController = cache.abortController
const requestOptions = { signal: runAbortController?.signal }
@@ -953,33 +925,16 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
count: transformedGroups.length,
}
actions.setHasMore(groupsResponse.hasMore || false)
- if (scopedRemoteEndpoint && !isExpanded) {
- expandedCountResponse = { count: transformedGroups.length }
- }
} else {
- // Use the original REST API for non-groups endpoints
- const [apiResponse, expandedApiResponse] = await Promise.all([
- // get the list of results
- fetchCachedListResponse(
- scopedRemoteEndpoint && !isExpanded ? scopedRemoteEndpoint : remoteEndpoint,
- searchParams,
- requestOptions
- ),
- // if this is an unexpanded scoped list, get the count for the full list
- scopedRemoteEndpoint && !isExpanded
- ? fetchCachedListResponse(
- remoteEndpoint,
- {
- ...searchParams,
- limit: 1,
- offset: 0,
- },
- requestOptions
- )
- : null,
- ])
- response = apiResponse
- expandedCountResponse = expandedApiResponse
+ // The full count only adds a final expand row; it cannot move the search results.
+ if (scopedRemoteEndpoint && !isExpanded && offset === 0) {
+ actions.loadExpandedCount({ endpoint: remoteEndpoint, searchParams, searchQuery })
+ }
+ response = await fetchCachedListResponse(
+ scopedRemoteEndpoint && !isExpanded ? scopedRemoteEndpoint : remoteEndpoint,
+ searchParams,
+ requestOptions
+ )
}
} catch (error: any) {
// An abort means either a newer query superseded this run, which owns the
@@ -1033,7 +988,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
response.count ||
(Array.isArray(response) ? response.length : 0) ||
(response.results || []).length,
- expandedCount: expandedCountResponse?.count,
}
},
updateRemoteItem: ({ item }) => {
@@ -1050,6 +1004,56 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
},
},
],
+ expandedCountResult: [
+ null as { searchQuery: string; count: number } | null,
+ {
+ loadExpandedCount: async (
+ {
+ endpoint,
+ searchParams,
+ searchQuery,
+ }: {
+ endpoint: string
+ searchParams: Record<string, string | number | undefined>
+ searchQuery: string
+ },
+ breakpoint
+ ) => {
+ cache.disposables.dispose('expandedCountRequest')
+ const controller = new AbortController()
+ cache.expandedCountController = controller
+ cache.disposables.add(
+ () => {
+ const timeout = window.setTimeout(() => controller.abort(), REMOTE_ITEMS_REQUEST_TIMEOUT_MS)
+ return () => {
+ window.clearTimeout(timeout)
+ controller.abort()
+ }
+ },
+ 'expandedCountRequest',
+ { pauseOnPageHidden: false }
+ )
+ try {
+ const response = await fetchCachedListResponse(
+ endpoint,
+ { ...searchParams, limit: 1, offset: 0 },
+ { signal: controller.signal }
+ )
+ breakpoint()
+ return { searchQuery, count: response.count ?? 0 }
+ } catch {
+ breakpoint()
+ // An optional expand count failing must not discard the selectable results.
+ return null
+ } finally {
+ if (cache.expandedCountController === controller) {
+ cache.disposables.dispose('expandedCountRequest')
+ cache.expandedCountController = null
+ }
+ }
+ },
+ },
+ ],
})),
reducers(({ props }) => ({
index: [
@@ -1229,14 +1233,13 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
],
hasRenderFunction: [(s) => [s.group], (group: TaxonomicFilterGroup | undefined) => !!group?.render],
isExpandable: [
- (s) => [s.remoteEndpoint, s.scopedRemoteEndpoint, s.remoteItems],
- (remoteEndpoint: string | null, scopedRemoteEndpoint: string | null, remoteItems: ListStorage) =>
- !!(
- remoteEndpoint &&
- scopedRemoteEndpoint &&
- remoteItems.expandedCount &&
- remoteItems.expandedCount > remoteItems.count
- ),
+ (s) => [s.remoteEndpoint, s.scopedRemoteEndpoint, s.remoteItems, s.expandedCount],
+ (
+ remoteEndpoint: string | null,
+ scopedRemoteEndpoint: string | null,
+ remoteItems: ListStorage,
+ expandedCount: number
+ ) => !!(remoteEndpoint && scopedRemoteEndpoint && expandedCount > remoteItems.count),
],
isExpandableButtonSelected: [
(s) => [s.isExpandable, s.index, s.totalListCount],
@@ -1942,7 +1945,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
remoteItems.count +
topMatches.filter((item) => !isSkeletonItem(item)).length,
searchQuery: remoteItems.searchQuery || localItems.searchQuery,
- expandedCount: remoteItems.expandedCount,
queryChanged: remoteItems.queryChanged,
first: localItems.first && remoteItems.first,
}
@@ -1954,7 +1956,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
items:
| {
count: number
- expandedCount: number | undefined
first: boolean | undefined
queryChanged: boolean | undefined
results: (SkeletonItem | TaxonomicDefinitionTypes)[]
@@ -1963,7 +1964,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
}
| {
count: number
- expandedCount?: undefined
first: boolean | undefined
queryChanged: boolean | undefined
results: QuickFilterItem[]
@@ -1981,28 +1981,9 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
(totalResultCount: number, totalExtraCount: number) => totalResultCount + totalExtraCount,
],
expandedCount: [
- (s) => [s.items],
- (
- items:
- | {
- count: number
- expandedCount: number | undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: (SkeletonItem | TaxonomicDefinitionTypes)[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- | {
- count: number
- expandedCount?: undefined
- first: boolean | undefined
- queryChanged: boolean | undefined
- results: QuickFilterItem[]
- searchQuery: string | undefined
- syntheticSelectedCount: number
- }
- ) => items.expandedCount || 0,
+ (s) => [s.expandedCountResult, s.searchQuery, s.isExpanded],
+ (result: { searchQuery: string; count: number } | null, searchQuery: string, isExpanded: boolean): number =>
+ !isExpanded && result?.searchQuery === searchQuery ? result.count : 0,
],
results: [
(s) => [s.items],
@@ -2010,7 +1991,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
items:
| {
count: number
- expandedCount: number | undefined
first: boolean | undefined
queryChanged: boolean | undefined
results: (SkeletonItem | TaxonomicDefinitionTypes)[]
@@ -2019,7 +1999,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
}
| {
count: number
- expandedCount?: undefined
first: boolean | undefined
queryChanged: boolean | undefined
results: QuickFilterItem[]
@@ -2084,7 +2063,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
items:
| {
count: number
- expandedCount: number | undefined
first: boolean | undefined
queryChanged: boolean | undefined
results: (SkeletonItem | TaxonomicDefinitionTypes)[]
@@ -2093,7 +2071,6 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
}
| {
count: number
- expandedCount?: undefined
first: boolean | undefined
queryChanged: boolean | undefined
results: QuickFilterItem[]
@@ -2178,6 +2155,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
}
},
setSearchQuery: async () => {
+ cache.disposables.dispose('expandedCountRequest')
const searchQueryChanged = cache.lastSearchQuery !== values.searchQuery
cache.lastSearchQuery = values.searchQuery
@@ -2292,6 +2270,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
actions.setIndex(rowIndex)
},
expand: () => {
+ cache.disposables.dispose('expandedCountRequest')
actions.loadRemoteItems({ offset: values.index, limit: values.limit })
},
abortAnyRunningQuery: () => {
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
index 94ae673db409..e19f7c143d61 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
@@ -46,10 +46,16 @@ function renderCombobox(): ReturnType<typeof render> {
)
}
-function makeEntry(groupType: TaxonomicFilterGroupType, name: string, groupName: string): any {
+function makeEntry(groupType: TaxonomicFilterGroupType, name: string, groupName: string, endpoint?: string): any {
return {
item: { name },
- group: { type: groupType, name: groupName, getName: (t: any) => t?.name, getValue: (t: any) => t?.name },
+ group: {
+ type: groupType,
+ name: groupName,
+ getName: (t: any) => t?.name,
+ getValue: (t: any) => t?.name,
+ ...(endpoint ? { endpoint } : {}),
+ },
name,
}
}
@@ -795,6 +801,33 @@ describe('MenuFilterCombobox', () => {
expect(screen.queryByText('my_recent_event')).not.toBeInTheDocument()
})
+ it.each(['Recent', 'Pinned'])(
+ 'filters the %s category by the query, endpoint-backed rows included',
+ async (label) => {
+ const user = userEvent.setup()
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+ // Saved rows carry their source group, and those groups fetch from an endpoint —
+ // but the rows themselves never reach it, so the query must filter them here.
+ const savedEntries = [
+ makeEntry(TaxonomicFilterGroupType.Events, 'browser_opened', 'Events', 'api/event_definitions'),
+ makeEntry(TaxonomicFilterGroupType.Events, 'checkout_started', 'Events', 'api/event_definitions'),
+ ]
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events],
+ searchQuery: 'browser',
+ recentEntries: label === 'Recent' ? savedEntries : undefined,
+ pinnedEntries: label === 'Pinned' ? savedEntries : undefined,
+ })
+
+ await user.click(screen.getByLabelText('Filter category'))
+ await user.click(await within(await openedCategoryPopup()).findByText(label))
+
+ await waitFor(() => expect(rowTexts().some((t) => t.includes('browser_opened'))).toBe(true))
+ expect(rowTexts().some((t) => t.includes('checkout_started'))).toBe(false)
+ }
+ )
+
it('tags recents and pinned rows with their source recency', async () => {
apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })
@@ -1084,6 +1117,97 @@ describe('MenuFilterCombobox', () => {
})
describe('reveal barrier', () => {
+ it('waits for contributing categories but not their full expansion counts', async () => {
+ let resolveProperties!: (value: { results: { id: number; name: string }[]; count: number }) => void
+ let resolveCount!: (value: { count: number }) => void
+ apiGet.mockImplementation((url: string) => {
+ if (url.includes('property_definitions')) {
+ return new Promise((resolve) => {
+ if (url.includes('filter_by_event_names=true')) {
+ resolveProperties = resolve
+ } else {
+ resolveCount = resolve
+ }
+ })
+ }
+ return Promise.resolve({ results: [{ id: 1, name: 'browser_opened' }], count: 1 })
+ })
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.EventProperties],
+ searchQuery: 'browser',
+ eventNames: ['browser_opened'],
+ })
+ await waitFor(() => expect(resolveProperties).toBeTruthy())
+ expect(screen.getByTestId('menu-filter-loading')).toBeInTheDocument()
+ expect(rowTexts()).toEqual([])
+
+ await act(async () => resolveProperties({ results: [{ id: 2, name: 'browser_name' }], count: 1 }))
+ await waitFor(() => expect(rowTexts().some((text) => text.includes('browser_name'))).toBe(true))
+ expect(rowTexts().some((text) => text.includes('browser_opened'))).toBe(true)
+ expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument()
+ const visibleRows = rowTexts()
+
+ await act(async () => resolveCount({ count: 9 }))
+ expect(rowTexts()).toEqual(visibleRows)
+ })
+
+ it('reveals the selected category while another category is still fetching', async () => {
+ const user = userEvent.setup()
+ apiGet.mockImplementation((url: string) =>
+ url.includes('property_definitions')
+ ? new Promise(() => {})
+ : Promise.resolve({ results: [{ id: 1, name: 'browser_opened' }], count: 1 })
+ )
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.EventProperties],
+ searchQuery: 'browser',
+ })
+ await waitFor(() => expect(screen.getByTestId('menu-filter-loading')).toBeInTheDocument())
+ await user.click(screen.getByLabelText('Filter category'))
+ await user.click(await within(await openedCategoryPopup()).findByText('Events'))
+ await waitFor(() => expect(rowTexts().some((text) => text.includes('browser_opened'))).toBe(true))
+ expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument()
+ })
+
+ it.each(['Recent', 'Pinned'])('never hides %s behind skeletons when switched to mid-search', async (label) => {
+ const user = userEvent.setup()
+ apiGet.mockResolvedValue({ results: [{ id: 1, name: 'browser_opened' }], count: 1 })
+ const resolvedEntry = makeEntry(TaxonomicFilterGroupType.Events, `browser_${label.toLowerCase()}`, 'Events')
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events],
+ searchQuery: 'browser',
+ recentEntries: label === 'Recent' ? [resolvedEntry] : undefined,
+ pinnedEntries: label === 'Pinned' ? [resolvedEntry] : undefined,
+ })
+ await waitFor(() => expect(rowTexts().some((text) => text.includes('browser_opened'))).toBe(true))
+
+ // The skeleton is inserted and removed within one event's commits, so a
+ // final-state query cannot see it. Record every insertion instead.
+ let skeletonInsertions = 0
+ const observer = new MutationObserver((mutations) => {
+ for (const mutation of mutations) {
+ for (const node of Array.from(mutation.addedNodes)) {
+ if (
+ node instanceof HTMLElement &&
+ (node.matches('[data-attr="menu-filter-loading"]') ||
+ node.querySelector('[data-attr="menu-filter-loading"]'))
+ ) {
+ skeletonInsertions += 1
+ }
+ }
+ }
+ })
+ observer.observe(document.body, { childList: true, subtree: true })
+ try {
+ await user.click(screen.getByLabelText('Filter category'))
+ await user.click(await within(await openedCategoryPopup()).findByText(label))
+ await waitFor(() => expect(rowTexts().some((text) => text.includes(resolvedEntry.name))).toBe(true))
+ } finally {
+ observer.disconnect()
+ }
+ expect(skeletonInsertions).toBe(0)
+ })
+
it('hides stale results during a refetch and reveals once it settles', async () => {
const user = userEvent.setup()
let resolveSecond: ((value: { results: any[]; count: number }) => void) | undefined
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
index fef837454a42..3de8b8d6cbdb 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
@@ -234,10 +234,12 @@ export function MenuFilterCombobox({
// Per-group `isFetching` flags (true during background refetches too, unlike
// `loadingByType` which is `loading && no-items-yet`). Drives the reveal
// barrier so kept-previous-data refetches still hold the list.
- const [fetchingByType, setFetchingByType] = useState<Record<string, boolean>>({})
- // Only engages while actively searching a fetching scope. Recent/Pinned
- // drills read pre-resolved `drillItems` (no fetch) so they're never gated.
- const searching = !drillItems && !!searchQuery.trim()
+ const [fetchingByType, setFetchingByType] = useState<Record<string, { query?: string; fetching: boolean }>>({})
+ // Only engages while actively searching a fetching scope. Recent/Pinned read
+ // pre-resolved entries (`drillItems` when drilled to, the recents/pinned props
+ // when picked from the category select) and never fetch, so they're never gated.
+ const readsResolvedEntries = !!drillItems || activeScope === 'recent' || activeScope === 'pinned'
+ const searching = !readsResolvedEntries && !!searchQuery.trim()
// Reveal barrier (ported from the legacy `taxonomicFilterLogic`): on a fresh
// search we hold the result list behind skeletons until every visible group's
// fetch settles (or a 5s fallback), so slower groups don't render on top of a
@@ -248,6 +250,7 @@ export function MenuFilterCombobox({
// sharing this same list are still in flight.
const [revealBarrierOpen, setRevealBarrierOpen] = useState(() => !searching)
const [barrierQuery, setBarrierQuery] = useState(searchQuery)
+ const [barrierScope, setBarrierScope] = useState(activeScope)
// Seed the highlight with the committed selection so the preview
// pane shows the right definition before any row hovers fire. Once
// the list mounts, `autoHighlight="always"` + the reordered
@@ -280,8 +283,12 @@ export function MenuFilterCombobox({
setLoadingByType((prev) => (prev[type] === loading ? prev : { ...prev, [type]: loading }))
}, [])
- const reportFetching = useCallback((type: string, fetching: boolean): void => {
- setFetchingByType((prev) => (prev[type] === fetching ? prev : { ...prev, [type]: fetching }))
+ const reportFetching = useCallback((type: string, fetching: boolean, query?: string): void => {
+ setFetchingByType((prev) =>
+ prev[type]?.fetching === fetching && prev[type]?.query === query
+ ? prev
+ : { ...prev, [type]: { query, fetching } }
+ )
}, [])
// Chips show only when `drillTo='all'` — drilled scopes lock to one
@@ -552,6 +559,12 @@ export function MenuFilterCombobox({
let base: MenuFilterEntry[]
if (!q) {
base = indexed
+ } else if (readsResolvedEntries) {
+ // Recent/Pinned rows come from the user's saved lists and never reach an
+ // endpoint, so the client Fuse is the only search they get. Without this
+ // branch the endpoint passthrough below keeps every saved row, because each
+ // row carries its source group (Events, Cohorts, ...) and those do fetch.
+ base = fuseMatchEntries(indexed, q)
} else {
// The endpoint is the search authority for endpoint-backed
// groups (e.g. Cohorts use `name__icontains` server-side, plus
@@ -613,7 +626,17 @@ export function MenuFilterCombobox({
return assembled
}
return base
- }, [indexed, searchQuery, selectedRowId, recentsPinnedPrefix, suggestedPrefix, showChips, activeChip, drillTo])
+ }, [
+ indexed,
+ searchQuery,
+ readsResolvedEntries,
+ selectedRowId,
+ recentsPinnedPrefix,
+ suggestedPrefix,
+ showChips,
+ activeChip,
+ drillTo,
+ ])
// O(1) row -> rendered-position lookup, rebuilt with `filtered`. Avoids an
// O(n) `indexOf` per commit and the stale-index risk if `filtered`'s identity
@@ -656,15 +679,15 @@ export function MenuFilterCombobox({
// Close synchronously the instant the query changes (React "adjust state
// while rendering" pattern) so a stale list never paints between keystroke
// and the fetch starting. Re-opens immediately for empty/drill scopes.
- if (searchQuery !== barrierQuery) {
+ if (searchQuery !== barrierQuery || activeScope !== barrierScope) {
setBarrierQuery(searchQuery)
+ setBarrierScope(activeScope)
setRevealBarrierOpen(!searching)
}
- const anyFetching = useMemo(() => targetGroups.some((g) => fetchingByType[g.type]), [targetGroups, fetchingByType])
- // Open once every visible group has settled. Edge-triggered on results /
- // fetching changes (not the bare query change) so the close commit — where
- // the Fetchers haven't yet reported `isFetching` — can't open it early.
- // Mirrors legacy's `!anyGroupLoading` check after `infiniteListResultsReceived`.
+ const anyFetching = targetGroups.some(
+ (g) => fetchingByType[g.type]?.query !== searchQuery || fetchingByType[g.type]?.fetching
+ )
+ // A missing report or one from a previous query cannot establish that a category has settled.
useEffect(() => {
if (revealBarrierOpen || !searching) {
return
@@ -672,8 +695,7 @@ export function MenuFilterCombobox({
if (!anyFetching) {
setRevealBarrierOpen(true)
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [itemsByType, fetchingByType])
+ }, [anyFetching, revealBarrierOpen, searching, barrierScope])
// 5s fallback so a wedged/never-settling fetch can't trap the list behind
// skeletons forever. Re-armed on every fresh query.
useEffect(() => {
@@ -682,7 +704,7 @@ export function MenuFilterCombobox({
}
const id = window.setTimeout(() => setRevealBarrierOpen(true), REVEAL_BARRIER_TIMEOUT_MS)
return () => window.clearTimeout(id)
- }, [barrierQuery, searching])
+ }, [barrierQuery, barrierScope, searching])
// While held, show skeletons in place of the (stale/partial) result list.
const barrierClosed = searching && !revealBarrierOpen
const displayedItems = barrierClosed ? NO_ENTRIES : filtered
@@ -1376,10 +1398,11 @@ function Fetcher({
onLoadingChange: (type: string, loading: boolean) => void
/** Reports `isFetching` (true during background refetches too) so the
* parent's reveal barrier holds the list until every group settles. */
- onFetchingChange: (type: string, fetching: boolean) => void
+ onFetchingChange: (type: string, fetching: boolean, query?: string) => void
}): null {
const { getGroupListInput } = useTaxonomicFilterContext()
- const list = useGroupList({ ...getGroupListInput(group), excludeStale })
+ const input = getGroupListInput(group)
+ const list = useGroupList({ ...input, excludeStale })
useEffect(() => {
onItems(group.type, list.items)
}, [group.type, list.items, onItems])
@@ -1387,8 +1410,8 @@ function Fetcher({
onLoadingChange(group.type, list.showLoadingState)
}, [group.type, list.showLoadingState, onLoadingChange])
useEffect(() => {
- onFetchingChange(group.type, list.isFetching)
- }, [group.type, list.isFetching, onFetchingChange])
+ onFetchingChange(group.type, list.isFetching, input.searchQuery)
+ }, [group.type, list.isFetching, input.searchQuery, onFetchingChange])
// Make sure we flip back to "not loading"/"not fetching" when this group
// unmounts — otherwise a stale `true` from a previously-active chip would
// keep the skeleton (or the reveal barrier) stuck after we switch scope.