:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(taxonomic-filter): collapse pageview URLs to one contains row (#62465)
Paul D'Ambra00b001dd6af4
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsxindex 1d0b80782ca7..65e07b6619af 100644--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx@@ -361,6 +361,115 @@ describe('MenuFilterCombobox', () => {expect(promotedIdx).toBeLessThan(otherIdx)})+ describe('pageview URLs collapse to a single "contains" suggestion', () => {+ const mockUrlValues = (urls: string[]): void => {+ apiGet.mockImplementation((url: string) => {+ if (url.includes('events/values') && url.includes('current_url')) {+ return Promise.resolve(urls.map((name) => ({ name })))+ }+ return Promise.resolve({ results: [], count: 0 })+ })+ }++ it('collapses matching URLs into one "URL contains <query>" row, not the raw URL list', async () => {+ mockUrlValues(['https://app.posthog.com/checkout', 'https://app.posthog.com/checkout/pay'])++ renderAll({ groupTypes: [TaxonomicFilterGroupType.PageviewUrls], searchQuery: 'checkout' })++ await waitFor(() => expect(rowTexts().some((t) => t.includes('URL contains "checkout"'))).toBe(true))+ const rows = rowTexts()+ // Exactly one synthetic row, and none of the raw matched URLs are listed.+ expect(rows.filter((t) => t.includes('URL contains "checkout"'))).toHaveLength(1)+ expect(rows.some((t) => t.includes('https://app.posthog.com/checkout'))).toBe(false)+ })++ it('shows no URL suggestion when no pageview URL matches (0 slots)', async () => {+ mockUrlValues([])++ renderAll({ groupTypes: [TaxonomicFilterGroupType.PageviewUrls], searchQuery: 'zzznomatch' })++ await waitFor(() => expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument())+ expect(screen.queryByText(/URL contains/)).not.toBeInTheDocument()+ })++ it('does not offer Pageview URLs as a navigable category', async () => {+ const user = userEvent.setup()+ mockUrlValues(['https://app.posthog.com/checkout'])++ renderAll({+ groupTypes: [TaxonomicFilterGroupType.EventProperties, TaxonomicFilterGroupType.PageviewUrls],+ })++ await user.click(screen.getByRole('combobox', { name: 'Filter category' }))+ expect(screen.queryByRole('option', { name: 'Pageview URLs' })).not.toBeInTheDocument()+ })++ it('commits the typed query as the value so it becomes $current_url contains <query>', async () => {+ const user = userEvent.setup()+ const onCommit = jest.fn()+ mockUrlValues(['https://app.posthog.com/checkout'])++ renderAll({+ groupTypes: [TaxonomicFilterGroupType.PageviewUrls],+ searchQuery: 'checkout',+ onCommit,+ })++ await waitFor(() => expect(rowTexts().some((t) => t.includes('URL contains "checkout"'))).toBe(true))+ const row = Array.from(document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]')).find((el) =>+ el.textContent?.includes('URL contains "checkout"')+ ) as HTMLElement+ await user.click(row)++ const [entry] = onCommit.mock.calls[0]+ expect(entry.group.type).toBe(TaxonomicFilterGroupType.PageviewUrls)+ // getValue reads the item name; the synthetic row carries the query, which+ // `taxonomicPropertyFilterLogic.selectItem` turns into `$current_url IContains`.+ expect(entry.group.getValue(entry.item)).toBe('checkout')+ // Tagged so the commit telemetry can measure adoption of the shortcut.+ expect((entry.item as { isContainsShortcut?: boolean }).isContainsShortcut).toBe(true)+ })++ it('opens on the All scope when the committed selection is from the hidden Pageview URLs category', async () => {+ apiGet.mockImplementation((url: string) => {+ if (url.includes('property_definitions')) {+ return Promise.resolve({ results: [{ id: 1, name: '$browser' }], count: 1 })+ }+ return Promise.resolve([])+ })+ // What TaxonomicPopoverMenu builds when reopening an existing+ // `$current_url icontains <value>` filter picked via the shortcut.+ const selectedEntry = makeEntry(TaxonomicFilterGroupType.PageviewUrls, 'checkout', 'Pageview URLs')++ render(+ <Provider>+ <TaxonomicFilterHeadless.Root+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.PageviewUrls,+ ]}+ onChange={jest.fn()}+ >+ <MenuFilterCombobox+ drillTo="all"+ selectedEntry={selectedEntry}+ onCommit={jest.fn()}+ onBack={jest.fn()}+ />+ </TaxonomicFilterHeadless.Root>+ </Provider>+ )++ // Stranded-scope regression: the category dropdown must read "All"+ // (pageview_urls is not a navigable option) and the All-surface+ // content must render rather than an empty hidden-category list.+ await waitFor(() => expect(rowTexts().some((t) => t.includes('$browser'))).toBe(true))+ expect(screen.getByRole('combobox', { name: 'Filter category' })).toHaveTextContent('All')+ // The committed selection stays reachable via the selected-entry prepend.+ expect(rowTexts().some((t) => t.includes('checkout'))).toBe(true)+ })+ })+it('drops the recents/pinned prefix once the query no longer matches them', async () => {apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })@@ -622,4 +731,58 @@ describe('MenuFilterCombobox', () => {expect(newUrls.every((url: string) => !url.includes('exclude_stale=true'))).toBe(true)})})++ describe('reveal barrier', () => {+ 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+ apiGet.mockImplementation((url: string) => {+ if (!url.includes('property_definitions')) {+ return Promise.resolve({ results: [], count: 0, next: null })+ }+ if (url.includes('search=alpha')) {+ return Promise.resolve({ results: [{ id: 1, name: 'alpha_prop' }], count: 1 })+ }+ // The second query's fetch is held open so we can observe the barrier holding.+ return new Promise((resolve) => {+ resolveSecond = resolve+ })+ })++ function Harness(): JSX.Element {+ const [query, setQuery] = useState('alpha')+ return (+ <>+ <button onClick={() => setQuery('beta')}>change-query</button>+ <Provider>+ <TaxonomicFilterHeadless.Root+ taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}+ onChange={jest.fn()}+ searchQuery={query}+ >+ <MenuFilterCombobox drillTo="all" onCommit={jest.fn()} onBack={jest.fn()} />+ </TaxonomicFilterHeadless.Root>+ </Provider>+ </>+ )+ }++ render(<Harness />)++ // First query settles -> its result is revealed.+ await waitFor(() => expect(rowTexts().some((t) => t.includes('alpha_prop'))).toBe(true))++ // Change query: the refetch is in flight. `keepPreviousData` means the stale+ // `alpha_prop` is still in the list data, but the barrier must hide it behind a+ // skeleton rather than leaking it (the bug this ports the legacy barrier to fix).+ await user.click(screen.getByRole('button', { name: 'change-query' }))+ await waitFor(() => expect(screen.getByTestId('menu-filter-loading')).toBeInTheDocument())+ expect(rowTexts().some((t) => t.includes('alpha_prop'))).toBe(false)++ // Resolve the refetch -> barrier opens, the new result shows, skeleton gone.+ resolveSecond?.({ results: [{ id: 2, name: 'beta_prop' }], count: 1 })+ await waitFor(() => expect(rowTexts().some((t) => t.includes('beta_prop'))).toBe(true))+ expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument()+ })+ })})diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsxindex 62950a559634..f9c0f5a68dda 100644--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx@@ -77,10 +77,27 @@ const HIDDEN_FROM_CHIPS: ReadonlySet<TaxonomicFilterGroupType> = new Set([TaxonomicFilterGroupType.HogQLExpression,])+/** Groups that feed the "all" surface but are collapsed to a single+ * "URL contains <query>" suggestion rather than listing every matching value,+ * and are not offered as a standalone chip/category. People filtering by URL+ * overwhelmingly want a contains match, so one synthetic row (when any URL+ * matches) beats a wall of exact URLs. */+const COLLAPSED_TO_CONTAINS_ROW: ReadonlySet<TaxonomicFilterGroupType> = new Set([+ TaxonomicFilterGroupType.PageviewUrls,+])+/** How many recents and pinned each lead the default "All" surface, matching* the pill variant's top-3 face. */const RECENT_PINNED_PREFIX_LIMIT = 3+/** Fallback that opens the reveal barrier even if some group's fetch never+ * settles. Matches the legacy `taxonomicFilterLogic` value. */+const REVEAL_BARRIER_TIMEOUT_MS = 5000++/** Stable empty list so a held (barrier-closed) render keeps a constant+ * `items` identity instead of allocating a new array each time. */+const NO_ENTRIES: MenuFilterEntry[] = []+/** Debounce before emitting `taxonomic_filter_search_query` — matches the* legacy picker so the search telemetry is comparable across variants. */export const SEARCH_QUERY_DEBOUNCE_MS = 500@@ -149,7 +166,10 @@ export function MenuFilterCombobox({// their selection's category by default — they can still tab back to// "All" or any other chip without leaving the combobox.const [activeChip, setActiveChip] = useState<DrillCategory>(() => {- if (drillTo === 'all' && selectedEntry) {+ // Collapsed groups (e.g. Pageview URLs) aren't navigable categories, so a+ // selection from one lands on "All" — its row still surfaces there via the+ // selected-entry prepend — instead of stranding the user in a hidden scope.+ if (drillTo === 'all' && selectedEntry && !COLLAPSED_TO_CONTAINS_ROW.has(selectedEntry.group.type)) {return selectedEntry.group.type}return drillTo@@ -164,6 +184,16 @@ export function MenuFilterCombobox({// fetch status across every visible (target) group, not just the one// whose `useGroupList` hook last rendered.const [loadingByType, setLoadingByType] = useState<Record<string, boolean>>({})+ // 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>>({})+ // 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+ // stale/partial list and rows don't jump around. Mirrors `revealBarrierOpen`.+ const [revealBarrierOpen, setRevealBarrierOpen] = useState(true)+ const [barrierQuery, setBarrierQuery] = useState(searchQuery)// 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@@ -237,6 +267,10 @@ 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 }))+ }, [])+// Chips show only when `drillTo='all'` — drilled scopes lock to one// category and hide the chip row per spec.const showChips = drillTo === 'all'@@ -256,6 +290,10 @@ export function MenuFilterCombobox({opts.push({ value: 'pinned', label: 'Pinned' })}for (const g of visibleChipGroups) {+ // Collapsed groups feed the "all" rows but aren't navigable categories.+ if (COLLAPSED_TO_CONTAINS_ROW.has(g.type)) {+ continue+ }opts.push({ value: g.type, label: g.name })}return opts@@ -299,8 +337,29 @@ export function MenuFilterCombobox({return pinnedEntries ?? []}const merged: MenuFilterEntry[] = []+ const trimmedQuery = searchQuery.trim()for (const group of targetGroups) {const items = itemsByType[group.type] ?? []+ // Collapse to a single "URL contains <query>" row when the contains+ // search found at least one matching URL. The synthetic item's value+ // is the typed query (its `name`, since the group's getValue reads+ // `name`), so `selectItem`'s existing PageviewUrls branch commits+ // `$current_url IContains <query>`.+ if (COLLAPSED_TO_CONTAINS_ROW.has(group.type)) {+ if (trimmedQuery && items.length > 0) {+ const label = `URL contains "${trimmedQuery}"`+ merged.push({+ // `isContainsShortcut` tags this synthetic row so the commit+ // telemetry can measure adoption of the contains shortcut vs+ // the old per-URL value-picker.+ item: { name: trimmedQuery, isContainsShortcut: true } as unknown as TaxonomicDefinitionTypes,+ group,+ name: label,+ friendlyLabel: label,+ })+ }+ continue+ }for (const item of items) {merged.push({item,@@ -356,6 +415,7 @@ export function MenuFilterCombobox({showChips,activeChip,drillTo,+ searchQuery,surveyQuestionLabels,])@@ -487,6 +547,44 @@ export function MenuFilterCombobox({return targetGroups.some((g) => loadingByType[g.type])}, [drillItems, targetGroups, loadingByType])+ // ---- Reveal barrier ----------------------------------------------------+ // 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()+ // 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) {+ setBarrierQuery(searchQuery)+ 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`.+ useEffect(() => {+ if (revealBarrierOpen || !searching) {+ return+ }+ if (!anyFetching) {+ setRevealBarrierOpen(true)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [itemsByType, fetchingByType])+ // 5s fallback so a wedged/never-settling fetch can't trap the list behind+ // skeletons forever. Re-armed on every fresh query.+ useEffect(() => {+ if (!searching) {+ return+ }+ const id = window.setTimeout(() => setRevealBarrierOpen(true), REVEAL_BARRIER_TIMEOUT_MS)+ return () => window.clearTimeout(id)+ }, [barrierQuery, searching])+ // While held, show skeletons in place of the (stale/partial) result list.+ const barrierClosed = searching && !revealBarrierOpen+ const displayedItems = barrierClosed ? NO_ENTRIES : filtered+// Empty-state message. Three branches:// - "needs more characters" — when the active chip resolves to a// single group with `minSearchQueryLength` and the search query@@ -691,7 +789,7 @@ export function MenuFilterCombobox({showTabHint={showChips && visibleChipGroups.length > 0}/><Autocomplete.Root- items={filtered}+ items={displayedItems}mode="none"inlinedefaultOpen@@ -787,12 +885,13 @@ export function MenuFilterCombobox({excludeStale={!includeStaleEvents}onItems={reportItems}onLoadingChange={reportLoading}+ onFetchingChange={reportFetching}/>))}<ScrollArea className="flex-1 min-h-0 scroll-py-8" alwaysShowScrollbars><Autocomplete.List data-quill className="p-2 scroll-py-8"><Autocomplete.Empty className="empty:hidden">- {isAnyLoading ? (+ {isAnyLoading || barrierClosed ? (<LoadingRows />) : (emptyState && (@@ -967,6 +1066,7 @@ function Fetcher({excludeStale,onItems,onLoadingChange,+ onFetchingChange,}: {group: TaxonomicFilterGroup/** Hide stale event definitions (event / custom-event groups only). */@@ -975,6 +1075,9 @@ function Fetcher({/** Reports `isLoading` (no items yet) so the parent can show a skeleton* instead of "No X found" during the first fetch. */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}): null {const { getGroupListInput } = useTaxonomicFilterContext()const list = useGroupList({ ...getGroupListInput(group), excludeStale })@@ -984,14 +1087,18 @@ function Fetcher({useEffect(() => {onLoadingChange(group.type, list.showLoadingState)}, [group.type, list.showLoadingState, onLoadingChange])- // Make sure we flip back to "not loading" when this group unmounts —- // otherwise a stale `true` from a previously-active chip would keep- // the skeleton on screen after we switch scope.+ useEffect(() => {+ onFetchingChange(group.type, list.isFetching)+ }, [group.type, list.isFetching, 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.useEffect(() => {return () => {onLoadingChange(group.type, false)+ onFetchingChange(group.type, false)}- }, [group.type, onLoadingChange])+ }, [group.type, onLoadingChange, onFetchingChange])return null}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsxindex 1ded88779aa6..a375dc2daf98 100644--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx@@ -351,6 +351,9 @@ export function TaxonomicFilterMenu({position: selection?.position,query: searchQuery || undefined,wasStale: eventSelectionWasStale(entry.group.type, entry.item),+ // True when the row is the synthetic "URL contains <query>" shortcut+ // rather than a real picked item — lets us measure its adoption.+ wasUrlContainsShortcut: (entry.item as { isContainsShortcut?: boolean }).isContainsShortcut === true,})selectItem(entry.group, itemValue, mergedItem)onCommit?.({ ...entry, item: mergedItem }, extra)