: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
chore(taxonomic-filter): remove the rebuilt menu (#124477)
Paul D'Ambra9a09cd749b14
diff --git a/.agents/skills/modifying-taxonomic-filter/SKILL.md b/.agents/skills/modifying-taxonomic-filter/SKILL.mdindex c67d350a18b0..f8cc5236e1fd 100644--- a/.agents/skills/modifying-taxonomic-filter/SKILL.md+++ b/.agents/skills/modifying-taxonomic-filter/SKILL.md@@ -1,6 +1,6 @@---name: modifying-taxonomic-filter-description: Guides safe, evidence-led changes to the TaxonomicFilter, PostHog's picker for events, actions, properties, cohorts, and more. Use when adding features, fixing bugs, removing groups or tabs, changing search, ordering, recents, pinning, empty states, loading or performance, or refactoring the classic picker, rebuild menu, or headless filter panel. Indexes how users actually pick, known failure modes, the feature inventory, design principles, contested decisions, where to find evidence, and how to measure a change.+description: Guides safe, evidence-led changes to the TaxonomicFilter, PostHog's picker for events, actions, properties, cohorts, and more. Use when adding features, fixing bugs, removing groups or tabs, changing search, ordering, recents, pinning, empty states, loading or performance, or refactoring the picker. Indexes how users actually pick, known failure modes, the feature inventory, design principles, contested decisions, where to find evidence, and how to measure a change.---# Modifying the TaxonomicFilter@@ -13,18 +13,14 @@ This file is an index.Read it fully, then load only the references your change needs.The references hold the detail and the evidence.-## Four guardrails+## Three guardrails1. **Decide with evidence, not taste.**Everyone who has worked on this picker has strong opinions, and some of them are wrong.Check a claim against [product-reality](references/product-reality.md) and [evidence-sources](references/evidence-sources.md) before acting on it, including claims in issues, Slack, or this skill.2. **Demoting what users actually pick is a regression**, even with every test green.Ordering, promotion, position-0 and default-tab changes need explicit human sign-off.-3. **Two surfaces, two implementations.**- The rebuild reimplements the legacy data layer.- Most behavior changes land in both, or the arms diverge.- See [surfaces-and-mirroring](references/surfaces-and-mirroring.md).-4. **Telemetry is a public contract.**+3. **Telemetry is a public contract.**Dashboards and replay scanners read these events.Never rename or repurpose a property silently.`telemetryContract.test.ts` fails when a capture call and the contract disagree, so update the contract in the same PR.@@ -46,22 +42,22 @@ For current values, run the `taxonomic_filter_*` metrics in the PostHog data cat## Route by what you are changing-| You are changing | Read first |-| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Ordering, promotion, Suggested, default tab | [product-reality](references/product-reality.md), [design-principles](references/design-principles.md), [contested-decisions](references/contested-decisions.md) |-| Adding, removing or hiding a group or tab | [feature-inventory](references/feature-inventory.md), [surfaces-and-mirroring](references/surfaces-and-mirroring.md), [call-sites](references/call-sites-and-blast-radius.md) |-| Search, empty states, no-results recovery | [failure-modes](references/failure-modes.md), [design-principles](references/design-principles.md) |-| Recents, pinning, remembered state | [contested-decisions](references/contested-decisions.md), [design-principles](references/design-principles.md) |-| Loading, latency, pagination, errors | [performance](references/performance.md), [failure-modes](references/failure-modes.md) |-| Telemetry or dashboards | [telemetry-contract](references/telemetry-contract.md), [measuring-changes](references/measuring-changes.md) |-| Any refactor | [architecture](references/architecture.md), [common-pitfalls](references/common-pitfalls.md), [testing-patterns](references/testing-patterns.md) |-| A bug report you can't reproduce | [surfaces-and-mirroring](references/surfaces-and-mirroring.md) (confirm the surface first) |-| Deciding whether a change is worth it | [evidence-sources](references/evidence-sources.md), [measuring-changes](references/measuring-changes.md) |+| You are changing | Read first |+| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Ordering, promotion, Suggested, default tab | [product-reality](references/product-reality.md), [design-principles](references/design-principles.md), [contested-decisions](references/contested-decisions.md) |+| Adding, removing or hiding a group or tab | [feature-inventory](references/feature-inventory.md), [call-sites](references/call-sites-and-blast-radius.md) |+| Search, empty states, no-results recovery | [failure-modes](references/failure-modes.md), [design-principles](references/design-principles.md) |+| Recents, pinning, remembered state | [contested-decisions](references/contested-decisions.md), [design-principles](references/design-principles.md) |+| Loading, latency, pagination, errors | [performance](references/performance.md), [failure-modes](references/failure-modes.md) |+| Telemetry or dashboards | [telemetry-contract](references/telemetry-contract.md), [measuring-changes](references/measuring-changes.md) |+| Any refactor | [architecture](references/architecture.md), [common-pitfalls](references/common-pitfalls.md), [testing-patterns](references/testing-patterns.md) |+| A bug report you can't reproduce | [call-sites](references/call-sites-and-blast-radius.md) (confirm the call site and props first) |+| Deciding whether a change is worth it | [evidence-sources](references/evidence-sources.md), [measuring-changes](references/measuring-changes.md) |## Working loop1. **State the user problem.**- Which surface, which users, what goes wrong.+ Which users, which call site, what goes wrong.Find it in the evidence, not only in the request.See [evidence-sources](references/evidence-sources.md).2. **Size it.**@@ -69,20 +65,18 @@ For current values, run the `taxonomic_filter_*` metrics in the PostHog data catA change that helps 0.1% of opens and risks the Suggested view is not worth it.3. **Check the principles and contested decisions** that apply.If your change reverses a documented decision, say so and bring evidence.-4. **Make the change in both surfaces**, or say explicitly why not.-5. **Lock behavior with React Testing Library tests** at the call sites you touched.+4. **Lock behavior with React Testing Library tests** at the call sites you touched.Agents find this component confusing; RTL tests are the fastest guard.See [testing-patterns](references/testing-patterns.md).-6. **Decide how you will know it worked** before merging.+5. **Decide how you will know it worked** before merging.Ship ordering or default changes behind a flag with a metric and a guardrail.See [measuring-changes](references/measuring-changes.md).## Pre-change checklist- [ ] The user problem is linked to evidence (telemetry, replay, ticket)-- [ ] Change mirrored across legacy and rebuild, or the gap is stated-- [ ] Both surfaces tested if tabs or groups changed-- [ ] Shared telemetry payloads still match across both emitters+- [ ] Every call site the change reaches is tested, including ones that mount `TaxonomicFilter` directly+- [ ] Telemetry payloads still match the contract- [ ] Ordering, promotion, position-0 or default tab: human sign-off- [ ] Search or loading: plan boundary verified, optional requests don't delay results- [ ] A success metric and a guardrail metric are nameddiff --git a/.agents/skills/modifying-taxonomic-filter/references/architecture.md b/.agents/skills/modifying-taxonomic-filter/references/architecture.mdindex 84d50d43c1db..2434096493df 100644--- a/.agents/skills/modifying-taxonomic-filter/references/architecture.md+++ b/.agents/skills/modifying-taxonomic-filter/references/architecture.md@@ -1,12 +1,11 @@# TaxonomicFilter architecture-There are two architectures living side by side: the **legacy** kea-driven-tree (below) and the **rebuild** (`menu/` + `headless/`, hooks-driven). See-the mirroring table in [surfaces-and-mirroring](surfaces-and-mirroring.md) for-which concern lives where.-This file documents both.+The picker is a single, kea-driven tree.+A ground-up rewrite (`menu/` + `headless/`, hooks-driven) lived behind a+feature flag for a while and has since been removed.+If it comes back, treat it as new work rather than a restore.-## Legacy component tree+## Component tree```textTaxonomicFilter@@ -19,7 +18,7 @@ TaxonomicFilter└── InfiniteListRow # item / skeleton / pinned / recent```-## Legacy logics+## Logics| File | Owns || ----------------------------------------- | ----------------------------------------------------------------------------------------------------- |@@ -31,33 +30,6 @@ TaxonomicFilterEach `infiniteListLogic` is keyed by `taxonomicFilterLogicKey` + `listGroupType`.Pinning/recents are shared singletons per team.-## Rebuild architecture (`menu/` + `headless/`)--Opt-in via `TAXONOMIC_FILTER_MENU_REBUILD`. Hooks-driven, not kea-driven —-it reimplements the legacy data layer rather than wrapping it.--```text-TaxonomicFilterMenu # menu/ — dropdown + combobox + DWH/HogQL sub-flows-└── TaxonomicFilterHeadless.Root # headless/ — Root/Input/Categories/Panel- └── useTaxonomicFilter # hooks/ — orchestrator: query, active group, ordering, selectItem- └── useGroupList (per tab) # hooks/ — fetch + pagination + min-query-length- └── useTaxonomicResource # hooks/ — resolves a group's data source- └── fetchTaxonomicListPage-```--| File | Rebuild counterpart of |-| --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |-| `utils/buildTaxonomicGroups.tsx` | legacy `taxonomicGroups` selector |-| `hooks/useTaxonomicFilter.ts` | legacy `taxonomicGroupTypes` selector + ordering |-| `hooks/useGroupList.ts` + `useTaxonomicResource.ts` + `fetchTaxonomicListPage.ts` | legacy `infiniteListLogic.ts` |-| `hooks/useTaxonomicLocalOverrides.ts` | feeds logic-backed group data the kea version got for free, and reads recents and pins through kea |-| `hooks/useTaxonomicGroupsContext.ts` | the group-definition context bridge (recents are written in `useTaxonomicFilter.ts`) |-| `menu/DwhFlow.tsx` | legacy DWH config inlined in `InfiniteList.tsx` |-| `menu/TaxonomicFilterMenu.tsx` | legacy telemetry in `taxonomicFilterLogic.tsx` |--`headless/UX_SPEC.md` is the rebuild's design source of truth — update it-when locking design, then build against it.-## Things that aren't where you'd guess- **Suggested-filters aggregation lives in `infiniteListLogic`**, notdiff --git a/.agents/skills/modifying-taxonomic-filter/references/call-sites-and-blast-radius.md b/.agents/skills/modifying-taxonomic-filter/references/call-sites-and-blast-radius.mdindex 583b636d5009..1481eff8c51b 100644--- a/.agents/skills/modifying-taxonomic-filter/references/call-sites-and-blast-radius.md+++ b/.agents/skills/modifying-taxonomic-filter/references/call-sites-and-blast-radius.md@@ -20,6 +20,21 @@ rg -l '<TaxonomicFilter\b|TaxonomicPopover|TaxonomicPropertyFilter' frontend proA change ripples through every consumer of these. Run their tests beforeshipping anything broad.+Many call sites skip the wrappers and mount `TaxonomicFilter` directly, so they+always render it with no wrapper logic in front.+Examples are `ColumnConfigurator.tsx` (inline `<TaxonomicFilter>`),+`UniversalFilters.tsx` (`PureTaxonomicFilter`) and `TaxonomicBreakdownPopover.tsx`.+Search the repo for direct `<TaxonomicFilter` and `PureTaxonomicFilter` uses to+find them all before you decide which call sites a change touches.++`TaxonomicPropertyFilter` has a branch that skips the popover entirely: without+`disablePopover`, a new or empty row, or a HogQL row, sets+`showInitialSearchInline` and renders the picker inline.+With `disablePopover`, that branch is skipped and the picker always opens in a+popover.+A group row (`nestedGroup`) opens no picker at all; a leaf row inside a group+follows the same rules as any other row.+## Prop combinations to think about| Prop | Why it matters |@@ -39,4 +54,4 @@ shipping anything broad.- [ ] Add a filter inside Replay's universal filter bar- [ ] Add a cohort field condition- [ ] Open the property selector inside Web analytics conversion goal-- [ ] Check both surfaces (`legacy-pill`, `rebuild-menu`) if you touched tab rendering. Reach the rebuild via a call site that goes through `TaxonomicPopover` or `TaxonomicPropertyFilter` with `TAXONOMIC_FILTER_MENU_REBUILD` on. `ActionFilterRow` goes through `TaxonomicPopover`, so it reaches the rebuild too; only a call site with a fully separate popover implementation never renders it+- [ ] If you touched tab rendering, check a call site that goes through a wrapper (such as `TaxonomicPopover`) and one that mounts `TaxonomicFilter` directlydiff --git a/.agents/skills/modifying-taxonomic-filter/references/common-pitfalls.md b/.agents/skills/modifying-taxonomic-filter/references/common-pitfalls.mdindex 960a1bea6af5..8281a6797c0e 100644--- a/.agents/skills/modifying-taxonomic-filter/references/common-pitfalls.md+++ b/.agents/skills/modifying-taxonomic-filter/references/common-pitfalls.md@@ -5,17 +5,17 @@ component-specific traps.## "If you change X, also check Y"-| Change | Verify |-| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Tab ordering or visibility | Keyboard nav (Tab cycles), default active tab, both surfaces (`legacy-pill`, `rebuild-menu`), suggested-filters tab; mirror the change in `buildTaxonomicGroups.tsx` + `useTaxonomicFilter.ts` |-| `PROMOTED_PROPERTIES_BY_SEARCH_TERM` or sort order | `$email` and `$current_url` still at position 0 for `email` / `url` searches |-| Selectors feeding `topMatchesForQuery` | Per-tab output **and** parent `appendTopMatches` aggregation; SuggestedFilters tab still populates |-| Search input or paste handling | `inputMode` field on `taxonomic_filter_search_query` still distinguishes typed/pasted/mixed |-| `selectItem` logic | Telemetry payload (`sourceGroupType`, `wasFromRecents`, `wasFromPinnedList`, `wasQuickFilter`, `position`); recents still recorded; `onChange` still fires |-| Persistence keys (recents or pinned) | Team-id prefix still applied; items don't leak across teams |-| Filter open/close lifecycle | `cache.openedAt` / `cache.hadSelection` still set; `taxonomic filter closed` still fires with `dwellMs` and `hadSelection` |-| Adding a `TaxonomicFilterGroupType` | Group config in `taxonomicFilterLogic.tsx`, shortcut routing, telemetry includes the new type, every consumer's `taxonomicGroupTypes` prop updated |-| Reactive prop behavior in any logic | Use `propsChanged` + `afterMount`, not subscriptions (see below) |+| Change | Verify |+| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Tab ordering or visibility | Keyboard nav (Tab cycles), default active tab, suggested-filters tab |+| `PROMOTED_PROPERTIES_BY_SEARCH_TERM` or sort order | `$email` and `$current_url` still at position 0 for `email` / `url` searches |+| Selectors feeding `topMatchesForQuery` | Per-tab output **and** parent `appendTopMatches` aggregation; SuggestedFilters tab still populates |+| Search input or paste handling | `inputMode` field on `taxonomic_filter_search_query` still distinguishes typed/pasted/mixed |+| `selectItem` logic | Telemetry payload (`sourceGroupType`, `wasFromRecents`, `wasFromPinnedList`, `wasQuickFilter`, `position`); recents still recorded; `onChange` still fires |+| Persistence keys (recents or pinned) | Team-id prefix still applied; items don't leak across teams |+| Filter open/close lifecycle | `cache.openedAt` / `cache.hadSelection` still set; `taxonomic filter closed` still fires with `dwellMs` and `hadSelection` |+| Adding a `TaxonomicFilterGroupType` | Group config in `taxonomicFilterLogic.tsx`, shortcut routing, telemetry includes the new type, every consumer's `taxonomicGroupTypes` prop updated |+| Reactive prop behavior in any logic | Use `propsChanged` + `afterMount`, not subscriptions (see below) |Suggested-filters items appear in API-response order; don't assert onorder within that tab unless you control the timing.diff --git a/.agents/skills/modifying-taxonomic-filter/references/contested-decisions.md b/.agents/skills/modifying-taxonomic-filter/references/contested-decisions.mdindex 47e1c47d45ef..f71becb185b6 100644--- a/.agents/skills/modifying-taxonomic-filter/references/contested-decisions.md+++ b/.agents/skills/modifying-taxonomic-filter/references/contested-decisions.md@@ -7,9 +7,9 @@ Bring evidence, not seniority.## Should the picker reopen on the last category used?- **Current position:** no.- For an ordinary selection, legacy reopens on Suggested and the rebuild reopens on its `all` scope (`comboboxAllState` in `menu/TaxonomicFilterMenu.tsx`).- Exceptions: with no selection the rebuild opens its top-level menu; HogQL and data warehouse selections reopen in their edit flows (`resolveSelectedOpenState` in `menu/TaxonomicFilterMenu.tsx`); legacy reopens a group in `OPEN_AS_SELF_ON_REOPEN` (`types.ts`) on itself.-- **For changing:** about 24% of users who click a category tab click the same tab again on a later day (about 9% of legacy picker users), over 90 days to 2026-10-15.+ For an ordinary selection, the picker reopens on Suggested.+ Exception: it reopens a group in `OPEN_AS_SELF_ON_REOPEN` (`types.ts`) on itself.+- **For changing:** about 24% of users who click a category tab click the same tab again on a later day (about 9% of picker users), over 90 days to 2026-10-15.Source: [Query 15](refreshing-product-reality.md#15-users-who-return-to-the-same-tab).An earlier draft said 44% and 11% with no recorded query, and no definition tried since reproduces them.- **Against changing:** a remembered tab is a hidden mode.diff --git a/.agents/skills/modifying-taxonomic-filter/references/evidence-sources.md b/.agents/skills/modifying-taxonomic-filter/references/evidence-sources.mdindex 47b4c2d0e7ea..5176fa395404 100644--- a/.agents/skills/modifying-taxonomic-filter/references/evidence-sources.md+++ b/.agents/skills/modifying-taxonomic-filter/references/evidence-sources.md@@ -11,10 +11,10 @@ Use the PostHog MCP (`posthog:execute-sql`, dashboards, vision scanners, convers- Events: see [telemetry-contract](telemetry-contract.md) for names and properties.- Queries: [refreshing-product-reality](refreshing-product-reality.md).- Live values: the `taxonomic_filter_*` metrics in the data catalog, run with `posthog:data-catalog-metric-run`.-- **Good for:** sizing a problem, comparing surfaces, before and after.+- **Good for:** sizing a problem, before and after.- **Bad for:** intent.A close without a pick can be success (the user only looked) or failure.-- **Watch for:** staff traffic, `groupType` vs `sourceGroupType`, and open-level splits covering engaged legacy opens only.+- **Watch for:** staff traffic, `groupType` vs `sourceGroupType`, and open-level splits covering engaged opens only.## The health dashboarddiff --git a/.agents/skills/modifying-taxonomic-filter/references/failure-modes.md b/.agents/skills/modifying-taxonomic-filter/references/failure-modes.mdindex 9bacb4d927a9..77629709923d 100644--- a/.agents/skills/modifying-taxonomic-filter/references/failure-modes.md+++ b/.agents/skills/modifying-taxonomic-filter/references/failure-modes.md@@ -34,27 +34,22 @@ Most empty searches are real words that exist somewhere else.## 3. Poor recovery after an empty result- **Signal:** the health dashboard's recovery tile fell from ~46% to ~39% over three months, while the empty-result rate stayed flat.-- **Caution:** that tile pools both surfaces, and they record different empty states.- A change in the rebuild share can move it on its own.- Check each surface with query 12 in [refreshing-product-reality](refreshing-product-reality.md) before you call it a worse empty state.- Today legacy recovers ~26% and the rebuild ~16%.-- **Fix direction:** same as above, and measure recovery directly.+- **Fix direction:** measure recovery directly.See [measuring-changes](measuring-changes.md).## 4. Failed requests-- **Signal:** `taxonomic filter fetch failed` ~0.2 times per 100 legacy search queries (query 10).+- **Signal:** `taxonomic filter fetch failed` ~0.2 times per 100 search queries (query 10).One search can send several events, so this is not a share of failed searches.The health dashboard shows ~2%, but it divides every failure, first loads included, by timed searches, so it overstates the rate.Events, cohorts, person properties and flags fail most.Some pseudo-category groups fail more often than they are picked.First-load failures have only been captured since 2026-09-13, so compare from then on.- **Why it matters:** a failure that looks like loading or like "no results" sends users away, and a 403 must not look like a slow request.-- **Current state:** both surfaces end loading and show "Couldn't load results" with a retry, except for a 403.- Legacy does it in `InfiniteList.tsx` (`InfiniteListErrorState`), the rebuild in `menu/Combobox.tsx` from `showErrorState` in `hooks/useGroupList.ts`.- Legacy's `remoteFetchForbidden` (`infiniteListLogic.ts`) shows an access-denied message with no retry for a `permission_denied` 403.- The rebuild has no equivalent, so a 403 there shows the generic retry instead.- Keep the two in parity, and reduce the failures themselves.+- **Current state:** the picker ends loading and shows "Couldn't load results" with a retry, except for a 403.+ `InfiniteList.tsx` (`InfiniteListErrorState`) handles this, fed by `infiniteListLogic.ts`.+ `remoteFetchForbidden` (`infiniteListLogic.ts`) shows an access-denied message with no retry for a `permission_denied` 403.+ Reduce the failures themselves.See [performance](performance.md).## 5. Slow tails on a few groups@@ -75,7 +70,7 @@ Most empty searches are real words that exist somewhere else.- **Signal:** the largest ticket theme.Popover placement, options that can't be clicked or scrolled, crashes in `infiniteListLogic`, and crashes in data-warehouse flows.-- **Fix direction:** reproduce on the reporter's surface first (see [surfaces-and-mirroring](surfaces-and-mirroring.md)).+- **Fix direction:** reproduce at the reporter's call site first (see [call-sites](call-sites-and-blast-radius.md)).Add an RTL regression test at that call site.## 8. The weakest big tab: person propertiesdiff --git a/.agents/skills/modifying-taxonomic-filter/references/feature-inventory.md b/.agents/skills/modifying-taxonomic-filter/references/feature-inventory.mdindex 5dafdb302135..476141a4d4c8 100644--- a/.agents/skills/modifying-taxonomic-filter/references/feature-inventory.md+++ b/.agents/skills/modifying-taxonomic-filter/references/feature-inventory.md@@ -23,7 +23,7 @@ Status meanings:| Event properties tab | Large | Improve | Ranking: selected items sit far down the list. || Person properties tab | Large, ~64% of closes on it pick (query 13, final tab) | Improve | Weakest big tab. || Empty-result state | ~5 per 100 search queries (query 13) | Fix | Should show matches in other groups. This snapshot excludes Suggested; new clients record All-tab empties. |-| Fetch error handling | ~0.2 failure events per 100 search queries (query 10) | Keep | Both surfaces show an error with retry. Keep them in parity. |+| Fetch error handling | ~0.2 failure events per 100 search queries (query 10) | Keep | Shows an error with retry. || Persons search latency | p90 ~4s | Fix | Slowest group. || Custom key for unseen properties | Ticket theme | Fix | Flags and cohorts especially. || Pin toggle | ~4% of selections come from pins | Keep | Cheap. |@@ -34,7 +34,6 @@ Status meanings:| Search intent switch banner | ~1 in 6 shown banners lead to a switch | Decide from its experiment | Promotion of the predicted group happens without the banner. || Category rail docking | ~1% of closes have docking on (query 13, preference) | Keep | Pick rate ~79% docked vs ~86% undocked. || Include stale toggle | Small, steady | Keep | Cheap. |-| Rebuild menu (`TAXONOMIC_FILTER_MENU_REBUILD`) | Some customers still see it | Finish or turn off | Selection rate looks lower than legacy, but the rebuild counts every close and legacy only engaged ones. |## Before removing anything@@ -42,7 +41,7 @@ Status meanings:A tab can be unused while its items are picked every day through Suggested.2. Separate "rarely used" from "failing".If a group's fetches fail, fix them before judging use.-3. Check both surfaces and every call site that passes the group.+3. Check every call site that passes the group.See [call-sites-and-blast-radius](call-sites-and-blast-radius.md).4. Check for a running experiment on the feature.5. Keep the telemetry event (or retire it on purpose) so dashboards don't silently go flat.diff --git a/.agents/skills/modifying-taxonomic-filter/references/measuring-changes.md b/.agents/skills/modifying-taxonomic-filter/references/measuring-changes.mdindex 301b0d18abaa..56f0d2ce0bc2 100644--- a/.agents/skills/modifying-taxonomic-filter/references/measuring-changes.md+++ b/.agents/skills/modifying-taxonomic-filter/references/measuring-changes.md@@ -23,7 +23,6 @@ The health dashboard (see [evidence-sources](evidence-sources.md)) has most of t- Any ordering, default or promotion change: watch row-0 share, opens ending in a selection, and the Suggested view's share of picks.- Any change to a group: watch that group's item use (`sourceGroupType`), not just its tab use.-- Any change in one surface: compare both surfaces on the shared events.## Experimentsdiff --git a/.agents/skills/modifying-taxonomic-filter/references/performance.md b/.agents/skills/modifying-taxonomic-filter/references/performance.mdindex f9b35804dff3..bf5e8921aa4d 100644--- a/.agents/skills/modifying-taxonomic-filter/references/performance.md+++ b/.agents/skills/modifying-taxonomic-filter/references/performance.md@@ -6,7 +6,6 @@ For the full profiling workflow, use [`profiling-slow-api-endpoints`](../../prof## Where users waitMeasured with `taxonomic filter search latency` (`time_to_see_data_ms`).-Only the legacy picker sends it, so these numbers say nothing about the rebuild.Refresh with query 9 in [refreshing-product-reality](refreshing-product-reality.md).- The median search is fast (~200ms) in every large group.@@ -19,20 +18,16 @@ Refresh with query 9 in [refreshing-product-reality](refreshing-product-reality.## A failed request must show as an error-`taxonomic filter fetch failed` fires ~0.2 times per 100 legacy search queries (query 10).+`taxonomic filter fetch failed` fires ~0.2 times per 100 search queries (query 10).One search can send several events, so this is not a share of failed searches.The health dashboard shows ~2%, but it divides every failure, first loads included, by timed searches, so it overstates the rate.Cohorts, events, person properties and flags make up most of the failures.-Both surfaces end loading on a failure and show "Couldn't load results" with a retry, except for a 403.+Loading ends on a failure and shows "Couldn't load results" with a retry, except for a 403.A 403 must not look like "no results".-- Legacy: `InfiniteListErrorState` in `InfiniteList.tsx`, fed by `infiniteListLogic.ts`.+- `InfiniteListErrorState` in `InfiniteList.tsx`, fed by `infiniteListLogic.ts`.Its `remoteFetchForbidden` shows an access-denied message with no retry for a `permission_denied` 403.-- Rebuild: the error block in `menu/Combobox.tsx`, fed by `showErrorState` from `hooks/useGroupList.ts`.- `useGroupList` keeps `showErrorState` and `showEmptyState` apart, so a failure never reads as an empty result.- It has no forbidden handling, so a 403 shows the generic retry instead of legacy's access-denied message.-- Keep `taxonomic filter fetch failed` firing with `groupType`, `searchQuery` and `surface` on both surfaces.- The rebuild sends no `groupType` on its `all`, `recent` and `pinned` scopes, so per-group analysis stays on legacy.+- Keep `taxonomic filter fetch failed` firing with `groupType` and `searchQuery`.## Backend search plan@@ -61,7 +56,7 @@ Measure projects on both sides of the threshold.Do not restate its loading rules here.For performance work, measure the time until the first usable result.-Check both `infiniteListLogic.ts` and `hooks/useGroupList.ts` because the legacy and rebuild paths implement loading separately.+Check `infiniteListLogic.ts` for how loading is implemented.## Verification@@ -69,7 +64,7 @@ Check both `infiniteListLogic.ts` and `hooks/useGroupList.ts` because the legacy- Compare both Postgres predicate forms with safe production `EXPLAIN` queries.- State whether each measured query used a warm or cold cache.- Run the definition API tests against Postgres.-- Test the legacy and rebuild loading paths, including a failed request.+- Test the loading path, including a failed request.- After shipping, compare p90 and p99 by group and the fetch failure rate.Result tests alone do not protect the plan choice because both plans return the same rows.diff --git a/.agents/skills/modifying-taxonomic-filter/references/product-reality.md b/.agents/skills/modifying-taxonomic-filter/references/product-reality.mdindex 872c114780eb..cb9db26f9b70 100644--- a/.agents/skills/modifying-taxonomic-filter/references/product-reality.md+++ b/.agents/skills/modifying-taxonomic-filter/references/product-reality.md@@ -14,21 +14,19 @@ The numbers below are a snapshot for orientation: before a figure drives a decis- **~85% of engaged opens end in a selection.** p50 dwell ~5.5s, p90 ~23s.Most engaged opens are quick and successful.- "Engaged" means the user interacted.- The legacy picker sends `taxonomic filter closed` only when `hadInteraction` is true, so an open dismissed untouched is not counted.+ The picker sends `taxonomic filter closed` only when `hadInteraction` is true, so an open dismissed untouched is not counted.The rate over all opens is lower.- The previous figure (~34%, May 2026) came from before close telemetry was complete.Don't compare the two numbers as a trend.- **Position is everything.**Row 0 takes ~52% of picks, row 1 ~23%, row 2 ~10%.About 85% of picks are in the top three rows.- These are legacy figures: the rebuild's `all` scope counts recents and pinned rows in its positions, so its numbers do not compare.-- **~96% of engaged opens never select a real category** (7-day sample, legacy picker, sessions split at each `taxonomic filter closed`).-- **Suggested carries about 70% of selections** (legacy picker).+- **~96% of engaged opens never select a real category** (7-day sample, sessions split at each `taxonomic filter closed`).+- **Suggested carries about 70% of selections.**Just over half of those are recents.## Selection paths-Legacy picker only (query 5 leaves out `rebuild-menu`).These overlap: one pick can be both searched and from recents.| Path | Share of selections |@@ -99,8 +97,7 @@ Detail in [failure-modes](failure-modes.md).- Opens with a category pick end in a selection ~62% of the time, vs ~85% without one.- Most empty searches are ordinary words in the wrong scope.- Recovery within 30s of an empty result fell from ~46% to ~39% (Jul to Oct 2026, health dashboard session tile) while the empty-result rate stayed flat.- The tile pools both surfaces, so check each one with query 12 before you read it as a worse empty state.-- About 0.2 fetch failure events per 100 legacy search queries (query 10).+- About 0.2 fetch failure events per 100 search queries (query 10).One search can send several, so this is not a share of failed searches.The health dashboard shows ~2%, but it divides every failure, first loads included, by timed searches, so it overstates the rate.Cohorts, events, person properties and flags make up most of the failures.@@ -127,7 +124,7 @@ Customers don't name it as the problem.## Caveats-- The open-level splits cover engaged legacy opens only.+- The open-level splits cover engaged opens only.A picker that stays mounted can merge several opens into one, so treat those ratios as direction.- Some dashboard tiles include staff traffic.Filter it when it matters.diff --git a/.agents/skills/modifying-taxonomic-filter/references/refreshing-product-reality.md b/.agents/skills/modifying-taxonomic-filter/references/refreshing-product-reality.mdindex 5f6f1b43f7fd..44170fc7f8bd 100644--- a/.agents/skills/modifying-taxonomic-filter/references/refreshing-product-reality.md+++ b/.agents/skills/modifying-taxonomic-filter/references/refreshing-product-reality.md@@ -18,6 +18,10 @@ The metrics are proposed until a person approves them in the data catalog, so trThe metric and the query here hold the same SQL.When you change one, change the other in the same PR (`posthog:data-catalog-metric-update` for the metric).+The rebuilt menu is removed from the code, but its `rebuild-menu` events stay in the data until they age out of the query windows.+That is why these queries still split or filter by `surface`.+Once no window holds a `rebuild-menu` row, simplify a query and its metric together.+| Query | Metric || ----- | ---------------------------------------------------- || 4 | `taxonomic_filter_engaged_selection_rate_by_surface` |diff --git a/.agents/skills/modifying-taxonomic-filter/references/surfaces-and-mirroring.md b/.agents/skills/modifying-taxonomic-filter/references/surfaces-and-mirroring.mddeleted file mode 100644index 8c437f6a30e9..000000000000--- a/.agents/skills/modifying-taxonomic-filter/references/surfaces-and-mirroring.md+++ /dev/null@@ -1,76 +0,0 @@-# Surfaces and mirroring--There are two live surfaces, and the rebuild is a parallel reimplementation of the legacy data and group layer, not a skin over it.-A behavior change usually has to land in both, or the two arms diverge.--## Two surfaces--A feature flag and a per-user toggle select between them in the shared wrappers.-The flag `TAXONOMIC_FILTER_MENU_REBUILD` makes the rebuild available.-The user's saved choice in `taxonomicMenuPreferenceLogic.useNewMenu` (the "Switch to the classic filter" toggle) then decides which one renders.-It defaults to on, so a flag-on user gets the rebuild until they switch back.-A bug report that doesn't reproduce locally is almost always a surface mismatch.-Confirm which surface the reporter is on first: most `taxonomic filter *` events carry `surface` (see [telemetry-contract](telemetry-contract.md) for the exceptions).--| Surface | When it renders | What renders |-| -------------- | ----------------------------------------- | --------------------------------------------- |-| `legacy-pill` | flag off, or flag on and `useNewMenu` off | classic picker with a category dropdown |-| `rebuild-menu` | flag on and `useNewMenu` on | ground-up rewrite in `menu/` over `headless/` |--- **legacy-pill** is the classic picker (`taxonomicFilterLogic.tsx` + `InfiniteList`) with a suffix category dropdown.- A person can pin the category rail from that dropdown.-- **rebuild-menu** is a fresh implementation: the `menu/` dropdown and combobox UI on top of `headless/` (a hooks-based filter panel).- It does **not** route through `taxonomicFilterLogic` or `infiniteListLogic`.- It has its own group definitions, fetch, pagination and ordering.- See `headless/UX_SPEC.md` for its design source of truth.- Some customers still see it, so treat it as live.--Two **shared consumer wrappers** choose a surface: `TaxonomicPopover.tsx` and `PropertyFilters/components/TaxonomicPropertyFilter.tsx`.-Both check `TAXONOMIC_FILTER_MENU_REBUILD` and `useNewMenu`, then render `<TaxonomicFilterMenu>` or the legacy `<TaxonomicFilter>`.--Some call sites mount the rebuild directly and skip both checks.-Today that is Error Tracking's issue filters (`products/error_tracking/frontend/components/IssueFilters/FilterGroup.tsx`), which mounts `TaxonomicFilterHeadless.Root` and `TaxonomicFilterMenu`.-Every user there is on the rebuild, whatever the flag or toggle says.-Find others with a search for direct imports of `menu/TaxonomicFilterMenu` or `headless` outside `TaxonomicFilter/` and `TaxonomicPopover/`.--A call site reaching one of those wrappers can still land on the legacy path.-`TaxonomicPopover` renders the rebuild only when `newMenuSupportsCallSite` holds (`!allowClear && closeOnChange && ref == null`), because the rebuilt menu can't honor those three capabilities.-So "does this reach the rebuild?" depends on the wrapper and the props that call site passes.-`ActionFilterRow` goes through `TaxonomicPopover` and passes none of the three, so it does reach the rebuild.-`TaxonomicPropertyFilter` has a legacy branch too: without `disablePopover`, a new or empty row, or a HogQL row, sets `showInitialSearchInline` and renders the legacy picker inline, whatever the flag and toggle say.-With `disablePopover`, that branch is skipped and the flag and toggle decide.-A group row (`nestedGroup`) opens no picker at all; a leaf row inside a group follows the same rules as any other row.-Without `disablePopover`, only an existing, non-HogQL row reaches the flag and toggle check.--Many call sites skip the wrappers and mount the legacy picker directly, so they always render legacy.-Examples are `ColumnConfigurator.tsx` (inline `<TaxonomicFilter>`), `UniversalFilters.tsx` (`PureTaxonomicFilter`) and `TaxonomicBreakdownPopover.tsx`.-Search the repo for direct `<TaxonomicFilter` and `PureTaxonomicFilter` uses to find them all before you decide which surfaces a change touches.--**Touching tab or group rendering means testing both surfaces.**--## Mirroring changes--The same concern lives in two files.-There is **no lint rule or test** enforcing parity; the only guard is "Mirrors the legacy…" comments.-When you change one, change the other, or tell the reviewer you couldn't.--| Concern | Legacy | Rebuild |-| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |-| Group definitions (endpoint, excluded props, group meta) | `taxonomicFilterLogic.tsx` `taxonomicGroups` selector | `utils/buildTaxonomicGroups.tsx` |-| Group ordering + SuggestedFilters injection | `taxonomicFilterLogic.tsx` `taxonomicGroupTypes` selector | `hooks/useTaxonomicFilter.ts` `resolveTaxonomicGroupTypes` |-| Per-tab fetch / pagination / min-query-length | `infiniteListLogic.ts` | `hooks/useGroupList.ts` + `useTaxonomicResource.ts` + `fetchTaxonomicListPage.ts` |-| Fetch error state | `InfiniteList.tsx` `InfiniteListErrorState` + `infiniteListLogic.ts` | `menu/Combobox.tsx` error block + `hooks/useGroupList.ts` `showErrorState` |-| Data-warehouse config flow | inline in `InfiniteList.tsx` | `menu/DwhFlow.tsx` |-| `taxonomic filter item selected` / `closed` telemetry | `taxonomicFilterLogic.tsx` | `menu/TaxonomicFilterMenu.tsx` |-| Standalone Recent and Pinned entries | `taxonomicFilterLogic.tsx` `taxonomicGroupTypes` selector (`recent_filters`, `pinned_filters`) | `menu/TaxonomicFilterMenu.tsx` (menu entries) + `menu/Combobox.tsx` (`recent` and `pinned` scopes) |-| New `TaxonomicFilterGroupType` enum value | `types.ts` (shared), then add group config in **both** rows above | |-| Logic-backed group data (Actions, Dashboards, …) | already in kea | also register in `hooks/useTaxonomicLocalOverrides.ts` |--**Shared, change once:** `types.ts` (the enum), `utils/promoteProperties.ts` (`PROMOTED_PROPERTIES_BY_SEARCH_TERM`), `recentTaxonomicFiltersLogic.ts` and `taxonomicFilterPinnedPropertiesLogic.ts`.-The rebuild reads recents and pins through these via a bridge; it doesn't fork them.--`redistributeTopMatches` is legacy-only: it lives in `taxonomicFilterLogic.tsx` and the rebuild never calls it.--Suggested ordering is shared behavior: both surfaces drop SuggestedFilters when there is one substantive group, and lead with it when there are two or more (legacy `resolveSuggestedFiltersGroup` in `taxonomicFilterLogic.tsx`, rebuild `resolveTaxonomicGroupTypes` in `hooks/useTaxonomicFilter.ts`).-Keep the two in parity when you change it.-Where a real divergence exists, it is documented next to the code; preserve those, and don't "fix" them into parity.diff --git a/.agents/skills/modifying-taxonomic-filter/references/telemetry-contract.md b/.agents/skills/modifying-taxonomic-filter/references/telemetry-contract.mdindex 1489ec8faac3..22a9abce4596 100644--- a/.agents/skills/modifying-taxonomic-filter/references/telemetry-contract.md+++ b/.agents/skills/modifying-taxonomic-filter/references/telemetry-contract.md@@ -10,9 +10,8 @@ When it fails, update this file in the same PR.- **Renaming or repurposing silently** is the worst case.Dashboards keep working and start lying.-The legacy stamp `legacy-pill` comes from `legacyTaxonomicSurface()` in `taxonomicFilterSurface.ts`.-The rebuild stamps `rebuild-menu` from `TAXONOMIC_FILTER_SURFACE` in `menu/types.ts`.-Only the events marked "with `surface`" below carry it.+Every event here carries `surface = 'legacy-pill'`, stamped by `legacyTaxonomicSurface()` in `taxonomicFilterSurface.ts`.+Only the events marked "with `surface`" below carry the property at all.Older data also has `legacy-control` and empty values.A filter such as `surface = 'legacy-pill'` drops every row without the property, so check the list before you filter.@@ -28,52 +27,31 @@ To judge whether a group's items are used, count `sourceGroupType`.To judge whether a tab is used, count `groupType`.Mixing them up makes reachable groups look unused.-This holds for legacy only.-The rebuild sends no `groupType` for its `all`, `recent` and `pinned` scopes (`telemetryGroupType` in `menu/Combobox.tsx`), so its data cannot tell those three apart.-In a query over both surfaces, label an empty `groupType` from `rebuild-menu` as an unknown meta-scope.-Do not fold it into Suggested or All, or treat it as Recent: the standalone Recent and Pinned picks are in there too.-Telling the scopes apart needs new telemetry.-HogQL and data warehouse commits (`menu/HogQLEditor.tsx`, `menu/DwhFlow.tsx`) also send no `groupType`, because they commit without a selection context.-They still send `sourceGroupType`, so split those rows out by `sourceGroupType` before you label the rest as a meta-scope.+## Events, with `surface`-## Shared events (both surfaces)--Keep these comparable across arms.-Add a property to both emitters or neither.-All carry `surface` on both surfaces, except `include stale toggled`, which carries it on the rebuild only.--- `taxonomic filter closed`: `dwellMs`, `hadSelection`, `categoryRailDocked`.- Legacy also sends `groupType`; the rebuild omits it because there is no single active tab at close.- Legacy sends it only when `hadInteraction` is true.- The rebuild sends it on every close, so their selection rates have different denominators.+- `taxonomic filter closed`: `dwellMs`, `hadSelection`, `categoryRailDocked`, `groupType`.+ Sent only when `hadInteraction` is true.- `taxonomic filter item selected`: `groupType`, `sourceGroupType`, `wasFromRecents`, `wasFromPinnedList`, `wasQuickFilter`, `hadSearchInput`, `position`, `query`, `wasStale`, `wasUrlContainsShortcut`.- Legacy sends `wasUrlContainsShortcut` only on a quick filter, with `filterName`, `propertyKey`, `operator`, `filterValue`, `propertyFilterType` and `eventName`.- The rebuild always sends `wasUrlContainsShortcut` and none of the others.+ `wasUrlContainsShortcut` is sent only on a quick filter, with `filterName`, `propertyKey`, `operator`, `filterValue`, `propertyFilterType` and `eventName`.- `taxonomic_filter_search_query`: `searchQuery`, `groupType`, `inputMode`, `pastedFraction`, `excludeStale`.- `taxonomic filter empty result`: `groupType`, `searchQuery`, `scope`.`scope` is `all` for the aggregate All view and `category` for a content category.- The rebuild also uses `recent` and `pinned` for those scopes.- Legacy All sends it when its visible empty state renders after contributing lists settle without a fetch failure.- Its `groupType` remains `suggested_filters`; rebuild All keeps `groupType` unset.+ Sent for the All view when its visible empty state renders after contributing lists settle without a fetch failure.+ Its `groupType` remains `suggested_filters` for the All view.Empty or whitespace-only searches do not count.Repeated renders of the same trimmed query do not send another event.- Legacy content categories send it from successful remote searches on the active tab.- Older legacy data has no All-tab empty events, and older events have no `scope`.+ Content categories send it from successful remote searches on the active tab.+ Older data has no All-tab empty events, and older events have no `scope`.Compare periods with the same coverage.-- `taxonomic filter fetch failed`: `groupType`, `searchQuery`, and on legacy `forbidden` (true when the request was refused with a 403).- Each surface sends it once per group or scope and query while the request keeps failing.- Legacy has also sent it on first-load failures since 2026-09-13, so legacy rates from before then are not comparable.- The rebuild sends no `groupType` on its `all`, `recent` and `pinned` scopes.+- `taxonomic filter fetch failed`: `groupType`, `searchQuery`, `forbidden` (true when the request was refused with a 403).+ Sent once per group and query while the request keeps failing.+ Sent on first-load failures since 2026-09-13, so rates from before then are not comparable.- `taxonomic filter include stale toggled`: `includeStaleEvents`, `groupType`, `searchQuery`.- Only the rebuild sends `surface` on this one.--## Legacy only, with `surface`-- `taxonomic filter search latency`: `groupType`, `searchQuery`, `resultCount`, `time_to_see_data_ms`, `revealedBy`, `pendingGroupTypes`.A category tab sends it when its own fetch lands, and `time_to_see_data_ms` is the fetch time.The All tab sends it when its rows reveal, with `groupType: suggested_filters`, `revealedBy` and `pendingGroupTypes`.- There `time_to_see_data_ms` runs from the last keystroke, so it includes the input debounce. Compare the two only by `groupType`.- The rebuild does not send it yet (see `hooks/useGroupList.ts`).+ There `time_to_see_data_ms` runs from the last keystroke, so it includes the input debounce.+ Compare the two only by `groupType`.- `taxonomic filter search intent predicted`: `query`, `activeTab`, `predictedGroupType`, `confidence`, `isConfident`, `suggestsSwitch`, `wouldPromote`, `promptVersion`, `source`, `variant`, `inTime`, `shown`.The banner funnel in [refreshing-product-reality](refreshing-product-reality.md) reads `variant` and `shown`.- `taxonomic filter search intent switched`: `fromGroupType`, `toGroupType`.@@ -85,45 +63,21 @@ All carry `surface` on both surfaces, except `include stale toggled`, which carrRead the event match events as a funnel: answered, then suggested, then selected.-## Legacy only, without `surface`+## Events, without `surface`- `taxonomic filter add filter clicked`: `eventName`.Fires only when a property filter row opens with no valid filter yet.Most opens do not send it, so do not use it to split sessions into opens.- Split after each legacy `taxonomic filter closed` instead.+ Split after each `taxonomic filter closed` instead.- `taxonomic filter category selected`: `groupType`, `eventName`.- `taxonomic filter category dropdown opened`: `variant`.- `taxonomic filter category rail toggled`: `docked`.- `taxonomic filter event match answered`: `outcome`.Emitted server side.--## Both surfaces, without `surface`--These come from the shared `taxonomicFilterPinnedPropertiesLogic.ts`, which both surfaces call.-Nothing on them says which surface sent them.-- `taxonomic filter pin toggled`: `groupType`, `value`, `pinned`.- A rebuild pin click sends `taxonomic filter menu pin toggled` and then this one too, so do not add the two together.+ Sent from the shared `taxonomicFilterPinnedPropertiesLogic.ts`.- `taxonomic filter default pins seeded`: `values`.-## Rebuild only, without `surface`--Every event here comes from the rebuild, so no `surface` filter is needed.-Do not add `surface = 'rebuild-menu'` to a query on them: it returns no rows.--- `taxonomic filter menu opened`: `openedTo`, `hadSelection`, `triggerLabel`, `msSinceLastClose`, `reopenedQuickly`.-- `taxonomic filter menu drilled`: `fromState`, `toState`.-- `taxonomic filter menu closed`: `dwellMs`, `hadCommit`, `lastState`.-- `taxonomic filter menu option clicked`: `option`.-- `taxonomic filter menu item selected`: `groupType`, `hadSearchInput`, `query`, `hadExtras`, `fromState`, `msSinceOpen`.-- `taxonomic filter menu category changed`: `fromChip`, `toChip`, `via`, and `direction` when `via` is `tab`.-- `taxonomic filter menu pin toggled`: `groupType`, `pinned`.--## Toggle, either surface, without `surface`--- `taxonomic filter menu preference changed`: `useNewMenu`.- It comes from the classic/new toggle and fires on either surface for users who have the rebuild flag.-## Before changing telemetry1. Search dashboards and insights for the event and property (`system.insights` via the PostHog MCP).diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 10749503f1b7..bad6ccdbeeca 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3816,42 +3816,6 @@ snapshots:hash: v1.k794b7964.c86259cd31b7314e2501ce1f5d2d9df90c71d89973451bc4fc7dc75f804f2ab0.0rNsoV08CBVe1fMHn0PdC9SQFdUUuvcWjZxuegKJDi0filters-taxonomic-filter--three-groups-default-layout--light:hash: v1.k794b7964.3a912cff1eae56feebdbc21446fdc3e61ac0d509204d8ad721b3aceb70720772.W1NBO4lj4EJOyXLHzqNk2WNFsya5ck4u27neOIPYc5M- filters-taxonomic-filter-menu-rebuild--cohorts-with-realtime-states--dark:- hash: v1.k794b7964.932df90594833f5d2039f583a662cc2aa42e72c7ad7f13f3075bd06a0119d077.O-c_P7j4v0FdBkmPUMcU5gjN-BPns7MvdvhkXEGQxcE- filters-taxonomic-filter-menu-rebuild--cohorts-with-realtime-states--light:- hash: v1.k794b7964.fe2e8e9e5341a9f15b78620d2fed44cd829a0dfb29249d4c72809fd91295f87a.K0E_-NAOF_HgRwpV5XJvo2HvQhUqCKwQTIwbWJfw2KQ- filters-taxonomic-filter-menu-rebuild--data-warehouse-config--dark:- hash: v1.k794b7964.4131254839bb13aed4af1f6cb7197cf9c23539c405c11ac33e2729bcaa30b505.osrHyuzzbrQgnurVXZQMRBdxj1_TxCyCvK-4eXXJYkE- filters-taxonomic-filter-menu-rebuild--data-warehouse-config--light:- hash: v1.k794b7964.dcd5a2635c692f7ba3d17bf648711d6abb00531869fa3c40b24b22f97a545bad.1BN3K_I1jp0O5lErsnd-6MsG1qjvxJoR4ene2gme1IA- filters-taxonomic-filter-menu-rebuild--events-and-actions--dark:- hash: v1.k794b7964.ef43eb3da4a924d2cabdd57184ff5e7ac3ddb2203e48109472244ea9a3294817.n_h4z87XQA0cCMJTN9qR-4cDmuE_lIqPkjbdNwgnfxo- filters-taxonomic-filter-menu-rebuild--events-and-actions--light:- hash: v1.k794b7964.5b682fa1b0befa226a706d2b8969abd58b176b4fc8a401892aade490b18a5942.XxX5GA9ck4oTCHHluStLXKIapfDGLSOx7GTjtkKxEtQ- filters-taxonomic-filter-menu-rebuild--hog-ql-only--dark:- hash: v1.k794b7964.69e5e2b843786e066cda98b2716f6bd5c929fcaf64c64be7ccb31a2417deada5.Z06YMmdo99SFz5_zOXppe1gIpxRTWBygg8zzbRcEHt0- filters-taxonomic-filter-menu-rebuild--hog-ql-only--light:- hash: v1.k794b7964.cbdda899fb6d823e98d1e8220fe862d2899537a4b9af0d2bcfda4acf1ceeffb7.uQv7dakLBmSnoYZaPIVaprG2zWYLnLjHAl95xWYmBLA- filters-taxonomic-filter-menu-rebuild--pre-selected-event--dark:- hash: v1.k794b7964.26ab46293c0477f4697ce98769db9eea0d31cfe33f0065f60d5d4534eb4dc1bf.3opeTVGtSuWSSBIBGVAY_epFt16T8XUyXxs8_PywsvU- filters-taxonomic-filter-menu-rebuild--pre-selected-event--light:- hash: v1.k794b7964.c1dcc778f84c7c4f4d4eeff1b3d9e8b4c52b02ac83dfc53500a8d6e4c4bb6862.Dt4PRKWrKTGAnqzvGkYYuSVn1122qoEBd8TPllGsa9E- filters-taxonomic-filter-menu-rebuild--pre-selected-hog-ql--dark:- hash: v1.k794b7964.d65e6e0e3eccc8c7a5039396da5731353407d74636686994a20801bc4fc7d0cd.9MRXkY2Go8Yym7ckr76J-9SwrWOhnTeHSCXDgXHi8IA- filters-taxonomic-filter-menu-rebuild--pre-selected-hog-ql--light:- hash: v1.k794b7964.6cb0dd8110519cf60b5da75bdb564c8e7f9f3403abc88f44ce6c46ae58e7c17e.a1Uk5lblEQQ6dxO6caFG0AsNisJKIOnFq_ewGmFNMpM- filters-taxonomic-filter-menu-rebuild--properties--dark:- hash: v1.k794b7964.2869fb83b6f6a3989b5d8cedc670cd9cb001f72c5be89338876badd78de22377.NBG0AcwD53xEg1qoiy9zTw4LTC-yA9ftbbluudmoTm8- filters-taxonomic-filter-menu-rebuild--properties--light:- hash: v1.k794b7964.60454016b8dffe18e0d8498c16a6cc7cd64fecdc9c16a61daad4b8ab20f626be.lJvLHUQIWH3PM3LEgkodi9xmJc5IB5n6BWm6pFgyjGs- filters-taxonomic-filter-menu-rebuild--recents-bare-key-expansion--dark:- hash: v1.k794b7964.35f57331fb0a726f3f1ecd224276be443302eb3f34a7df370222931502cc82d2.WthryKSq2B5c3eVPZ15eanxkkCNwsnsz-OCNRvyydik- filters-taxonomic-filter-menu-rebuild--recents-bare-key-expansion--light:- hash: v1.k794b7964.2f192bfcd2410a4955c3881c9510fe9a0789f4eda306d025d9d9325a96877098.eY9iXd5t-3AoGLo4CiAZFOF01cqKcqxg-diZIfyl6eA- filters-taxonomic-filter-menu-rebuild--series-plus-data-warehouse--dark:- hash: v1.k794b7964.e575a6fe0650de8136525ca833e523aee2834ab250e698ca5a291582058f1225.CzFI0b5Zsxpc2aqMQ81c2UBIlP9f3wD99-Y_vf9nNUY- filters-taxonomic-filter-menu-rebuild--series-plus-data-warehouse--light:- hash: v1.k794b7964.55ca200a0ae83e772ec48d184e693dd4d839c90e0cfc4a0abe7ad756515bf2b6.6QQUHueNRsfm1BE7DWUPkBeN4TnMk5VvMeHO1VklBZIfilters-taxonomicpopover--multiple-categories--dark:hash: v1.k794b7964.03b4b270a02f86dfb9bafd37252eb9bdda9019f17d1f891a1892d93de57972ba.PtANH0fO47BsG8cHofR47rd39UNILQKtU-mC2Vxwuvkfilters-taxonomicpopover--multiple-categories--light:diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.stories.tsx b/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.stories.tsxindex c7d615eed48b..733f201abcc9 100644--- a/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.stories.tsx+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.stories.tsx@@ -248,9 +248,7 @@ export const WithoutTimestamps: Story = {// Covers the column-field pickers shown when a data warehouse table is// selected as an insight series in the legacy TaxonomicFilter path// (`DefinitionPopoverContents` → `DefinitionView` DWH branch). Pins the-// `pill` variant of the category-dropdown experiment. The rebuild variant-// of the same view is covered by `DataWarehouseConfig` in-// `TaxonomicFilterMenu.stories.tsx`.+// `pill` variant of the category-dropdown experiment.const mockDataWarehouseTable = {id: 'dwh-table-1',diff --git a/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx b/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsxindex 8a991a911e95..f01a6e22e240 100644--- a/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx+++ b/frontend/src/lib/components/PropertyFilters/PropertyFilters.tsx@@ -70,12 +70,6 @@ export interface PropertyFiltersProps {addFilterDocLink?: stringoperatorAllowlist?: OperatorValueSelectProps['operatorAllowlist']hogQLGlobals?: Record<string, any>- /**- * `'input'` renders the replay-style input-box add-filter trigger; `'button'`- * (the default) renders a button. Only has an effect on the rebuild menu- * (`TAXONOMIC_FILTER_MENU_REBUILD`).- */- triggerVariant?: 'button' | 'input'staticValueOptions?: PropertyFilterInternalProps['staticValueOptions']renderOperatorValueSelect?: PropertyFilterInternalProps['renderOperatorValueSelect']/** Override inferred property definitions for contexts where one event key is polymorphic. */@@ -134,7 +128,6 @@ export function PropertyFilters({addFilterDocLink,operatorAllowlist,hogQLGlobals,- triggerVariant = 'button',staticValueOptions,renderOperatorValueSelect,propertyDefinitionsOverride,@@ -252,7 +245,6 @@ export function PropertyFilters({editable={editable}operatorAllowlist={operatorAllowlist}hogQLGlobals={hogQLGlobals}- triggerVariant={triggerVariant}staticValueOptions={staticValueOptions}renderOperatorValueSelect={renderOperatorValueSelect}propertyDefinitionsOverride={propertyDefinitionsOverride}diff --git a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.triggerVariant.test.tsx b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.triggerVariant.test.tsxdeleted file mode 100644index 14173e289385..000000000000--- a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.triggerVariant.test.tsx+++ /dev/null@@ -1,97 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, screen, waitFor } from '@testing-library/react'-import { Provider } from 'kea'--import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'--import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { groupsModel } from '~/models/groupsModel'-import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'-import { initKeaTests } from '~/test/init'-import { mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'--import { TaxonomicFilterGroupType } from '../../TaxonomicFilter/types'-import { PropertyFilters } from '../PropertyFilters'--jest.mock('lib/components/AutoSizer', () => ({- AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>- renderProp({ height: 400, width: 400 }),-}))--describe('TaxonomicPropertyFilter triggerVariant (rebuild menu)', () => {- let unmountFeatureFlagLogic: (() => void) | null = null-- beforeEach(() => {- initKeaTests()- actionsModel.mount()- groupsModel.mount()- propertyDefinitionsModel.mount()- localStorage.clear()- useMocks({- get: {- '/api/projects/:team/event_definitions': mockGetEventDefinitions,- '/api/projects/:team/property_definitions': mockGetPropertyDefinitions,- '/api/projects/:team/actions': { results: [] },- },- post: {- '/api/environments/:team/query': { results: [] },- },- })- unmountFeatureFlagLogic = featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD], {- [FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]: true,- })- })-- afterEach(() => {- featureFlagLogic.actions.setFeatureFlags([], {})- unmountFeatureFlagLogic?.()- unmountFeatureFlagLogic = null- cleanup()- })-- function renderWith(triggerVariant?: 'button' | 'input'): void {- render(- <Provider>- <PropertyFilters- pageKey="input-trigger-test"- propertyFilters={[]}- onChange={jest.fn()}- disablePopover- taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}- triggerVariant={triggerVariant}- />- </Provider>- )- }-- it.each([- { name: 'renders the button trigger by default', triggerVariant: undefined, expectInput: false },- {- name: 'renders the button trigger for triggerVariant="button"',- triggerVariant: 'button',- expectInput: false,- },- {- name: 'renders the input-box trigger for triggerVariant="input"',- triggerVariant: 'input',- expectInput: true,- },- ] as const)('$name', async ({ triggerVariant, expectInput }) => {- renderWith(triggerVariant)-- if (expectInput) {- await waitFor(() => {- expect(screen.getByTestId('taxonomic-filter-menu-input')).toBeInTheDocument()- })- } else {- await waitFor(() => {- expect(screen.getByTestId('taxonomic-popover-menu-trigger')).toBeInTheDocument()- })- expect(screen.queryByTestId('taxonomic-filter-menu-input')).not.toBeInTheDocument()- }- })-})diff --git a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsxindex 5fd3e7c27188..c81bbcb6572c 100644--- a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx+++ b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx@@ -21,7 +21,6 @@ import {sanitizePropertyFilter,} from 'lib/components/PropertyFilters/utils'import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'-import { taxonomicTriggerWrapperClassName } from 'lib/components/TaxonomicFilter/menu/triggerLayout'import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import {TaxonomicFilterGroup,@@ -29,11 +28,6 @@ import {TaxonomicFilterValue,isKeyOnlyForGroup,} from 'lib/components/TaxonomicFilter/types'-import { taxonomicMenuPreferenceLogic } from 'lib/components/TaxonomicPopover/taxonomicMenuPreferenceLogic'-import { TaxonomicMenuToggle } from 'lib/components/TaxonomicPopover/TaxonomicMenuToggle'-import { TaxonomicPopoverMenu } from 'lib/components/TaxonomicPopover/TaxonomicPopoverMenu'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { isOperatorMulti, isOperatorRegex } from 'lib/utils/operators'import { toParams } from 'lib/utils/url'import { teamLogic } from 'scenes/teamLogic'@@ -91,7 +85,6 @@ export function TaxonomicPropertyFilter({operatorAllowlist,endpointFilters,hogQLGlobals,- triggerVariant = 'button',staticValueOptions,renderOperatorValueSelect,propertyDefinitionsOverride,@@ -151,9 +144,6 @@ export function TaxonomicPropertyFilter({const { cohortsById } = useValues(cohortsModel)const { columnsJoinedToPersons } = useValues(joinsLogic)const { currentTeamId } = useValues(teamLogic)- const { featureFlags } = useValues(featureFlagLogic)- const { useNewMenu } = useValues(taxonomicMenuPreferenceLogic)- const menuRebuildEnabled = !!featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]// We don't support array filter values here. Multiple-cohort only supported in TaxonomicBreakdownFilter.// This is mostly to make TypeScript happy.@@ -313,7 +303,7 @@ export function TaxonomicPropertyFilter({))- const legacyDropdown = (+ const editablePicker = (<LemonDropdownoverlay={taxonomicFilter}placement="bottom-start"@@ -347,56 +337,6 @@ export function TaxonomicPropertyFilter({</LemonDropdown>)- // The rebuilt menu is a self-contained popover, so it only replaces the- // row-branch dropdown variant. The truly inline mode is already routed- // away via `showInitialSearchInline`; `disablePopover` still renders a- // button + dropdown here, so it's fine to swap.- //- // Key-only rows route through the rebuilt menu too — the picker fires- // the same `taxonomicOnChange` callback in either mode, so the commit- // shape is identical (cohort id → `setFilter` with `type: 'cohort'`).- //- // The rebuilt menu carries its own toggle inside its trigger wrapper, so- // it needs no extra DOM and inherits the row's layout exactly. The- // legacy path gets a thin positioned wrapper to host the floating toggle.- const editablePicker = !menuRebuildEnabled ? (- legacyDropdown- ) : useNewMenu ? (- <TaxonomicPopoverMenu- groupType={filterTaxonomicGroupType ?? groupTypes[0]}- value={cohortOrOtherValue}- groupTypes={groupTypes}- onChange={(value, _groupType, item, group) => taxonomicOnChange(group, value, item)}- renderValue={() => <span className="truncate">{filterContent}</span>}- placeholder={addText || 'Add filter'}- metadataSource={metadataSource}- eventNames={eventNames}- schemaColumns={schemaColumns}- excludedProperties={excludedProperties}- propertyAllowList={propertyAllowList}- optionsFromProp={taxonomicFilterOptionsFromProp}- hideBehavioralCohorts={hideBehavioralCohorts}- showCohortFlagTargeting={showCohortFlagTargeting}- endpointFilters={endpointFilters}- hogQLGlobals={hogQLGlobals}- enableKeywordShortcuts- triggerVariant={triggerVariant}- triggerButtonProps={{- type: 'secondary',- size,- truncate: true,- sideIcon: null,- fullWidth: triggerVariant === 'input',- icon: !valuePresent ? <IconPlusSmall /> : undefined,- }}- />- ) : (- <span className={taxonomicTriggerWrapperClassName()}>- {legacyDropdown}- <TaxonomicMenuToggle />- </span>- )-return (<divclassName={clsx('TaxonomicPropertyFilter', {diff --git a/frontend/src/lib/components/PropertyFilters/types.ts b/frontend/src/lib/components/PropertyFilters/types.tsindex bba7f40b0d50..65211b443d20 100644--- a/frontend/src/lib/components/PropertyFilters/types.ts+++ b/frontend/src/lib/components/PropertyFilters/types.ts@@ -79,12 +79,6 @@ export interface PropertyFilterInternalProps {addFilterDocLink?: stringendpointFilters?: Record<string, any>hogQLGlobals?: Record<string, any>- /**- * `'input'` renders the replay-style input-box add-filter trigger; `'button'`- * (the default) renders a button. Only has an effect on the rebuild menu- * (`TAXONOMIC_FILTER_MENU_REBUILD`).- */- triggerVariant?: 'button' | 'input'/*** Statically known value suggestions per property key, replacing API-fetched ones.* Return an empty array to disable suggestions for a key, or null to fall backdiff --git a/frontend/src/lib/components/PropertyFilters/utils.test.ts b/frontend/src/lib/components/PropertyFilters/utils.test.tsindex a77be5ec70ce..0f42cb472a70 100644--- a/frontend/src/lib/components/PropertyFilters/utils.test.ts+++ b/frontend/src/lib/components/PropertyFilters/utils.test.ts@@ -439,8 +439,8 @@ describe('type mapping round-trip', () => {})it('MCPProperties maps one-way to the Event property filter type', () => {- // The rebuild menu commits with the tab's own group type, so without this- // mapping an MCP-tab selection would produce a filter with no type.+ // A selection committed with the MCP tab's own group type would otherwise+ // produce a filter with no type.expect(taxonomicFilterTypeToPropertyFilterType(TaxonomicFilterGroupType.MCPProperties)).toEqual(PropertyFilterType.Event)diff --git a/frontend/src/lib/components/PropertyFilters/utils.ts b/frontend/src/lib/components/PropertyFilters/utils.tsindex 1388daf8a18a..14b7a7b02416 100644--- a/frontend/src/lib/components/PropertyFilters/utils.ts+++ b/frontend/src/lib/components/PropertyFilters/utils.ts@@ -744,8 +744,7 @@ export function taxonomicFilterTypeToPropertyFilterType(* Recover a property definition's id. Pinned/default taxonomic items are stored as* `{ name }` with no saved id, so fall back to the canonical `propertyDefinitionsModel`* (keyed by name + type) instead of building a link with an `undefined` id. Returns- * `undefined` when the id can't be resolved so callers can hide the link. Shared by the- * legacy DefinitionPopover and the quill rebuild's PreviewPane to keep them in lockstep.+ * `undefined` when the id can't be resolved so callers can hide the link.*/export function resolvePropertyDefinitionId(definition: Pick<PropertyDefinition, 'id' | 'name'>,diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsxindex 5a52c8d19a74..eef89c2e16f0 100644--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsx@@ -602,7 +602,6 @@ describe('TaxonomicFilter', () => {// Searching an event this picker hides has to say so. Dropping it from the list and then// reporting "no results" tells someone who knows the event exists that it never did.- // The rebuild's half of this lives in menu/Combobox.test.tsx.describe('an event hidden because its data is moving', () => {beforeEach(() => {setFlagEvaluationsMode(FlagEvaluationsModeEnumApi.Number1)@@ -1433,7 +1432,7 @@ describe('TaxonomicFilter', () => {filterValue: '/pricing',propertyFilterType: PropertyFilterType.Event,// Tagged so commit telemetry can distinguish the URL-contains shortcut- // from keyword shortcuts (parity with the rebuild's wasUrlContainsShortcut).+ // from keyword shortcuts.isContainsShortcut: true,}))diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilterGallery.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilterGallery.stories.tsxindex 84c81d1ed858..11e8b3b6704f 100644--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilterGallery.stories.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilterGallery.stories.tsx@@ -9,14 +9,11 @@ import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__import { TaxonomicFilter, TaxonomicFilterSearchInput } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import { taxonomicFilterLogic } from 'lib/components/TaxonomicFilter/taxonomicFilterLogic'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { taxonomicMenuPreferenceLogic } from 'lib/components/TaxonomicPopover/taxonomicMenuPreferenceLogic'import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'-import { FEATURE_FLAGS } from 'lib/constants'-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { actionsModel } from '~/models/actionsModel'import { cohortsModel } from '~/models/cohortsModel'@@ -56,7 +53,6 @@ const USAGES: Usage[] = [entry: 'properties',props: {onChange: noop,- triggerVariant: 'input',eventNames: ['$pageview'],hasRowOperator: true,allowRelativeDateOptions: true,@@ -332,15 +328,10 @@ const VARIANTS: { key: string; label: string; blurb: string }[] = [blurb: 'Generic popover wrapper; resting state is a button.',},{- key: 'properties:button',- label: 'PropertyFilters — button trigger',+ key: 'properties',+ label: 'PropertyFilters',blurb: 'Property-filter rows; the add control is a button.',},- {- key: 'properties:input',- label: 'PropertyFilters — input trigger',- blurb: 'Replay-style input add control (triggerVariant: input).',- },{key: 'universal',label: 'UniversalFilters — add-filter pills',@@ -353,34 +344,6 @@ const VARIANTS: { key: string; label: string; blurb: string }[] = [},]-function variantKey(usage: Usage): string {- if (usage.entry === 'properties') {- return `properties:${usage.props.triggerVariant ?? 'button'}`- }- return usage.entry-}--const STORY_TITLE: Record<string, string> = {- 'rebuild-menu': 'rebuild menu on (only the wrapper entry points change)',- 'classic-picker': 'classic picker with category dropdown',-}--/**- * The surface a given variant actually renders on a given story. The rebuild- * flag only swaps the two wrapper entry points, so a raw `TaxonomicFilter`- * stays on the classic picker even on the rebuild story. This label makes that- * explicit per cell instead of letting the story title imply otherwise.- */-function surfaceFor(key: string, story: string): string {- // Only the two rebuild wrappers (TaxonomicPopover, TaxonomicPropertyFilter)- // get the rebuild menu. Raw TaxonomicFilter and UniversalFilters never do.- const getsRebuild = key === 'popover' || key.startsWith('properties')- if (getsRebuild && story === 'rebuild-menu') {- return 'rebuild menu'- }- return 'classic picker'-}-function UsagePreview({ usage, storyKey }: { usage: Usage; storyKey: string }): JSX.Element {// Raw TaxonomicFilter has no resting state — it IS the open panel, and it// autofocuses its search input on mount. Mounting ~8 of those at once made@@ -485,44 +448,30 @@ function UniversalFilterGroupBody(): JSX.Element {)}-function Gallery({ variant }: { variant: string }): JSX.Element {+function Gallery(): JSX.Element {useMountedLogic(actionsModel)useMountedLogic(cohortsModel)- // The rebuild menu is gated by both the flag (set per story) and this- // persisted preference. The preference is a real-user escape hatch back to- // the classic UI; a fixture should always show the rebuild when flagged in,- // regardless of whatever a dev left in their Storybook localStorage.- const { setUseNewMenu } = useActions(taxonomicMenuPreferenceLogic)- useOnMountEffect(() => setUseNewMenu(true))-return (<div className="p-4">- <h1 className="text-xl font-bold mb-2">Taxonomic filter gallery — {STORY_TITLE[variant] ?? variant}</h1>+ <h1 className="text-xl font-bold mb-2">Taxonomic filter gallery</h1><p className="text-sm text-secondary mb-4 max-w-3xl">The taxonomic-filter family collapses to a handful of unique presentations. Most call sites just pass adifferent <code>taxonomicGroupTypes</code> to the same one. Each cell renders one variant and lists the- call sites that use it with the props that differ. The badge on each cell is the surface it actually- renders. The rebuild flag only swaps the two wrapper entry points, so raw <code>TaxonomicFilter</code>{' '}- stays on the classic picker even on the rebuild story. Raw <code>TaxonomicFilter</code> has no resting+ call sites that use it with the props that differ. Raw <code>TaxonomicFilter</code> has no restingstate, so it reveals on "Show picker".</p><div className="grid grid-cols-1 xl:grid-cols-2 border-l border-t">{VARIANTS.map((v) => {- const usages = USAGES.filter((usage) => variantKey(usage) === v.key)+ const usages = USAGES.filter((usage) => usage.entry === v.key)if (usages.length === 0) {return null}- const storyKey = `gallery-${variant}-${v.key}`+ const storyKey = `gallery-${v.key}`return (<div key={v.key} className="border-r border-b p-4 flex flex-col gap-3 min-w-0"><div>- <div className="flex items-center gap-2">- <h1 className="text-base font-bold">{v.label}</h1>- <span className="text-2xs uppercase tracking-wide px-1.5 py-0.5 rounded bg-surface-secondary text-secondary whitespace-nowrap">- {surfaceFor(v.key, variant)}- </span>- </div>+ <h1 className="text-base font-bold">{v.label}</h1><p className="text-xs text-secondary">{v.blurb}</p></div><div className="min-w-0">@@ -562,7 +511,7 @@ const meta: Meta = {docs: {description: {component:- 'A catalogue of every distinct taxonomic-filter usage across the app, repeated for each live variant, to drive simplification.',+ 'A catalogue of every distinct taxonomic-filter usage across the app, to drive simplification.',},},},@@ -572,11 +521,6 @@ const meta: Meta = {export default metatype Story = StoryObj-export const RebuildMenu: Story = {- render: () => <Gallery variant="rebuild-menu" />,- parameters: { featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]: true } },-}--export const ClassicPicker: Story = {- render: () => <Gallery variant="classic-picker" />,+export const AllUsages: Story = {+ render: () => <Gallery />,}diff --git a/frontend/src/lib/components/TaxonomicFilter/dataWarehouseItemUtils.ts b/frontend/src/lib/components/TaxonomicFilter/dataWarehouseItemUtils.tsindex 91bede70f082..e1bc4c310edd 100644--- a/frontend/src/lib/components/TaxonomicFilter/dataWarehouseItemUtils.ts+++ b/frontend/src/lib/components/TaxonomicFilter/dataWarehouseItemUtils.ts@@ -22,7 +22,7 @@ function findFieldByNameCandidates(candidates: string[]): DataWarehouseTableForInsight['fields'][string] | undefined {// `fields` may be missing when the warehouse item is reconstructed- // from a committed filter (e.g. via the new menu rebuild) where the+ // from a committed filter where the// selection only carries `name` / `id`. Bail out cleanly instead of// throwing on `Object.values(undefined)`.if (!warehouseItem.fields) {diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsxdeleted file mode 100644index 4bf523a1a8dc..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx+++ /dev/null@@ -1,2156 +0,0 @@-/**- * Composable TaxonomicFilter autocomplete (Base UI Autocomplete + Quill- * primitives). Every piece is opt-in — `Root` is a pure provider; the- * Popover, Trigger, Content, Input, Chips, List are sibling primitives the- * consumer composes in any order.- *- * <TaxonomicAutocomplete.Root>- * <TaxonomicAutocomplete.Popover>- * <TaxonomicAutocomplete.Trigger />- * <TaxonomicAutocomplete.Content>- * <TaxonomicAutocomplete.Input />- * <TaxonomicAutocomplete.Chips />- * <TaxonomicAutocomplete.List />- * </TaxonomicAutocomplete.Content>- * </TaxonomicAutocomplete.Popover>- * </TaxonomicAutocomplete.Root>- *- * Or wire raw Quill primitives via `useTaxonomicAutocomplete()` if you- * need full control over the popover (or want to render inline, in a- * Sheet, etc).- *- * Selecting any row closes the popover. Pass `open` + `onOpenChange` to- * control externally.- *- * Modes:- * - 'all' — merges items from every visible group, single Fuse pass.- * Selecting routes back to the source group.- * - <type> — only that group's items.- *- * For both modes, every visible group is fetched via `useGroupList` while- * the popover is open so 'All' search has data ready.- */-import { Autocomplete } from '@base-ui/react/autocomplete'-import { useActions, useValues } from 'kea'-import {- createContext,- ReactElement,- ReactNode,- RefObject,- useCallback,- useContext,- useEffect,- useMemo,- useRef,- useState,-} from 'react'--import { IconChevronLeft } from '@posthog/icons'-import { IconChevronRight } from '@posthog/icons'-import {- Button,- ButtonGroup,- cn,- DropdownMenu,- DropdownMenuContent,- DropdownMenuGroup,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,- InputGroup,- InputGroupInput,- Popover,- PopoverContent,- PopoverTrigger,- ScrollArea,- Tooltip,- TooltipContent,- TooltipTrigger,-} from '@posthog/quill'--import { createFuse } from 'lib/utils/fuseSearch'-import { surveyQuestionLabelsLogic } from 'scenes/surveys/surveyQuestionLabelsLogic'--import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'-import { getCoreFilterDefinition } from '~/taxonomy/helpers'-import { PropertyDefinitionType } from '~/types'--import { useGroupList } from '../hooks/useGroupList'-import { hasPinnedContext, taxonomicFilterPinnedPropertiesLogic } from '../taxonomicFilterPinnedPropertiesLogic'-import {- META_GROUP_TYPES,- TaxonomicDefinitionTypes,- TaxonomicFilterGroup,- TaxonomicFilterGroupType,- TaxonomicFilterValue,- withoutSearchOnlyGroups,-} from '../types'-import { useTaxonomicFilterContext } from './context'--export type TaxonomicAutocompleteCategoryMode = 'all' | TaxonomicFilterGroupType--export interface TaxonomicAutocompleteCategory {- /** 'all' for the synthetic "all" entry, otherwise the group type. */- id: TaxonomicAutocompleteCategoryMode- /** Human label — `group.name` for groups, "All" for the synthetic entry. */- name: string- isActive: boolean- onSelect: () => void- /** Underlying group, undefined for the 'all' entry. */- group?: TaxonomicFilterGroup- /** Number of items currently loaded for the group. Undefined for 'all'. */- count?: number- isLoading?: boolean- needsMoreSearchCharacters?: boolean-}--export interface TaxonomicAutocompleteEntry {- item: TaxonomicDefinitionTypes- group: TaxonomicFilterGroup- name: string- friendlyLabel?: string-}--/**- * Lightweight seed for `defaultSelected` — consumer doesn't need to know- * the full `TaxonomicFilterGroup` config, just the type. Resolved to a- * full `TaxonomicAutocompleteEntry` once Root has the matching group.- */-export interface TaxonomicAutocompleteSeed {- groupType: TaxonomicFilterGroupType- /** Underlying value (e.g. `"$pageview"`). Used for value-based matching. */- value: TaxonomicFilterValue- /** Raw name (e.g. `"$pageview"`). */- name: string- /** Friendly label (e.g. `"Pageview"`). Falls back to `name` for the trigger. */- friendlyLabel?: string-}--type IndexedItem = TaxonomicAutocompleteEntry--/**- * Sub-page kinds in the popover view stack. `configure` = inline form- * before commit (DWH columns, HogQL editor). `details` = read-only- * metadata sheet (description, type, sent-as, pin / edit / open buttons).- *- * Both render via the shared `Header` + sliding view stack; the only- * difference is which `<…View>` primitive matches the active kind.- */-export type TaxonomicAutocompletePageKind = 'configure' | 'details'--export interface TaxonomicAutocompletePage {- kind: TaxonomicAutocompletePageKind- entry: TaxonomicAutocompleteEntry-}--/**- * Curation meta groups — user shortcuts (Recent / Pinned / Suggested).- * These get auto-injected by the orchestrator but live as separate UX- * affordances elsewhere; we hide them from the chip row + 'all' search.- *- * Distinct from the orchestrator's broader `META_GROUP_TYPES` set, which- * also includes render-driven groups like `HogQLExpression` and- * `Wildcards` — those ARE first-class chips here.- */-const CURATION_META_GROUP_TYPES: ReadonlySet<TaxonomicFilterGroupType> = new Set([- TaxonomicFilterGroupType.SuggestedFilters,- TaxonomicFilterGroupType.RecentFilters,- TaxonomicFilterGroupType.PinnedFilters,-])--interface AutocompleteCtx {- category: TaxonomicAutocompleteCategoryMode- setCategory: (m: TaxonomicAutocompleteCategoryMode) => void- visibleGroups: TaxonomicFilterGroup[]- targetGroups: TaxonomicFilterGroup[]- searchQuery: string- setSearchQuery: (q: string) => void- items: IndexedItem[]- inputPlaceholder?: string- listClassName?: string- maxItems: number- open: boolean- setOpen: (v: boolean) => void- onSelectEntry: (entry: IndexedItem) => void- itemsByType: Record<string, TaxonomicDefinitionTypes[]>- loadingByType: Record<string, boolean>- needsMoreByType: Record<string, boolean>- emptyState: ReactNode- /** Last entry selected through this UI (rich data: group + item + labels). */- selectedEntry: IndexedItem | null- clearSelection: () => void- /** Currently keyboard/pointer-highlighted row (transient — reset on close). */- highlightedEntry: IndexedItem | null- setHighlightedEntry: (entry: IndexedItem | null) => void- /** Currently controlled value from the orchestrator (raw, no item context). */- value: TaxonomicFilterValue | undefined- /** Ref to the search input — Input attaches it on mount. */- inputRef: RefObject<HTMLInputElement>- /** Move focus to the search input. */- focusInput: () => void- /** Label for the default Trigger button when no entry is selected. */- triggerLabel?: string- /** Active sub-page on the view stack, or null in the root view. */- pendingPage: TaxonomicAutocompletePage | null- /** Convenience: `pendingPage?.entry ?? null`. */- pendingEntry: IndexedItem | null- /** Group types that have a `<ConfigureView>` registered. */- configuredTypes: ReadonlySet<TaxonomicFilterGroupType>- addConfiguredType: (t: TaxonomicFilterGroupType) => void- removeConfiguredType: (t: TaxonomicFilterGroupType) => void- /** Group types that have a `<DetailsView>` registered. */- detailsTypes: ReadonlySet<TaxonomicFilterGroupType>- addDetailsType: (t: TaxonomicFilterGroupType) => void- removeDetailsType: (t: TaxonomicFilterGroupType) => void- /**- * Group types managed by `<MenuTrigger>` shortcuts — excluded from- * popover chips + list so they only surface in the dropdown menu.- */- dropdownManagedTypes: ReadonlySet<TaxonomicFilterGroupType>- addDropdownManagedType: (t: TaxonomicFilterGroupType) => void- removeDropdownManagedType: (t: TaxonomicFilterGroupType) => void- /** True while a `<MenuTrigger>` is mounted. */- hasMenuTrigger: boolean- setHasMenuTrigger: (v: boolean) => void- /**- * Ref to the trigger button when `<MenuTrigger>` is in use — Content- * uses this as the popover anchor instead of `<PopoverTrigger>`. Lets- * the menu and popover share the same visible button without their- * click handlers fighting each other.- */- triggerRef: RefObject<HTMLElement | null>- /** Open the configurator for an entry (e.g. clicking the item segment of SegmentedTrigger). */- openConfigureFor: (entry: IndexedItem) => void- /** Open the details sheet for an entry (e.g. arrow-right → View cell). */- openDetailsFor: (entry: IndexedItem) => void- /** Commit the pending entry, optionally merging extra fields into the item. */- commitPending: (extra?: Record<string, unknown>) => void- /** Cancel the pending sub-view, leaving any prior selection intact. */- cancelPending: () => void- /** Title for the active sub-view; pushed up by the sub-view for `Header`. */- pendingTitle: ReactNode | null- setPendingTitle: (t: ReactNode | null) => void-}--const Ctx = createContext<AutocompleteCtx | null>(null)--function useAutocompleteCtx(): AutocompleteCtx {- const ctx = useContext(Ctx)- if (!ctx) {- throw new Error('TaxonomicAutocomplete sub-components must be used inside <TaxonomicAutocomplete.Root>.')- }- return ctx-}--// `threshold` + `ignoreDiacritics` come from `createFuse` defaults; we-// only override the keys + the `ignoreLocation` switch here.-const FUSE_OPTIONS = {- keys: ['name', 'friendlyLabel'],- ignoreLocation: true,-}--function getRawName(item: TaxonomicDefinitionTypes, group: TaxonomicFilterGroup): string {- return (- group.getName?.(item) ??- ('name' in (item as unknown as Record<string, unknown>)- ? ((item as unknown as { name?: string }).name ?? '')- : '')- )-}--function getFriendlyLabel(item: TaxonomicDefinitionTypes, group: TaxonomicFilterGroup): string | undefined {- const raw = getRawName(item, group)- if (!raw) {- return undefined- }- return getCoreFilterDefinition(raw, group.type)?.label-}--// Autocomplete owns these keys; stop them from bubbling into the-// orchestrator's `rootProps.onKeyDown`, which would call useGroupList's-// moveUp/moveDown/selectSelected and double-handle the event (and worse,-// preventDefault arrow keys before Autocomplete sees them). Tab still-// bubbles so the parent's tabLeft/tabRight tab-switching keeps working.-function stopOwnedKeys(e: React.KeyboardEvent<HTMLDivElement>): void {- switch (e.key) {- case 'ArrowUp':- case 'ArrowDown':- case 'Home':- case 'End':- case 'PageUp':- case 'PageDown':- case 'Enter':- case 'Escape':- e.stopPropagation()- break- }-}--export interface TaxonomicAutocompleteRootProps {- children: ReactNode- /** Controlled open state. */- open?: boolean- onOpenChange?: (open: boolean) => void- /** Uncontrolled initial open. */- defaultOpen?: boolean- /** Default category. Defaults to 'all'. */- defaultCategory?: TaxonomicAutocompleteCategoryMode- /** Hide meta groups (Suggested / Recent / Pinned) from categories + 'all' search. Default true. */- excludeMetaFromAll?: boolean- /** Maximum items rendered in the list. Default 50. */- maxItems?: number- listClassName?: string- /** Override the search input placeholder. */- placeholder?: string- /**- * Label shown by the default Trigger button when nothing is selected.- * Independent of `placeholder` (which is for the search input only).- * Falls back to `placeholder`, then `"Search…"`.- */- triggerLabel?: string- /**- * Pre-fill the trigger with an initial selection on mount. Uncontrolled- * — only seeds once, after that the user's selections take over.- */- defaultSelected?: TaxonomicAutocompleteSeed | null-}--export function Root({- children,- open,- onOpenChange,- defaultOpen,- defaultCategory = 'all',- excludeMetaFromAll = true,- maxItems = 50,- listClassName,- placeholder,- triggerLabel,- defaultSelected,-}: TaxonomicAutocompleteRootProps): JSX.Element | null {- const { groups, inputProps, selectItem, searchQuery, setSearchQuery, value } = useTaxonomicFilterContext()- const [internalOpen, setInternalOpen] = useState<boolean>(defaultOpen ?? false)- const [category, setCategory] = useState<TaxonomicAutocompleteCategoryMode>(defaultCategory)- const [itemsByType, setItemsByType] = useState<Record<string, TaxonomicDefinitionTypes[]>>({})- const [loadingByType, setLoadingByType] = useState<Record<string, boolean>>({})- const [needsMoreByType, setNeedsMoreByType] = useState<Record<string, boolean>>({})- const [selectedEntry, setSelectedEntry] = useState<IndexedItem | null>(null)- // Transient — base-ui's `onItemHighlighted` writes here so consumers- // can render side panels (preview, hover details) keyed off the- // currently-cursored row without DOM-walking.- const [highlightedEntry, setHighlightedEntry] = useState<IndexedItem | null>(null)- const [pendingPage, setPendingPage] = useState<TaxonomicAutocompletePage | null>(null)- const [pendingTitle, setPendingTitle] = useState<ReactNode | null>(null)- const [configuredTypes, setConfiguredTypes] = useState<Set<TaxonomicFilterGroupType>>(() => new Set())- const [detailsTypes, setDetailsTypes] = useState<Set<TaxonomicFilterGroupType>>(() => new Set())- const [dropdownManagedTypes, setDropdownManagedTypes] = useState<Set<TaxonomicFilterGroupType>>(() => new Set())- const [hasMenuTrigger, setHasMenuTrigger] = useState(false)- const triggerRef = useRef<HTMLElement | null>(null)- const seededRef = useRef(false)- const inputRef = useRef<HTMLInputElement>(null)- const focusInput = useCallback((): void => {- inputRef.current?.focus()- }, [])-- const addConfiguredType = useCallback((t: TaxonomicFilterGroupType): void => {- setConfiguredTypes((prev) => {- if (prev.has(t)) {- return prev- }- const next = new Set(prev)- next.add(t)- return next- })- }, [])- const removeConfiguredType = useCallback((t: TaxonomicFilterGroupType): void => {- setConfiguredTypes((prev) => {- if (!prev.has(t)) {- return prev- }- const next = new Set(prev)- next.delete(t)- return next- })- }, [])- const addDetailsType = useCallback((t: TaxonomicFilterGroupType): void => {- setDetailsTypes((prev) => {- if (prev.has(t)) {- return prev- }- const next = new Set(prev)- next.add(t)- return next- })- }, [])- const removeDetailsType = useCallback((t: TaxonomicFilterGroupType): void => {- setDetailsTypes((prev) => {- if (!prev.has(t)) {- return prev- }- const next = new Set(prev)- next.delete(t)- return next- })- }, [])- const addDropdownManagedType = useCallback((t: TaxonomicFilterGroupType): void => {- setDropdownManagedTypes((prev) => {- if (prev.has(t)) {- return prev- }- const next = new Set(prev)- next.add(t)- return next- })- }, [])- const removeDropdownManagedType = useCallback((t: TaxonomicFilterGroupType): void => {- setDropdownManagedTypes((prev) => {- if (!prev.has(t)) {- return prev- }- const next = new Set(prev)- next.delete(t)- return next- })- }, [])-- const isControlled = open !== undefined- const isOpen = isControlled ? open : internalOpen- const setOpen = useCallback(- (v: boolean): void => {- if (!isControlled) {- setInternalOpen(v)- }- // Reset transient highlight when the popover closes — the- // next open should start fresh rather than echo a stale row.- if (!v) {- setHighlightedEntry(null)- }- onOpenChange?.(v)- },- [isControlled, onOpenChange]- )-- const visibleGroups = useMemo(- // Exclude *curation* meta (Recent / Pinned / Suggested) — those- // exist as user shortcuts elsewhere. Also exclude any types- // registered as `dropdownManagedTypes` by `<MenuTrigger>` (DWH /- // HogQL surfaced as menu shortcuts, not chips).- () => {- const hidden = new Set<TaxonomicFilterGroupType>()- if (excludeMetaFromAll) {- CURATION_META_GROUP_TYPES.forEach((t) => hidden.add(t))- }- dropdownManagedTypes.forEach((t) => hidden.add(t))- return hidden.size > 0 ? groups.filter((g) => !hidden.has(g.type)) : groups- },- [groups, excludeMetaFromAll, dropdownManagedTypes]- )-- // Resolve `defaultSelected` once a matching group is available. Single- // shot — subsequent prop changes don't re-seed (treat it as defaultValue).- useEffect(() => {- if (seededRef.current || !defaultSelected || groups.length === 0) {- return- }- const grp = groups.find((g) => g.type === defaultSelected.groupType)- if (!grp) {- return- }- seededRef.current = true- // Synthetic item — `getValue`/`getName` use whatever the group- // accessors expect; we only need this to round-trip the trigger- // label and the controlled-value comparison. Once the user clicks- // a real row, this gets replaced with a fully-formed entry.- const syntheticItem = {- name: defaultSelected.name,- value: defaultSelected.value,- } as unknown as TaxonomicDefinitionTypes- setSelectedEntry({- item: syntheticItem,- group: grp,- name: defaultSelected.name,- friendlyLabel: defaultSelected.friendlyLabel,- })- }, [defaultSelected, groups])-- const targetGroups = useMemo(- () => (category === 'all' ? visibleGroups : visibleGroups.filter((g) => g.type === category)),- [visibleGroups, category]- )-- // Mount + subscribe so `$survey_response_<question-id>` keys resolve to the- // actual question text. `getFriendlyLabel` reads through `getCoreFilterDefinition`,- // which falls back to a static label until `surveyQuestionLabelsLogic` has- // loaded. Subscribing here ensures `indexed` recomputes the labels once they- // arrive — without this, each entry's `friendlyLabel` would be frozen to the- // pre-load fallback for the lifetime of the popover.- const { surveyQuestionLabels } = useValues(surveyQuestionLabelsLogic)-- const indexed = useMemo<IndexedItem[]>(() => {- const merged: IndexedItem[] = []- for (const group of targetGroups) {- const items = itemsByType[group.type] ?? []- // Render-driven groups (e.g. `HogQLExpression` with InlineHogQLEditor)- // have no list items — they're a single editor surface. Synthesise- // one sentinel row so the user has something to click; selection- // hands off to a `<ConfigureView>` registered for that group.- if (items.length === 0 && (group as { render?: unknown }).render) {- merged.push({- item: { name: group.name } as TaxonomicDefinitionTypes,- group,- name: group.name,- friendlyLabel: undefined,- })- continue- }- for (const item of items) {- merged.push({- item,- group,- name: getRawName(item, group),- friendlyLabel: getFriendlyLabel(item, group),- })- }- }- return merged- // `surveyQuestionLabels` is a deliberate recompute trigger: it isn't read- // directly in the body, but `getFriendlyLabel` → `getCoreFilterDefinition`- // reads its value via `findMounted()`. Without this dep the memo would- // freeze each entry's `friendlyLabel` to the pre-load fallback.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [targetGroups, itemsByType, surveyQuestionLabels])-- const filtered = useMemo<IndexedItem[]>(() => {- const trimmed = searchQuery.trim()- if (!trimmed) {- return indexed- }- const fuse = createFuse(indexed, FUSE_OPTIONS as Parameters<typeof createFuse<IndexedItem>>[1])- return fuse.search(trimmed).map((r) => r.item)- }, [indexed, searchQuery])-- const items = useMemo(() => filtered.slice(0, maxItems), [filtered, maxItems])-- const anyLoading = targetGroups.some((g) => loadingByType[g.type])- const allNeedMore = targetGroups.length > 0 && targetGroups.every((g) => needsMoreByType[g.type])- const emptyState: ReactNode = allNeedMore ? 'Type more to search' : anyLoading ? 'Loading…' : 'No matches'-- const commitEntry = useCallback(- (entry: IndexedItem, extra?: Record<string, unknown>): void => {- const mergedItem = extra- ? ({ ...(entry.item as object), ...extra } as unknown as TaxonomicDefinitionTypes)- : entry.item- const itemValue = entry.group.getValue?.(mergedItem) ?? null- const finalEntry: IndexedItem = extra ? { ...entry, item: mergedItem } : entry- setSelectedEntry(finalEntry)- selectItem(entry.group, itemValue, mergedItem)- setOpen(false)- },- [selectItem, setOpen]- )-- const onSelectEntry = useCallback(- (entry: IndexedItem): void => {- // Two-phase: if a `<ConfigureView>` is registered for this- // group, defer commit until the form completes. Otherwise- // commit immediately.- if (configuredTypes.has(entry.group.type)) {- setPendingPage({ kind: 'configure', entry })- return- }- commitEntry(entry)- },- [commitEntry, configuredTypes]- )-- const openConfigureFor = useCallback((entry: IndexedItem): void => {- setPendingPage({ kind: 'configure', entry })- }, [])-- const openDetailsFor = useCallback((entry: IndexedItem): void => {- setPendingPage({ kind: 'details', entry })- }, [])-- const commitPending = useCallback(- (extra?: Record<string, unknown>): void => {- const entry = pendingPage?.entry- if (entry) {- commitEntry(entry, extra)- setPendingPage(null)- }- },- [pendingPage, commitEntry]- )-- const cancelPending = useCallback((): void => {- setPendingPage(null)- }, [])-- const pendingEntry = pendingPage?.entry ?? null-- // When a sub-view closes (pendingPage → null), refocus the search input- // so the next Escape lands on Input's handler — which closes the- // popover — instead of dying on the unmounted form field. This is what- // makes "Esc, Esc" feel like "back, then close" once a sub-view is open.- //- // RootView (and its Input) was unmounted during the sub-view, so wait- // for the next paint before focusing — `inputRef.current` is set during- // the commit, but base-ui's Autocomplete.Input wraps render-prop refs- // through useRender, and the ref attachment can land a tick after the- // outer commit. `setTimeout(0)` is a reliable post-commit hook.- const prevPendingRef = useRef<TaxonomicAutocompletePage | null>(pendingPage)- useEffect(() => {- if (prevPendingRef.current && !pendingPage) {- const t = window.setTimeout(() => inputRef.current?.focus(), 0)- prevPendingRef.current = pendingPage- return () => window.clearTimeout(t)- }- prevPendingRef.current = pendingPage- return undefined- }, [pendingPage])-- const clearSelection = useCallback(() => setSelectedEntry(null), [])-- // If the consumer is *explicitly* controlling `value` and clears it- // (null) or sets it to something that doesn't match the cached entry,- // drop the cache so the trigger doesn't lie. `undefined` means- // uncontrolled — don't touch the cache, otherwise we'd race with our- // own `setSelectedEntry` on click.- useEffect(() => {- if (value === undefined) {- return- }- if (value === null) {- setSelectedEntry(null)- return- }- if (selectedEntry) {- const currentValue = selectedEntry.group.getValue?.(selectedEntry.item)- if (currentValue !== value) {- setSelectedEntry(null)- }- }- }, [value, selectedEntry])-- const ctxValue = useMemo<AutocompleteCtx>(- () => ({- category,- setCategory,- visibleGroups,- targetGroups,- searchQuery,- setSearchQuery,- items,- inputPlaceholder: placeholder ?? inputProps.placeholder,- listClassName,- maxItems,- open: isOpen,- setOpen,- onSelectEntry,- itemsByType,- loadingByType,- needsMoreByType,- emptyState,- selectedEntry,- clearSelection,- highlightedEntry,- setHighlightedEntry,- value,- inputRef,- focusInput,- triggerLabel,- pendingPage,- pendingEntry,- configuredTypes,- addConfiguredType,- removeConfiguredType,- detailsTypes,- addDetailsType,- removeDetailsType,- dropdownManagedTypes,- addDropdownManagedType,- removeDropdownManagedType,- hasMenuTrigger,- setHasMenuTrigger,- triggerRef,- openConfigureFor,- openDetailsFor,- commitPending,- cancelPending,- pendingTitle,- setPendingTitle,- }),- [- category,- visibleGroups,- targetGroups,- searchQuery,- setSearchQuery,- items,- placeholder,- inputProps.placeholder,- listClassName,- maxItems,- isOpen,- setOpen,- onSelectEntry,- itemsByType,- loadingByType,- needsMoreByType,- emptyState,- selectedEntry,- clearSelection,- highlightedEntry,- value,- focusInput,- triggerLabel,- pendingPage,- pendingEntry,- configuredTypes,- addConfiguredType,- removeConfiguredType,- detailsTypes,- addDetailsType,- removeDetailsType,- dropdownManagedTypes,- addDropdownManagedType,- removeDropdownManagedType,- hasMenuTrigger,- openConfigureFor,- openDetailsFor,- commitPending,- cancelPending,- pendingTitle,- ]- )-- const reportItems = useCallback(- (type: string, next: TaxonomicDefinitionTypes[]): void =>- setItemsByType((prev) => (prev[type] === next ? prev : { ...prev, [type]: next })),- []- )- const reportLoading = useCallback(- (type: string, loading: boolean): void =>- setLoadingByType((prev) => (prev[type] === loading ? prev : { ...prev, [type]: loading })),- []- )- const reportNeedsMore = useCallback(- (type: string, needs: boolean): void =>- setNeedsMoreByType((prev) => (prev[type] === needs ? prev : { ...prev, [type]: needs })),- []- )-- if (groups.length === 0) {- return null- }-- return (- <Ctx.Provider value={ctxValue}>- {/* Fetchers run while the popover is open so 'All' search has- every group's items ready, and so the categories list can- expose live counts via `useTaxonomicAutocompleteCategories`.- Zero-DOM components — render anywhere in the tree. */}- {isOpen &&- visibleGroups.map((group) => (- <GroupItemsFetcher- key={group.type}- group={group}- onItems={reportItems}- onLoading={reportLoading}- onNeedsMore={reportNeedsMore}- />- ))}- {children}- </Ctx.Provider>- )-}--/**- * Quill Popover wrapper bound to Root state. Optional — drop in a raw- * `<Popover open={...} onOpenChange={...}>` instead if you need to swap- * the container (Sheet, inline panel, etc.). Use `useTaxonomicAutocomplete()`- * to read the open state for that case.- *- * Sub-views (DataWarehouse field config, HogQL editor, etc.) render inside- * this same popover via `<RootView>` + `<ConfigureView>` — no nested- * dialogs, just an internal view stack with back-button + Esc-to-go-back.- */-function PopoverWrapper({ children }: { children: ReactNode }): JSX.Element {- const ctx = useAutocompleteCtx()- return (- <Popover- open={ctx.open}- onOpenChange={(open, details) => {- // When MenuTrigger is mounted, the popover trigger and the- // dropdown-menu trigger live on the same button. Pressing- // it should open the MENU only — `trigger-press` opens- // here are dropped. Programmatic opens (menu items calling- // ctx.setOpen) come through with reason='none' and pass.- if (- open &&- ctx.hasMenuTrigger &&- (details?.reason === 'trigger-press' || details?.reason === 'trigger-hover')- ) {- return- }- ctx.setOpen(open)- }}- >- {children}- </Popover>- )-}--interface GroupItemsFetcherProps {- group: TaxonomicFilterGroup- onItems: (type: string, items: TaxonomicDefinitionTypes[]) => void- onLoading: (type: string, loading: boolean) => void- onNeedsMore: (type: string, needs: boolean) => void-}--function GroupItemsFetcher({ group, onItems, onLoading, onNeedsMore }: GroupItemsFetcherProps): null {- const { getGroupListInput } = useTaxonomicFilterContext()- const list = useGroupList(getGroupListInput(group))- useEffect(() => {- onItems(group.type, list.items)- }, [group.type, list.items, onItems])- useEffect(() => {- onLoading(group.type, list.isLoading)- }, [group.type, list.isLoading, onLoading])- useEffect(() => {- onNeedsMore(group.type, list.needsMoreSearchCharacters)- }, [group.type, list.needsMoreSearchCharacters, onNeedsMore])- return null-}--/** Snapshot passed to the trigger's render-prop function. */-export interface TaxonomicAutocompleteTriggerState {- /** Whether the popover is currently open. */- open: boolean- /** Last entry selected through this UI; null if nothing selected (or value reset externally). */- selected: TaxonomicAutocompleteEntry | null- /** Display label: friendly label > raw name > placeholder > "Search…". */- label: string- /** Resolved placeholder, before falling back to "Search…". */- placeholder?: string- /** Currently controlled value from the orchestrator. */- value: TaxonomicFilterValue | undefined- /** Active category. */- category: TaxonomicAutocompleteCategoryMode- /** Drop the cached selected entry (e.g. for a "clear" button on the trigger). */- clearSelection: () => void-}--export interface TaxonomicAutocompleteTriggerProps {- /** Static render element passed to base-ui PopoverTrigger. */- render?: ReactElement- /**- * Either a static node, or a render-function `(state) => ReactElement`- * that receives full trigger state so the consumer can show the- * selected value (or anything else) inside the trigger.- */- children?: ReactNode | ((state: TaxonomicAutocompleteTriggerState) => ReactElement)-}--function Trigger({ render, children }: TaxonomicAutocompleteTriggerProps): JSX.Element {- const ctx = useAutocompleteCtx()- const selected = ctx.selectedEntry- const label =- (selected?.friendlyLabel && selected.friendlyLabel.length > 0 ? selected.friendlyLabel : selected?.name) ||- ctx.triggerLabel ||- ctx.inputPlaceholder ||- 'Search…'- const state: TaxonomicAutocompleteTriggerState = {- open: ctx.open,- selected,- label,- placeholder: ctx.inputPlaceholder,- value: ctx.value,- category: ctx.category,- clearSelection: ctx.clearSelection,- }- let element: ReactElement- if (typeof children === 'function') {- element = children(state)- } else if (render) {- element = render- } else {- element = <Button variant="outline">{label}</Button>- }- return <PopoverTrigger render={element}>{typeof children !== 'function' ? children : null}</PopoverTrigger>-}--export interface TaxonomicAutocompleteContentProps {- children: ReactNode- className?: string-}--function Content({ children, className }: TaxonomicAutocompleteContentProps): JSX.Element {- const ctx = useAutocompleteCtx()- const inSubView = ctx.pendingEntry != null-- // Tab trap for sub-views. Scope is the popup, so Header's back button +- // form fields all cycle. base-ui's `modal="trap-focus"` didn't loop- // reliably with this Autocomplete.Root composition, and- // FloatingFocusManager standalone needs a floating context we don't own.- const handleSubViewTab = (e: React.KeyboardEvent<HTMLDivElement>): void => {- if (!inSubView) {- return- }- e.stopPropagation()- const popupRoot = e.currentTarget- const FOCUSABLE =- 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'- const tabbables = Array.from(popupRoot.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(- (el) => el.offsetParent !== null- )- if (tabbables.length === 0) {- return- }- const first = tabbables[0]- const last = tabbables[tabbables.length - 1]- const active = popupRoot.ownerDocument.activeElement as HTMLElement | null- if (e.shiftKey && active === first) {- e.preventDefault()- last.focus()- } else if (!e.shiftKey && active === last) {- e.preventDefault()- first.focus()- }- }-- return (- // Hard height pins the surface so view-stack swaps don't reflow.- <PopoverContent- className={cn('p-0 gap-0 w-(--anchor-width) min-w-[320px] h-[400px] overflow-hidden', className)}- >- <Autocomplete.Root- items={ctx.items}- mode="none"- inline- defaultOpen- autoHighlight="always"- openOnInputClick={false}- itemToStringValue={(entry: IndexedItem) => entry.name}- onItemHighlighted={(entry) => ctx.setHighlightedEntry((entry as IndexedItem | undefined) ?? null)}- >- {/* Wrapper owns: Esc-as-back in sub-view, Tab loop in- sub-view (covers Header back button + form fields), and- base-ui key swallowing in root view. */}- <div- className="flex flex-col flex-1 min-h-0 overflow-hidden"- onKeyDown={(e) => {- if (e.key === 'Escape' && inSubView) {- ctx.cancelPending()- e.preventDefault()- e.stopPropagation()- return- }- if (e.key === 'Tab' && inSubView) {- handleSubViewTab(e)- return- }- if (- inSubView &&- (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'Home' || e.key === 'End')- ) {- e.stopPropagation()- return- }- stopOwnedKeys(e)- }}- >- {children}- </div>- </Autocomplete.Root>- </PopoverContent>- )-}--export interface TaxonomicAutocompleteInputProps {- className?: string- placeholder?: string-}--function Input({ className, placeholder }: TaxonomicAutocompleteInputProps): JSX.Element {- const ctx = useAutocompleteCtx()- const categories = useTaxonomicAutocompleteCategories()- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {- if (e.key === 'Escape') {- // Two-step: first Escape returns from a drilled category to- // 'all'; second Escape (already on 'all') closes the popover.- if (ctx.category !== 'all') {- ctx.setCategory('all')- } else {- ctx.setOpen(false)- }- e.preventDefault()- e.stopPropagation()- return- }- if (e.key === 'Enter') {- // Autocomplete mode="none" leaves selection up to us. Prefer- // `aria-activedescendant` (driven by `autoHighlight="always"`),- // fall back to `[data-highlighted]` then the first option —- // covers the brief window after returning from a sub-view- // where the input has remounted but base-ui hasn't yet- // reasserted activedescendant.- const doc = e.currentTarget.ownerDocument- const activeId = e.currentTarget.getAttribute('aria-activedescendant')- const popupRoot = e.currentTarget.closest('[data-slot="popover-content"]')- const itemEl =- (activeId && (doc.getElementById(activeId) as HTMLElement | null)) ||- (popupRoot?.querySelector('[data-highlighted]') as HTMLElement | null) ||- (popupRoot?.querySelector('[role="option"]') as HTMLElement | null)- if (itemEl) {- itemEl.click()- e.preventDefault()- e.stopPropagation()- return- }- }- // Cycle category chips with Tab / Shift+Tab while focus stays on- // the input. Skip when no chips are visible (sub-view active, or- // only the synthetic 'all' entry exists) so the browser's natural- // Tab order — i.e. tabbing into the sub-view's form — wins.- if (e.key === 'Tab' && !ctx.pendingEntry && categories.length > 1) {- const idx = categories.findIndex((c) => c.isActive)- const dir = e.shiftKey ? -1 : 1- const next = (idx + dir + categories.length) % categories.length- categories[next]?.onSelect()- e.preventDefault()- e.stopPropagation()- }- }- return (- <InputGroup>- <Autocomplete.Input- render={- <InputGroupInput- ref={ctx.inputRef}- data-attr="taxonomic-filter-searchfield"- placeholder={placeholder ?? ctx.inputPlaceholder}- className={className}- onKeyDown={handleKeyDown}- />- }- value={ctx.searchQuery}- onChange={(e) => ctx.setSearchQuery(e.target.value)}- />- </InputGroup>- )-}--export interface TaxonomicAutocompleteListProps {- className?: string- children?: ReactNode-}--function List({ className, children }: TaxonomicAutocompleteListProps): JSX.Element {- const ctx = useAutocompleteCtx()- return (- // Height constraint MUST live on the Viewport, not Root. Quill's- // ScrollArea Viewport uses `height: 100%`, but `%` heights only- // resolve when the parent has an explicit height — Root has only- // `position: relative` plus whatever className we pass. Setting- // `max-h-*` on Root leaves the Viewport free to size to content,- // so `clientHeight === scrollHeight`, and base-ui never sets- // `data-overflow-y-end` on Root, so the shadow CSS never fires.- // Routing user className → viewportClassName makes the Viewport the- // overflowing element, which is what base-ui measures.- // `Autocomplete.List` itself stays non-scrollable so native- // `scrollIntoView({block:'nearest'})` walks up to the Viewport.- // `scroll-py-1` keeps the highlighted row from sitting flush- // against the top/bottom edge after scroll.- <ScrollArea- showScrollToButton={['bottom']}- // ScrollArea Root grows into the pinned popover envelope.- // Padding lives on `Autocomplete.List` because Quill's main- // `ScrollArea` (the published dist) doesn't expose- // `viewportClassName` — passing it silently drops onto the- // root div as an unknown DOM attribute.- className="flex-1 min-h-0"- >- <Autocomplete.List data-quill className={cn('p-2 scroll-b-3 scroll-t-2', ctx.listClassName, className)}>- {children ?? (- <>- <Empty />- <Items />- </>- )}- </Autocomplete.List>- </ScrollArea>- )-}--export interface TaxonomicAutocompleteEmptyProps {- className?: string- children?: ReactNode-}--function Empty({ className, children }: TaxonomicAutocompleteEmptyProps): JSX.Element {- const ctx = useAutocompleteCtx()- return (- <Autocomplete.Empty className={cn('px-2 py-3 text-xs text-secondary empty:hidden', className)}>- {children ?? ctx.emptyState}- </Autocomplete.Empty>- )-}--export interface TaxonomicAutocompleteItemsProps {- /** Custom row renderer. Receives the indexed entry. */- children?: (entry: IndexedItem) => ReactNode-}--function Items({ children }: TaxonomicAutocompleteItemsProps): JSX.Element {- return (- <Autocomplete.Collection>- {(entry: IndexedItem) => (children ? children(entry) : <DefaultRow entry={entry} />)}- </Autocomplete.Collection>- )-}--interface DefaultRowProps {- entry: IndexedItem-}--function DefaultRow({ entry }: DefaultRowProps): JSX.Element {- const ctx = useAutocompleteCtx()- const { item, group } = entry- const rawName = entry.name- const friendly = entry.friendlyLabel- const title = friendly && friendly.length > 0 ? friendly : rawName- const subtitle = friendly && friendly !== rawName ? rawName : undefined- // Each Autocomplete.Item needs a unique id so base-ui's- // `aria-activedescendant` only matches one row. Without a stable id,- // base-ui falls back to a composite-list index, and identity churn in- // the items array can cause two rows to share an id → both match- // `data-[highlighted]` styling.- const stableId = `taxonomic-${group.type}-${String(group.getValue?.(item) ?? rawName)}`- // Group badge is only useful in 'all' search — it tells the user which- // group an item came from when results from multiple groups are- // interleaved. Inside a drilled category, every row is from the same- // group, so the badge is just noise.- const showGroupLabel = ctx.category === 'all'- // Rows whose group has a `<ConfigureView>` registered (DWH, HogQL) get- // a chevron + click-to-edit semantics.- const hasConfigure = ctx.configuredTypes.has(group.type)- // Hover popover by default for everything except Configure rows — the- // chevron tells the user clicking opens an editor, a hovercard would- // compete with that intent.- const showHover = !hasConfigure- const rowContent = (- <>- <div className="flex items-baseline gap-2 w-full">- <span className="text-sm">- {title}- {showGroupLabel && (- <span className="ml-2 text-xxs uppercase tracking-wide text-secondary relative -top-px">- {group.name}- </span>- )}- </span>- {hasConfigure && <IconChevronRight className="text-secondary ml-auto" />}- </div>- {subtitle && <span className="text-xs text-secondary">{subtitle}</span>}- </>- )- const itemClassName = cn(- 'flex flex-col items-start gap-0 rounded-sm px-2 py-1 cursor-pointer outline-none',- 'data-[highlighted]:bg-[var(--fill-selected)]'- )-- if (!showHover) {- return (- <Autocomplete.Item- value={entry}- onClick={(e) => {- e.preventDefault()- ctx.onSelectEntry(entry)- }}- className={itemClassName}- // base-ui omits `id` from `AutocompleteItem`'s prop type- // (it assigns its own internally). Pin the stable id we- // need via the wrap-render fallthrough.- render={(itemProps) => <div {...itemProps} id={stableId} />}- >- {rowContent}- </Autocomplete.Item>- )- }-- // Quill `Tooltip` is base-ui Tooltip with hoverable popup enabled by- // default — user can move the cursor into the tooltip without it- // closing. PreviewCard's render-composition with Autocomplete.Item- // wasn't dispatching hover events; Tooltip's compose path is simpler.- return (- <Tooltip>- <TooltipTrigger- delay={350}- render={(triggerProps) => (- <Autocomplete.Item- {...triggerProps}- value={entry}- onClick={(e) => {- e.preventDefault()- ctx.onSelectEntry(entry)- }}- className={itemClassName}- // base-ui omits `id` from `AutocompleteItem`'s- // prop type (it assigns its own internally). Pin- // the stable id via the wrap-render fallthrough.- render={(itemProps) => <div {...itemProps} id={stableId} />}- >- {rowContent}- </Autocomplete.Item>- )}- />- <TooltipContent- side="right"- align="start"- sideOffset={12}- className="rounded-md border bg-popover text-popover-foreground shadow-md max-w-[320px] p-0"- >- <DefaultHoverBody entry={entry} />- </TooltipContent>- </Tooltip>- )-}--/**- * Default body for the row's hover popover. Reads metadata via- * `useTaxonomicAutocompleteItemDetails`. Mirrors the layout of the- * sub-page details sheet so the two surfaces feel consistent.- */-function DefaultHoverBody({ entry }: { entry: TaxonomicAutocompleteEntry }): JSX.Element | null {- const details = useTaxonomicAutocompleteItemDetails(entry)- if (!details) {- return null- }- return (- <div className="flex flex-col gap-3 p-3 text-sm">- <div className="flex flex-col gap-1">- <div className="text-[10px] uppercase tracking-wide text-secondary">{details.groupLabel}</div>- <div className="text-base font-semibold leading-tight">{details.title}</div>- </div>- {details.description && <p className="text-xs text-secondary">{details.description}</p>}- {details.example && <p className="text-xs italic text-secondary">Example: {details.example}</p>}- {details.propertyType && (- <div className="flex flex-col gap-0.5 border-t pt-2">- <div className="text-[10px] uppercase tracking-wide text-secondary">Property type</div>- <div className="text-xs">{details.propertyType}</div>- </div>- )}- {details.rawName !== details.title && (- <div className="flex flex-col gap-0.5 border-t pt-2">- <div className="text-[10px] uppercase tracking-wide text-secondary">Sent as</div>- <code className="text-xs">{details.rawName}</code>- </div>- )}- </div>- )-}--/** Raw category list — no UI. Render however you want (chips, dropdown menu, …). */-export function useTaxonomicAutocompleteCategories(): TaxonomicAutocompleteCategory[] {- const ctx = useAutocompleteCtx()- return useMemo<TaxonomicAutocompleteCategory[]>(() => {- const all: TaxonomicAutocompleteCategory = {- id: 'all',- name: 'All',- isActive: ctx.category === 'all',- onSelect: () => ctx.setCategory('all'),- }- // Search-only groups still feed "all", but are not offered as categories.- const categoryGroups = withoutSearchOnlyGroups(- ctx.visibleGroups,- (group) => group.type,- (type) => META_GROUP_TYPES.has(type)- )- const groupCats = categoryGroups.map<TaxonomicAutocompleteCategory>((group) => ({- id: group.type,- name: group.name,- group,- isActive: ctx.category === group.type,- onSelect: () => ctx.setCategory(group.type),- count: ctx.itemsByType[group.type]?.length,- isLoading: ctx.loadingByType[group.type],- needsMoreSearchCharacters: ctx.needsMoreByType[group.type],- }))- return [all, ...groupCats]- }, [ctx.category, ctx.visibleGroups, ctx.setCategory, ctx.itemsByType, ctx.loadingByType, ctx.needsMoreByType, ctx])-}--/** Read raw Root state from any descendant (open/setOpen, selected, search, …). */-export function useTaxonomicAutocomplete(): {- open: boolean- setOpen: (v: boolean) => void- selectedEntry: TaxonomicAutocompleteEntry | null- clearSelection: () => void- /** Currently keyboard/pointer-cursored row — useful for side-panel previews. */- highlightedEntry: TaxonomicAutocompleteEntry | null- value: TaxonomicFilterValue | undefined- searchQuery: string- setSearchQuery: (q: string) => void- category: TaxonomicAutocompleteCategoryMode- setCategory: (m: TaxonomicAutocompleteCategoryMode) => void- items: TaxonomicAutocompleteEntry[]- onSelectEntry: (entry: TaxonomicAutocompleteEntry) => void- focusInput: () => void-} {- const ctx = useAutocompleteCtx()- return {- open: ctx.open,- setOpen: ctx.setOpen,- selectedEntry: ctx.selectedEntry,- clearSelection: ctx.clearSelection,- highlightedEntry: ctx.highlightedEntry,- value: ctx.value,- searchQuery: ctx.searchQuery,- setSearchQuery: ctx.setSearchQuery,- category: ctx.category,- setCategory: ctx.setCategory,- items: ctx.items,- onSelectEntry: ctx.onSelectEntry,- focusInput: ctx.focusInput,- }-}--export interface TaxonomicAutocompleteChipsProps {- className?: string- /** Override per-chip rendering. */- children?: (category: TaxonomicAutocompleteCategory) => ReactNode-}--function Chips({ className, children }: TaxonomicAutocompleteChipsProps): JSX.Element {- const categories = useTaxonomicAutocompleteCategories()- const ctx = useAutocompleteCtx()- return (- <div role="tablist" className={cn('flex flex-wrap gap-1 px-2 py-1', className)}>- {categories.map((c) =>- children ? (- <span key={c.id}>{children(c)}</span>- ) : (- <Button- key={c.id}- type="button"- role="tab"- size="sm"- aria-selected={c.isActive}- variant={c.isActive ? 'primary' : 'outline'}- // Prevent the chip from stealing focus on mousedown- // (so the input keeps its caret), then re-focus on- // click as a belt-and-braces for keyboard / touch.- onMouseDown={(e: React.MouseEvent<HTMLButtonElement>) => e.preventDefault()}- onClick={() => {- c.onSelect()- ctx.focusInput()- }}- data-attr={c.id === 'all' ? 'taxonomic-tab-all' : `taxonomic-tab-${c.id}`}- >- {c.name}- </Button>- )- )}- </div>- )-}--/** State passed to a `<ConfigureView>` render function. */-export interface TaxonomicAutocompleteConfigureState {- /** The entry awaiting configuration. */- entry: TaxonomicAutocompleteEntry- /** Commit the entry, optionally merging extra fields into the underlying item. */- commit: (extra?: Record<string, unknown>) => void- /** Cancel without committing. Prior `selectedEntry` is preserved. */- cancel: () => void-}--/**- * Inline header rendered at the top of the popover content. Auto-shows a- * back button (← chevron) whenever a sub-view is active, which pops the- * view stack. Title is optional in the root view, required when a- * `<ConfigureView>` provides one.- */-export interface TaxonomicAutocompleteHeaderProps {- /** Title shown when the root view is active. Sub-views render their own. */- rootTitle?: ReactNode- /** Title shown when a sub-view is active. Falls back to the registered view title. */- subTitle?: ReactNode- className?: string-}--function Header({ rootTitle, subTitle, className }: TaxonomicAutocompleteHeaderProps): JSX.Element | null {- const ctx = useAutocompleteCtx()- const isSub = ctx.pendingEntry != null- const resolvedTitle = isSub ? (subTitle ?? ctx.pendingTitle ?? ctx.pendingEntry?.name) : rootTitle- if (!resolvedTitle && !isSub) {- return null- }- return (- <div- className={cn('flex items-center gap-2 px-3 py-2 border-b text-sm font-semibold', className)}- data-state={isSub ? 'sub' : 'root'}- >- {isSub && (- <Button- type="button"- variant="default"- size="icon-sm"- aria-label="Back"- onClick={() => ctx.cancelPending()}- data-attr="taxonomic-autocomplete-back"- className="-ml-1 shrink-0"- >- <IconChevronLeft className="size-4" />- </Button>- )}- <span className="flex-1 truncate">{resolvedTitle}</span>- </div>- )-}--export interface TaxonomicAutocompleteRootViewProps {- children: ReactNode- className?: string-}--/**- * Wraps the root-view content (typically `Input` + `Chips` + `List`).- * Fully unmounts when a `<ConfigureView>` is showing — keeping it mounted- * with `display:none` left the hidden Input's keydown handlers eligible- * for events (notably Tab cycling chips) and made it look like the- * sub-view couldn't take focus. Search query lives on Root, so it- * restores naturally on remount.- */-function RootView({ children, className }: TaxonomicAutocompleteRootViewProps): JSX.Element | null {- const ctx = useAutocompleteCtx()- if (ctx.pendingEntry != null) {- return null- }- return (- <div- // `flex-1 min-h-0` so the list inside can flex-grow into the- // pinned popover envelope (`min-h-[420px]` on PopoverContent).- // Without `min-h-0`, flex items refuse to shrink below their- // content height and the scroll viewport can't expand cleanly.- className={cn('flex flex-col flex-1 min-h-0', className)}- data-state="active"- style={{ animation: 'taxonomic-slide-from-left 220ms cubic-bezier(0.215, 0.61, 0.355, 1)' }}- >- {children}- </div>- )-}--export interface TaxonomicAutocompleteConfigureViewProps {- /** Group types this view handles. */- for: readonly TaxonomicFilterGroupType[]- /** Title for the header back-button row. */- title?: ReactNode | ((entry: TaxonomicAutocompleteEntry) => ReactNode)- /** Render the configuration form. Receives entry + commit/cancel callbacks. */- children: (state: TaxonomicAutocompleteConfigureState) => ReactNode- className?: string-}--/**- * In-popover sub-view that activates when the user clicks a row whose- * group is registered in `for`. Renders a header (with back button) plus- * the consumer's form. Esc bubbles up to `Content`, which calls- * `cancelPending` so back/Esc behave the same.- */-function ConfigureView({- for: forGroups,- title,- children,- className,-}: TaxonomicAutocompleteConfigureViewProps): JSX.Element | null {- const ctx = useAutocompleteCtx()- // Register / unregister types. Stable join key avoids re-running on- // every render even though the array literal identity changes.- const key = forGroups.join(',')- useEffect(() => {- forGroups.forEach((t) => ctx.addConfiguredType(t))- return () => forGroups.forEach((t) => ctx.removeConfiguredType(t))- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [key])-- const pending = ctx.pendingPage?.kind === 'configure' ? ctx.pendingPage.entry : null- const matches = pending != null && forGroups.includes(pending.group.type)- const resolvedTitle = pending && title ? (typeof title === 'function' ? title(pending) : title) : pending?.name-- // Push the resolved title up to the shared Header so it can show it- // alongside the back button. Use a layout effect to land before paint.- useEffect(() => {- if (matches && resolvedTitle != null) {- ctx.setPendingTitle(resolvedTitle)- return () => ctx.setPendingTitle(null)- }- return undefined- }, [matches, resolvedTitle, ctx])-- // Move focus to the first tabbable element on mount. PopoverContent has- // `tabIndex=-1` and Autocomplete.Root absorbs Tab — without an explicit- // handoff, focus dies on the popover surface. Header's back button sits- // in a sibling subtree, so this query naturally scopes to the form.- const containerRef = useRef<HTMLDivElement | null>(null)- useEffect(() => {- if (!matches) {- return- }- const root = containerRef.current- if (!root) {- return- }- const FOCUSABLE =- 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'- root.querySelector<HTMLElement>(FOCUSABLE)?.focus()- }, [matches])-- if (!matches || !pending) {- return null- }-- return (- <div- ref={containerRef}- // `flex-1` so the sub-view fills the remaining popover height- // (popover has `min-h-[420px]` to pin position). Form bodies- // use their own `flex-1` to push the footer to the bottom.- className={cn('flex flex-col flex-1', className)}- data-state="active"- style={{ animation: 'taxonomic-slide-from-right 220ms cubic-bezier(0.215, 0.61, 0.355, 1)' }}- >- {children({- entry: pending,- commit: ctx.commitPending,- cancel: ctx.cancelPending,- })}- </div>- )-}--/** State passed to a `<DetailsView>` render function. */-export interface TaxonomicAutocompleteDetailsState {- /** The entry being viewed. */- entry: TaxonomicAutocompleteEntry- /** Commit the entry as the selected value (e.g. "Use this property" footer). */- commit: (extra?: Record<string, unknown>) => void- /** Close the details sheet, returning to the root view. */- cancel: () => void-}--export interface TaxonomicAutocompleteDetailsViewProps {- /** Group types this details sheet handles. */- for: readonly TaxonomicFilterGroupType[]- /** Title for the header back-button row. */- title?: ReactNode | ((entry: TaxonomicAutocompleteEntry) => ReactNode)- /** Render the details body. Receives entry + commit/cancel callbacks. */- children: (state: TaxonomicAutocompleteDetailsState) => ReactNode- className?: string-}--/**- * Read-only sub-view that activates when the user navigates to the "View"- * cell of a row (right-arrow → Enter, or click). Same chrome as- * `<ConfigureView>` — sliding panel + Header back button — but registered- * for the `'details'` kind. Body comes from the consumer; pair with- * `useTaxonomicAutocompleteItemDetails(entry)` for property metadata.- */-function DetailsView({- for: forGroups,- title,- children,- className,-}: TaxonomicAutocompleteDetailsViewProps): JSX.Element | null {- const ctx = useAutocompleteCtx()- const key = forGroups.join(',')- useEffect(() => {- forGroups.forEach((t) => ctx.addDetailsType(t))- return () => forGroups.forEach((t) => ctx.removeDetailsType(t))- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [key])-- const pending = ctx.pendingPage?.kind === 'details' ? ctx.pendingPage.entry : null- const matches = pending != null && forGroups.includes(pending.group.type)- const resolvedTitle = pending && title ? (typeof title === 'function' ? title(pending) : title) : pending?.name-- useEffect(() => {- if (matches && resolvedTitle != null) {- ctx.setPendingTitle(resolvedTitle)- return () => ctx.setPendingTitle(null)- }- return undefined- }, [matches, resolvedTitle, ctx])-- const containerRef = useRef<HTMLDivElement | null>(null)- useEffect(() => {- if (!matches) {- return- }- const root = containerRef.current- if (!root) {- return- }- const FOCUSABLE =- 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'- root.querySelector<HTMLElement>(FOCUSABLE)?.focus()- }, [matches])-- if (!matches || !pending) {- return null- }-- return (- <div- ref={containerRef}- // `flex-1` so the sub-view fills the remaining popover height- // (popover has `min-h-[420px]` to pin position). Form bodies- // use their own `flex-1` to push the footer to the bottom.- className={cn('flex flex-col flex-1', className)}- data-state="active"- style={{ animation: 'taxonomic-slide-from-right 220ms cubic-bezier(0.215, 0.61, 0.355, 1)' }}- >- {children({- entry: pending,- commit: ctx.commitPending,- cancel: ctx.cancelPending,- })}- </div>- )-}--/**- * Rich metadata for an autocomplete entry — title / description / type /- * sent-as plus pin state and toggle. Pulls from kea logics- * (`propertyDefinitionsModel` for type, `taxonomicFilterPinnedPropertiesLogic`- * for pins) and the static `getCoreFilterDefinition` taxonomy.- *- * Property-typed groups (Event/Person/Session/Group properties, EventMetadata,- * EventFeatureFlags) get a `propertyType`; others fall back to bare info.- *- * Returns `null` when entry is null — convenience so callers can pass the- * possibly-null `pendingPage.entry` directly.- */-const PROPERTY_GROUP_TYPE_TO_DEFINITION_TYPE: Partial<Record<TaxonomicFilterGroupType, PropertyDefinitionType>> = {- [TaxonomicFilterGroupType.EventProperties]: PropertyDefinitionType.Event,- [TaxonomicFilterGroupType.EventMetadata]: PropertyDefinitionType.Event,- [TaxonomicFilterGroupType.EventFeatureFlags]: PropertyDefinitionType.Event,- [TaxonomicFilterGroupType.PersonProperties]: PropertyDefinitionType.Person,- [TaxonomicFilterGroupType.SessionProperties]: PropertyDefinitionType.Session,- [TaxonomicFilterGroupType.GroupsPrefix]: PropertyDefinitionType.Group,-}--export interface TaxonomicAutocompleteItemDetails {- title: string- /** Group label, uppercased — e.g. `EVENT PROPERTY`, `PERSON PROPERTY`. */- groupLabel: string- /** Raw underlying name (e.g. `$browser_type`). */- rawName: string- description?: string- /** First example value, formatted. */- example?: string- /** Property type ("String", "Numeric", …) if the group resolves to one. */- propertyType?: string- /** Whether the entry is currently pinned in `taxonomicFilterPinnedPropertiesLogic`. */- isPinned: boolean- /** Toggle pin state for the entry. */- togglePin: () => void- /** Whether the group supports pinning at all (META groups don't). */- isPinnable: boolean-}--export function useTaxonomicAutocompleteItemDetails(- entry: TaxonomicAutocompleteEntry | null-): TaxonomicAutocompleteItemDetails | null {- const { describeProperty } = useValues(propertyDefinitionsModel)- const { isPinned } = useValues(taxonomicFilterPinnedPropertiesLogic)- const { togglePin: togglePinAction } = useActions(taxonomicFilterPinnedPropertiesLogic)-- return useMemo<TaxonomicAutocompleteItemDetails | null>(() => {- if (!entry) {- return null- }- const { item, group, name, friendlyLabel } = entry- const title = friendlyLabel && friendlyLabel.length > 0 ? friendlyLabel : name- const def = getCoreFilterDefinition(name, group.type)- // Fall back to the pinned context's stored value when `getValue`- // can't read it from the shrunk `{ name }` reducer payload — Actions- // and other groups whose `getValue` reads `id` (not `name`) would- // otherwise short-circuit to `null` and break pin/unpin from the- // pinned drill.- const value = group.getValue?.(item) ?? (hasPinnedContext(item) ? item._pinnedContext.value : null) ?? null- const definitionType = PROPERTY_GROUP_TYPE_TO_DEFINITION_TYPE[group.type]- const propertyType = definitionType ? (describeProperty(name, definitionType) ?? undefined) : undefined- const example = def?.examples?.[0] != null ? String(def.examples[0]) : undefined- // `group.name` is optional on synthetic groups (e.g. the- // `ActionFilterRow` trigger-only group constructed from a- // committed filter). Fall back to the type so the label still- // renders something sensible instead of throwing.- const groupLabel = (group.name ?? String(group.type ?? '')).toUpperCase()- const isPinnable = value != null && !CURATION_META_GROUP_TYPES.has(group.type)- // Prefer taxonomy core description (canonical events/props), fall- // back to the item's own description (Actions, custom events, DWH- // tables — user-authored).- const itemDescription =- (item as { description?: unknown })?.description &&- typeof (item as { description?: unknown }).description === 'string'- ? ((item as { description?: string }).description as string)- : undefined- // `getCoreFilterDefinition.description` is typed as `ReactNode`- // (some core defs ship JSX); narrow to string here so the- // returned `TaxonomicAutocompleteItemDetails.description?: string`- // contract holds. Lossy for JSX-shaped descriptions, but the- // current consumers all render plain strings anyway.- const coreDescription = typeof def?.description === 'string' ? def.description : undefined- return {- title,- groupLabel,- rawName: name,- description: coreDescription ?? itemDescription,- example,- propertyType: propertyType ? String(propertyType) : undefined,- isPinned: isPinnable ? isPinned(group.type, value) : false,- isPinnable,- togglePin: () => {- if (isPinnable) {- togglePinAction(group.type, group.name, value, item)- }- },- }- }, [entry, describeProperty, isPinned, togglePinAction])-}--// View-stack slide animations injected once at module load. ease-out-cubic-// (Quill's popover-content easing) at 220ms — long enough to read the-// motion as a "slide" without delaying interaction. 16px travel matches-// what feels like a half-step rather than a twitch. Pseudo-elements don't-// need them; only the two keyframes are exposed.-const VIEW_ANIMATIONS_STYLE_ID = 'taxonomic-autocomplete-view-animations'-if (typeof document !== 'undefined' && !document.getElementById(VIEW_ANIMATIONS_STYLE_ID)) {- const styleEl = document.createElement('style')- styleEl.id = VIEW_ANIMATIONS_STYLE_ID- styleEl.textContent = `-@keyframes taxonomic-slide-from-right {- from { transform: translateX(16px); opacity: 0; }- to { transform: translateX(0); opacity: 1; }-}-@keyframes taxonomic-slide-from-left {- from { transform: translateX(-16px); opacity: 0; }- to { transform: translateX(0); opacity: 1; }-}-@media (prefers-reduced-motion: reduce) {- [data-state="active"] {- animation: none !important;- }-}-`- document.head.appendChild(styleEl)-}--export interface TaxonomicAutocompleteSegmentedTriggerProps {- /** Render the group segment. Defaults to `selected.group.name`. */- renderGroup?: (entry: TaxonomicAutocompleteEntry) => ReactNode- /** Render the item segment. Defaults to friendly label or raw name. */- renderItem?: (entry: TaxonomicAutocompleteEntry) => ReactNode- /** Hide the trailing × button. */- hideClear?: boolean- /**- * Render when nothing is selected. Defaults to a single Button using- * `triggerLabel` / placeholder fallback.- */- renderEmpty?: () => ReactElement- className?: string-}--/**- * `[group | item | ×]` button group. Group segment opens the picker- * (drilled to the selected category); item segment re-opens the- * configurator for the entry (or the picker, if no configurator- * registered); × clears.- */-function SegmentedTrigger({- renderGroup,- renderItem,- hideClear = false,- renderEmpty,- className,-}: TaxonomicAutocompleteSegmentedTriggerProps): JSX.Element {- const ctx = useAutocompleteCtx()- const selected = ctx.selectedEntry-- if (!selected) {- const fallback = renderEmpty ? (- renderEmpty()- ) : (- <Button variant="outline">{ctx.triggerLabel ?? ctx.inputPlaceholder ?? 'Select…'}</Button>- )- return <PopoverTrigger render={fallback} />- }-- const itemHasConfigurator = ctx.configuredTypes.has(selected.group.type)- const itemContent = renderItem ? renderItem(selected) : selected.friendlyLabel || selected.name- const groupContent = renderGroup ? renderGroup(selected) : selected.group.name-- return (- <ButtonGroup className={className}>- <PopoverTrigger- render={- <Button- variant="outline"- onClick={() => ctx.setCategory(selected.group.type)}- data-attr="taxonomic-autocomplete-segment-group"- >- {groupContent}- </Button>- }- />- <Button- variant="outline"- data-attr="taxonomic-autocomplete-segment-item"- onClick={() => {- if (itemHasConfigurator) {- ctx.openConfigureFor(selected)- } else {- ctx.setOpen(true)- }- }}- >- {itemContent}- </Button>- {!hideClear && (- <Button- variant="outline"- aria-label="Clear selection"- data-attr="taxonomic-autocomplete-segment-clear"- onClick={(e: React.MouseEvent<HTMLButtonElement>) => {- e.stopPropagation()- ctx.clearSelection()- }}- >- ×- </Button>- )}- </ButtonGroup>- )-}--/**- * Pinned + suggested entries surfaced through `<MenuTrigger>` shortcuts.- * Pinned items come from `taxonomicFilterPinnedPropertiesLogic`; suggested- * items come from the orchestrator's synthetic `SuggestedFilters` group- * (`group.options`). Both are mapped back to the source group so- * `ctx.onSelectEntry(entry)` commits to the right group.- */-export function useTaxonomicAutocompleteShortcutItems(): {- pinned: TaxonomicAutocompleteEntry[]- suggested: TaxonomicAutocompleteEntry[]-} {- const { groups, excludedProperties } = useTaxonomicFilterContext()- const { pinnedFilterItems } = useValues(taxonomicFilterPinnedPropertiesLogic)-- return useMemo<{ pinned: TaxonomicAutocompleteEntry[]; suggested: TaxonomicAutocompleteEntry[] }>(() => {- const findGroup = (type: TaxonomicFilterGroupType | undefined): TaxonomicFilterGroup | undefined =>- type ? groups.find((g) => g.type === type) : undefined-- const buildEntry = (- item: TaxonomicDefinitionTypes,- sourceType: TaxonomicFilterGroupType | undefined- ): TaxonomicAutocompleteEntry | null => {- const group = findGroup(sourceType)- if (!group) {- return null- }- const name = getRawName(item, group)- return { item, group, name, friendlyLabel: getFriendlyLabel(item, group) }- }-- const pinned: TaxonomicAutocompleteEntry[] = (- pinnedFilterItems as Array<- TaxonomicDefinitionTypes & {- _pinnedContext?: { sourceGroupType?: TaxonomicFilterGroupType; value?: TaxonomicFilterValue }- }- >- )- .map((item) => {- const sourceGroupType = item._pinnedContext?.sourceGroupType- const pinnedValue = item._pinnedContext?.value- const entry = buildEntry(item, sourceGroupType)- // A value the source group excludes must not be offered as a shortcut, the same way- // `filterPinnedForContext` drops it from the Pinned tab. Groups like Logs, Issues, and- // Revenue analytics filter their own options from the root `excludedProperties` map and- // never set `group.excludedProperties`, so read that root map keyed by the source group too.- const rootExcluded = sourceGroupType ? excludedProperties?.[sourceGroupType] : undefined- const isExcluded =- pinnedValue != null &&- (entry?.group.excludedProperties?.includes(pinnedValue as string) ||- rootExcluded?.includes(pinnedValue))- if (isExcluded) {- return null- }- return entry- })- .filter((e): e is TaxonomicAutocompleteEntry => e != null)-- const suggestedGroup = findGroup(TaxonomicFilterGroupType.SuggestedFilters)- const suggestedOptions = ((- suggestedGroup as { options?: Array<{ name: string; group: TaxonomicFilterGroupType }> } | undefined- )?.options ?? []) as Array<{ name: string; group: TaxonomicFilterGroupType }>- const suggested: TaxonomicAutocompleteEntry[] = suggestedOptions- .map((opt) => buildEntry({ name: opt.name } as unknown as TaxonomicDefinitionTypes, opt.group))- .filter((e): e is TaxonomicAutocompleteEntry => e != null)-- return { pinned, suggested }- }, [groups, pinnedFilterItems, excludedProperties])-}--const DEFAULT_MENU_SHORTCUT_GROUPS: readonly TaxonomicFilterGroupType[] = [- TaxonomicFilterGroupType.DataWarehouse,- TaxonomicFilterGroupType.HogQLExpression,-]--export interface TaxonomicAutocompleteMenuTriggerProps {- /**- * Group types managed by the menu — surfaced as menu items, removed- * from popover chips/list. Default: DataWarehouse + HogQLExpression.- */- shortcutGroups?: readonly TaxonomicFilterGroupType[]- /** Label for the "open the search popover" menu item. */- chooseFilterLabel?: ReactNode- /** Static render element passed to the menu trigger. */- render?: ReactElement- /** Render-function form. Receives full trigger state. */- children?: ReactNode | ((state: TaxonomicAutocompleteTriggerState) => ReactElement)-}--/**- * Dropdown-menu trigger that fronts the popover with quick-action items.- * Click → opens menu, menu offers:- * - "Choose filter…" → opens the popover (search list)- * - Pinned items → commit directly- * - Suggested items → commit directly- * - Per-shortcut group → DWH opens popover at DWH category, HogQL opens- * the editor sub-page- *- * Composes Popover + DropdownMenu on the same button via `render` so the- * popover can still anchor to the trigger (PopoverWrapper gates the- * trigger-press so the click only opens the menu, not the popover).- */-function MenuTrigger({- shortcutGroups = DEFAULT_MENU_SHORTCUT_GROUPS,- chooseFilterLabel = 'Choose filter…',- render,- children,-}: TaxonomicAutocompleteMenuTriggerProps): JSX.Element {- const ctx = useAutocompleteCtx()- const { groups } = useTaxonomicFilterContext()- const { pinned, suggested } = useTaxonomicAutocompleteShortcutItems()- const [menuOpen, setMenuOpen] = useState(false)-- // Register shortcut groups + flag the trigger so PopoverWrapper gates- // the trigger-press. Stable join key avoids re-running on render.- const key = shortcutGroups.join(',')- useEffect(() => {- shortcutGroups.forEach((t) => ctx.addDropdownManagedType(t))- ctx.setHasMenuTrigger(true)- return () => {- shortcutGroups.forEach((t) => ctx.removeDropdownManagedType(t))- ctx.setHasMenuTrigger(false)- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [key])-- const selected = ctx.selectedEntry- const label =- (selected?.friendlyLabel && selected.friendlyLabel.length > 0 ? selected.friendlyLabel : selected?.name) ||- ctx.triggerLabel ||- ctx.inputPlaceholder ||- 'Filter'- const state: TaxonomicAutocompleteTriggerState = {- open: ctx.open,- selected,- label,- placeholder: ctx.inputPlaceholder,- value: ctx.value,- category: ctx.category,- clearSelection: ctx.clearSelection,- }- let triggerEl: ReactElement- if (typeof children === 'function') {- triggerEl = children(state)- } else if (render) {- triggerEl = render- } else {- triggerEl = <Button variant="outline">{label}</Button>- }-- const dwhGroup = groups.find((g) => g.type === TaxonomicFilterGroupType.DataWarehouse)- const hogqlGroup = groups.find((g) => g.type === TaxonomicFilterGroupType.HogQLExpression)- const showDwhShortcut = shortcutGroups.includes(TaxonomicFilterGroupType.DataWarehouse) && !!dwhGroup- const showHogqlShortcut = shortcutGroups.includes(TaxonomicFilterGroupType.HogQLExpression) && !!hogqlGroup-- return (- <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>- {/* Single button = both the menu trigger AND the popover anchor.- base-ui composes both components' props onto the same DOM- node via render. Clicks open the menu; the popover's- trigger-press reason is dropped in PopoverWrapper so it- doesn't auto-open. Programmatic opens (menu items calling- ctx.setOpen) bypass the gate. */}- <DropdownMenuTrigger render={<PopoverTrigger render={triggerEl} />} />- <DropdownMenuContent align="start" className="min-w-[240px]">- <DropdownMenuItem- onClick={() => {- setMenuOpen(false)- ctx.setOpen(true)- }}- data-attr="taxonomic-menu-choose-filter"- >- {chooseFilterLabel}- </DropdownMenuItem>- {pinned.length > 0 && (- <>- <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuLabel>Pinned</DropdownMenuLabel>- {pinned.map((entry) => {- const entryValue = entry.group.getValue?.(entry.item)- const itemKey = `pinned-${entry.group.type}-${String(entryValue ?? entry.name)}`- return (- <DropdownMenuItem- key={itemKey}- onClick={() => {- setMenuOpen(false)- ctx.onSelectEntry(entry)- }}- >- {entry.friendlyLabel ?? entry.name}- </DropdownMenuItem>- )- })}- </DropdownMenuGroup>- </>- )}- {suggested.length > 0 && (- <>- <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuLabel>Suggested</DropdownMenuLabel>- {suggested.map((entry) => {- const entryValue = entry.group.getValue?.(entry.item)- const itemKey = `suggested-${entry.group.type}-${String(entryValue ?? entry.name)}`- return (- <DropdownMenuItem- key={itemKey}- onClick={() => {- setMenuOpen(false)- ctx.onSelectEntry(entry)- }}- >- {entry.friendlyLabel ?? entry.name}- </DropdownMenuItem>- )- })}- </DropdownMenuGroup>- </>- )}- {(showDwhShortcut || showHogqlShortcut) && <DropdownMenuSeparator />}- {showDwhShortcut && dwhGroup && (- <DropdownMenuItem- onClick={() => {- setMenuOpen(false)- ctx.setCategory(TaxonomicFilterGroupType.DataWarehouse)- ctx.setOpen(true)- }}- data-attr="taxonomic-menu-shortcut-dwh"- >- {dwhGroup.name}- </DropdownMenuItem>- )}- {showHogqlShortcut && hogqlGroup && (- <DropdownMenuItem- onClick={() => {- setMenuOpen(false)- const synthetic: IndexedItem = {- item: { name: hogqlGroup.name } as TaxonomicDefinitionTypes,- group: hogqlGroup,- name: hogqlGroup.name,- }- ctx.openConfigureFor(synthetic)- ctx.setOpen(true)- }}- data-attr="taxonomic-menu-shortcut-hogql"- >- {hogqlGroup.name}- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>- )-}--export const TaxonomicAutocomplete = {- Root,- Popover: PopoverWrapper,- Trigger,- MenuTrigger,- SegmentedTrigger,- Content,- Header,- RootView,- ConfigureView,- DetailsView,- Input,- Chips,- List,- Empty,- Items,-}--/**- * Convenience composition that mirrors the previous monolithic component.- * Renders trigger + popover with input on top, category chips below input,- * then the result list. Use the granular `TaxonomicAutocomplete.*` parts- * (and `useTaxonomicAutocompleteCategories`) when you need a different- * layout — e.g. categories as a dropdown menu instead of chips.- */-export interface TaxonomicFilterAutocompleteInputProps extends Omit<TaxonomicAutocompleteRootProps, 'children'> {- /**- * Custom trigger. Either a static element, or a render function- * `(state) => ReactElement` that receives full trigger state (selected- * entry, value, open, label, …) so the consumer can render the trigger- * however they want — e.g. show the selected value as a chip.- */- trigger?: ReactElement | ((state: TaxonomicAutocompleteTriggerState) => ReactElement)- /** Class on the popover content surface. */- contentClassName?: string-}--export function TaxonomicFilterAutocompleteInput({- trigger,- contentClassName,- ...rootProps-}: TaxonomicFilterAutocompleteInputProps): JSX.Element | null {- return (- <TaxonomicAutocomplete.Root {...rootProps}>- <TaxonomicAutocomplete.Popover>- {typeof trigger === 'function' ? (- <TaxonomicAutocomplete.Trigger>{trigger}</TaxonomicAutocomplete.Trigger>- ) : (- <TaxonomicAutocomplete.Trigger render={trigger} />- )}- <TaxonomicAutocomplete.Content className={contentClassName}>- <TaxonomicAutocomplete.Header />- <TaxonomicAutocomplete.RootView>- <div className="p-4">- <TaxonomicAutocomplete.Input />- </div>- <TaxonomicAutocomplete.Chips className="border-t" />- <TaxonomicAutocomplete.List />- </TaxonomicAutocomplete.RootView>- </TaxonomicAutocomplete.Content>- </TaxonomicAutocomplete.Popover>- </TaxonomicAutocomplete.Root>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/Categories.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/Categories.tsxdeleted file mode 100644index b995ad3aef03..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/Categories.tsx+++ /dev/null@@ -1,79 +0,0 @@-import { ReactNode } from 'react'--import { Button } from '@posthog/quill'--import { useGroupList } from '../hooks/useGroupList'-import { TaxonomicFilterGroup } from '../types'-import { useTaxonomicFilterContext } from './context'--export interface TaxonomicFilterCategoriesProps {- /** Override how each tab is rendered. */- renderTab?: (props: TaxonomicFilterCategoryRenderProps) => ReactNode- className?: string-}--export interface TaxonomicFilterCategoryRenderProps {- group: TaxonomicFilterGroup- isActive: boolean- count: number- isLoading: boolean- onSelect: () => void-}--export function TaxonomicFilterCategories({ renderTab, className }: TaxonomicFilterCategoriesProps): JSX.Element {- const { groups } = useTaxonomicFilterContext()- return (- <div className={className} role="tablist">- {groups.map((group) => (- <TaxonomicFilterCategoryTab key={group.type} group={group} renderTab={renderTab} />- ))}- </div>- )-}--interface CategoryTabProps {- group: TaxonomicFilterGroup- renderTab?: (props: TaxonomicFilterCategoryRenderProps) => ReactNode-}--function TaxonomicFilterCategoryTab({ group, renderTab }: CategoryTabProps): JSX.Element {- const { activeGroupType, setActiveGroupType, getGroupListInput } = useTaxonomicFilterContext()- const list = useGroupList(getGroupListInput(group))- const isActive = activeGroupType === group.type- const onSelect = (): void => setActiveGroupType(group.type)-- if (renderTab) {- return (- <>- {renderTab({- group,- isActive,- count: list.totalResultCount,- isLoading: list.isLoading,- onSelect,- })}- </>- )- }-- return (- <Button- type="button"- role="tab"- data-attr={`taxonomic-tab-${group.type}`}- aria-selected={isActive}- variant={isActive ? 'primary' : 'outline'}- size="sm"- onClick={onSelect}- >- {group.categoryLabel ? (- group.categoryLabel(list.totalResultCount)- ) : (- <>- {group.name}- {!list.needsMoreSearchCharacters && `: ${list.isLoading ? '…' : list.totalResultCount}`}- </>- )}- </Button>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/Input.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/Input.tsxdeleted file mode 100644index 8aa082f4d078..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/Input.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { InputHTMLAttributes, forwardRef } from 'react'--import { InputGroup, InputGroupInput } from '@posthog/quill'--import { useTaxonomicFilterContext } from './context'--export interface TaxonomicFilterInputProps extends Omit<- InputHTMLAttributes<HTMLInputElement>,- // `prefix` exists on `HTMLAttributes` typed as `string` (RDFa);- // we redeclare it as `ReactNode` for the slot, so omit the parent- // version to avoid the structural mismatch error from ts.- 'value' | 'onChange' | 'onKeyDown' | 'prefix'-> {- /** Override the placeholder produced by useTaxonomicFilter. */- placeholder?: string- /** Class on the wrapping InputGroup. */- className?: string- /** Class on the inner input element. */- inputClassName?: string- /** Slot rendered before the input (e.g. a search icon). */- prefix?: React.ReactNode- /** Slot rendered after the input (e.g. a clear button or count). */- suffix?: React.ReactNode-}--/**- * TaxonomicFilter search input.- *- * Wraps Quill's `<InputGroup>` + `<InputGroupInput>` (which themselves wrap- * Base UI's `<Input>` primitive). Spreads `inputProps` from the orchestrator- * onto the input element so search + keyboard nav are wired automatically.- */-export const TaxonomicFilterInput = forwardRef<HTMLInputElement, TaxonomicFilterInputProps>(- function TaxonomicFilterInput(- { placeholder, className, inputClassName, prefix, suffix, ...rest },- ref- ): JSX.Element {- const { inputProps } = useTaxonomicFilterContext()- return (- <InputGroup className={className}>- {prefix}- <InputGroupInput- ref={ref}- type="search"- data-attr="taxonomic-filter-searchfield"- className={inputClassName}- {...rest}- {...inputProps}- placeholder={placeholder ?? inputProps.placeholder}- />- {suffix}- </InputGroup>- )- }-)diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/Panel.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/Panel.tsxdeleted file mode 100644index fd923b4742a0..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/Panel.tsx+++ /dev/null@@ -1,196 +0,0 @@-import { ReactNode, useCallback, useEffect, useRef, useState } from 'react'--import { IconWarning } from '@posthog/icons'-import { Button, Empty, EmptyHeader, EmptyTitle, ItemMenuItem, Spinner } from '@posthog/quill'--import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'--import { useGroupList, UseGroupListResult } from '../hooks/useGroupList'-import { hasRecentContext } from '../recentTaxonomicFiltersLogic'-import { TaxonomicDefinitionTypes, TaxonomicFilterGroup } from '../types'-import { useTaxonomicFilterContext } from './context'--export interface TaxonomicFilterPanelProps {- /** Override the row renderer. Receives item + per-row state. */- renderRow?: (props: TaxonomicFilterRowRenderProps) => ReactNode- /** Slot shown when the active list returns showEmptyState=true. */- emptyState?: ReactNode- /** Slot shown when the active list returns showLoadingState=true. */- loadingState?: ReactNode- className?: string-}--export interface TaxonomicFilterRowRenderProps {- item: TaxonomicDefinitionTypes- index: number- isActive: boolean- onSelect: () => void- onMouseEnter: () => void- group: TaxonomicFilterGroup-}--/** Renders the active group's items. Internally calls `useGroupList` for the- * active group AND registers its api with the orchestrator so keyboard- * navigation routes through this list. */-export function TaxonomicFilterPanel({- renderRow,- emptyState,- loadingState,- className,-}: TaxonomicFilterPanelProps): JSX.Element | null {- const { activeGroup } = useTaxonomicFilterContext()- if (!activeGroup) {- return null- }- return (- <TaxonomicFilterActivePanel- key={activeGroup.type}- group={activeGroup}- renderRow={renderRow}- emptyState={emptyState}- loadingState={loadingState}- className={className}- />- )-}--interface ActivePanelProps {- group: TaxonomicFilterGroup- renderRow?: (props: TaxonomicFilterRowRenderProps) => ReactNode- emptyState?: ReactNode- loadingState?: ReactNode- className?: string-}--function TaxonomicFilterActivePanel({- group,- renderRow,- emptyState,- loadingState,- className,-}: ActivePanelProps): JSX.Element {- const { getGroupListInput, registerActiveList, selectItem, searchQuery } = useTaxonomicFilterContext()- const list: UseGroupListResult = useGroupList(getGroupListInput(group))- // `useTaxonomicResource`'s cache only notifies subscribers once a fetch settles, not when- // it starts, so `list.isFetching` doesn't flip to true for the duration of an imperative- // `refetch()` call here. Track the retry's own in-flight state instead, so the button shows- // a loading state and can't be clicked again mid-retry.- const [retrying, setRetrying] = useState(false)- const handleRetry = useCallback(async (): Promise<void> => {- setRetrying(true)- try {- await list.refetch()- } finally {- setRetrying(false)- }- }, [list])-- // Register this list as the keyboard target for as long as the panel- // is mounted. We pass a stable getter (`useRef`-backed) instead of- // the `list` object itself so the registration doesn't churn on- // every render — `useGroupList` returns a fresh reference each- // render, and registering it directly produced a brief null window- // between cleanup and re-register that broke `selectSelected()`- // under concurrent rendering.- const listRef = useRef(list)- listRef.current = list- useEffect(() => {- registerActiveList(() => listRef.current)- return () => registerActiveList(null)- }, [registerActiveList])-- if (list.showLoadingState) {- return (- <div className={className}>- {loadingState !== undefined ? (- loadingState- ) : (- <Empty>- <EmptyHeader>- <Spinner />- <EmptyTitle>Loading…</EmptyTitle>- </EmptyHeader>- </Empty>- )}- </div>- )- }-- if (list.showErrorState) {- return (- <div className={className}>- <Empty>- <EmptyHeader>- <IconWarning className="text-5xl text-tertiary" />- <EmptyTitle>Couldn't load results</EmptyTitle>- </EmptyHeader>- <Button- variant="outline"- size="sm"- data-attr="taxonomic-panel-retry"- loading={retrying}- onKeyDown={(event) => event.stopPropagation()}- onClick={handleRetry}- >- Try again- </Button>- </Empty>- </div>- )- }-- if (list.showEmptyState) {- return (- <div className={className}>- {emptyState !== undefined ? (- emptyState- ) : (- <Empty>- <EmptyHeader>- <EmptyTitle>- {list.needsMoreSearchCharacters- ? 'Type more to search'- : group.shouldSearch?.(searchQuery) === false- ? (group.searchQueryHint ?? 'No results')- : 'No results'}- </EmptyTitle>- </EmptyHeader>- </Empty>- )}- </div>- )- }-- return (- <div className={className} role="listbox" data-attr={`taxonomic-list-${group.type}`}>- {list.items.map((item, index) => {- const isActive = list.index === index- const onSelect = (): void => {- const itemValue = group.getValue?.(item) ?? null- selectItem(group, itemValue, item)- }- const onMouseEnter = (): void => list.setIndex(index)- if (renderRow) {- return <div key={index}>{renderRow({ item, index, isActive, onSelect, onMouseEnter, group })}</div>- }- const label =- hasRecentContext(item) && item._recentContext.propertyFilter- ? formatPropertyLabel(item._recentContext.propertyFilter, {})- : (group.getName?.(item) ?? ('name' in item ? (item as { name?: string }).name : ''))- return (- <ItemMenuItem- key={index}- size="sm"- role="option"- aria-selected={isActive}- data-attr={`taxonomic-row-${group.type}-${index}`}- onClick={onSelect}- onMouseEnter={onMouseEnter}- >- {label}- </ItemMenuItem>- )- })}- </div>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/Root.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/Root.tsxdeleted file mode 100644index 629427d8bf0f..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/Root.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { ReactNode } from 'react'--import { useTaxonomicFilter, UseTaxonomicFilterOptions } from '../hooks/useTaxonomicFilter'-import { TaxonomicFilterContext } from './context'--export interface TaxonomicFilterRootProps extends UseTaxonomicFilterOptions {- children: ReactNode- className?: string- /** Spread `rootProps` (incl. onKeyDown) onto this wrapper. Default true. */- bindRootProps?: boolean-}--export function TaxonomicFilterRoot({- children,- className,- bindRootProps = true,- ...opts-}: TaxonomicFilterRootProps): JSX.Element {- const api = useTaxonomicFilter(opts)- return (- <TaxonomicFilterContext.Provider value={api} data-quill>- <div className={className} {...(bindRootProps ? api.rootProps : {})}>- {children}- </div>- </TaxonomicFilterContext.Provider>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/UX_SPEC.md b/frontend/src/lib/components/TaxonomicFilter/headless/UX_SPEC.mddeleted file mode 100644index 94182804d7e7..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/UX_SPEC.md+++ /dev/null@@ -1,213 +0,0 @@-# Taxonomic filter — UX spec--Source of truth for the dropdown-menu-fronted taxonomic filter. Edit this-doc to lock the design, then rebuild fresh against it. No hooks-based-plumbing required — keep state local where it lives, pass refs/callbacks-when components have to coordinate.-------## High-level flow--```text-[ trigger button ]- │ click- ▼-┌─────────────────────────────┐-│ DropdownMenu │-│ ─ New filter… │ → opens combobox (search across all groups)-│ ─ Recent │ → opens combobox seeded to "recent"-│ ─ Pinned │ → opens combobox seeded to "pinned"-│ ─ ───────────── │-│ ─ Data warehouse tables ▶ │ → submenu: list of tables → on pick, open-│ │ inline DWH config (id / timestamp / distinct)-│ ─ HogQL expression │ → submenu / page: SQL editor → commit on save-└─────────────────────────────┘-```--The dropdown is the **first thing** the user sees. It surfaces the most-common quick-actions (Recent / Pinned) without forcing a search step, and-hides power-user options (DWH / HogQL) inside a focused sub-flow so-they're one click away but don't clutter the combobox.-------## Trigger--- One button, label = current selected entry's friendly name, or `"Filter"` (or- consumer-supplied) when nothing is selected.-- Click → opens the dropdown menu. Nothing else.-- Keyboard: Enter / Space when focused opens the menu. Esc closes.--The trigger is a regular button — no compose-with-popover-trigger trick,-no anchor games. Both the dropdown menu AND the combobox popover anchor-to this button (the combobox via `Popover.Positioner` `anchor` prop using-the trigger's ref).-------## Dropdown menu items--| Item | Behavior |-| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **New filter…** | Closes menu, opens combobox. Combobox starts on the "All" category, search input focused, list shows everything. |-| **Recent** | Closes menu, opens combobox **drilled into the Recent category** (doesn't show chips). List shows recent entries. Search filters within recent. Show header with name, back button to dropdownmenu |-| **Pinned** | Same as Recent, but for the Pinned category. Doesn't show chips, Show header with name, with back button to dropdownmenu . |-| ─ separator ─ | |-| **Data warehouse tables ▶** | Submenu (chevron). Hover/click opens it. Show header with name, with back button to dropdownmenu |-| **HogQL expression** | Closes menu, opens HogQL editor _directly_ (skips the combobox). On save, commits the expression as the selection. Show header with name, with back button to dropdownmenu |--### Conditional rendering--- **Recent** / **Pinned**: only render when there are entries to show. If- the user has zero pinned items, omit the row entirely (don't show an- empty section).-- **Data warehouse tables**: only render when the consumer's- `taxonomicGroupTypes` includes `DataWarehouse`.-- **HogQL expression**: only render when the consumer's- `taxonomicGroupTypes` includes `HogQLExpression`.--These two groups (`DataWarehouse`, `HogQLExpression`) are **removed from-the combobox's category chips and item list** when surfaced via the-menu — the user gets to them through one menu, not two.-------## Data warehouse submenu--Hover (or arrow-right) on the menu item opens a **submenu** listing-available tables (e.g. `extended_properties`, `paid_bills`, `signups`).--On clicking a table:--1. Submenu closes-2. Main menu closes-3. **Inline DWH config form** opens — same chrome as the combobox popover- (anchored to trigger), but with a header `< Configure data warehouse-table` and the form body (ID field / Timestamp field / Distinct ID- field selects + Cancel / Select buttons).-4. Save → commits the entry with the chosen columns merged into `item`.-5. Cancel / Esc / `<` back → closes the form, returns to root popover- state (or closes everything if reached via the menu).--Submenu nav: arrow keys cycle tables. Enter to pick. Esc to back out to-parent menu.-------## HogQL expression flow--Click "HogQL expression" → menu closes → **expression editor opens**-directly (no combobox stop-over). Editor is the same inline view-stack-page as DWH (header with back button, body = SQL textarea / Monaco,-footer with Cancel / Save).--Save → commits `{ name: <expression>, value: <expression> }` and closes.-Cancel / Esc → closes without committing.-------## Combobox popover--Reached from "New filter…", "Recent", "Pinned", or after the user picks-a Recent/Pinned shortcut that doesn't immediately commit (e.g. category-drill).--- Search input at top — focused on open.-- Category chips below — `All` plus one per visible group (excluding- Recent / Pinned / Suggested / DataWarehouse / HogQLExpression — all- surfaced via the menu). Click chip to filter list. Tab cycles chips.-- Result list — single-cell rows by default. Each row shows- - friendly title (or raw name)- - `[GROUP NAME]` badge — only in the `All` category (redundant when- drilled)- - subtitle (raw name) when it differs from friendly- - hover popover (preview card / tooltip) with description / type /- sent-as / pin button — opt-in per group via consumer config-- Footer / chrome — none. Esc closes; clicking outside closes.--Click a row → commits the entry, closes popover.--### View stack inside popover--Sub-pages slide in from the right with the same chrome as the root view:--- Header gets a `<` back button + page title-- Sub-page body fills the popover envelope-- Esc / back button → pops to root--Only DWH config and HogQL editor live here. (Property "View details"-sheet was prototyped but parked.)-------## Sizing & position--- Popover height is **fixed** (`h-[400px]`) so view-stack swaps- (root → sub-page → root) don't reflow Floating UI's positioning.-- Width = `--anchor-width` (matches trigger width), `min-w-[320px]`.-- List inside scrolls; surrounding chrome (header, input, chips) is- pinned.-- Position recomputed once on open; pinned thereafter.-------## Selection behavior--- `selectedEntry` lives on the picker (controlled or uncontrolled).-- Trigger reflects the latest selection's friendly name.-- Recent + Pinned items in the menu are direct shortcuts — clicking- commits without entering the combobox.-- Clearing selection: trigger may render a × affordance, or consumer- handles via separate button.-------## Keyboard summary--| Context | Key | Action |-| -------- | -------------------- | ---------------------------------- |-| Trigger | Enter / Space | Open menu |-| Menu | ↑/↓ | Navigate items |-| Menu | → on submenu trigger | Enter submenu |-| Menu | Enter | Activate item |-| Menu | Esc | Close menu |-| Combobox | Type | Filter list |-| Combobox | ↑/↓ | Navigate rows |-| Combobox | Enter | Commit highlighted row |-| Combobox | Tab / Shift+Tab | Cycle category chips |-| Combobox | Esc (drilled) | Back to All |-| Combobox | Esc (root) | Close popover |-| Sub-page | Esc / `<` | Back to root view |-| Sub-page | Tab | Cycle within form (loops on edges) |-------## What we are NOT building (yet)--- Property "View details" sheet (description / pin / edit / open) —- parked. Hover popover may surface this later.-- Multi-select in the combobox — out of scope.-- Sticky search input across categories — input clears on chip change.-- Nested sub-menus beyond DWH tables — flat menu otherwise.-------## Implementation notes (for the rebuild)--- **No global hooks for menu/sub-page registration.** Components- coordinate via props + refs passed from a thin parent that owns the- open state machine.-- **One open-state machine** at the parent level — discriminated union- is fine: `{ kind: 'closed' } | { kind: 'menu' } | { kind: 'combobox', drillTo?: GroupType } | { kind: 'dwh-config', table } | { kind: 'hogql-edit' }`. Transitions are explicit.-- **Trigger button ref** — single ref, shared between menu (anchors via- base-ui `DropdownMenu`'s own trigger registration) and combobox- (anchors via `Popover.Positioner` `anchor` prop). Don't compose two- trigger components on one button.-- **Menu and combobox never open simultaneously.** Closing the menu and- opening the combobox happens in the same state transition.-- **DWH / HogQL data is consumer-supplied** — no kea coupling inside the- widget. The picker takes `dataWarehouseTables: Array<{ name, fields }>`- and `onCommit(entry)`; consumer wires kea selectors externally.-- **Recent / Pinned data**: same — passed in as `recent: Entry[]`,- `pinned: Entry[]` props (consumer reads from whatever logic).diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/context.ts b/frontend/src/lib/components/TaxonomicFilter/headless/context.tsdeleted file mode 100644index f7bf01aa8428..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/context.ts+++ /dev/null@@ -1,16 +0,0 @@-import { createContext, useContext } from 'react'--import { TaxonomicFilterApi } from '../hooks/useTaxonomicFilter'--export const TaxonomicFilterContext = createContext<TaxonomicFilterApi | null>(null)--export function useTaxonomicFilterContext(): TaxonomicFilterApi {- const ctx = useContext(TaxonomicFilterContext)- if (!ctx) {- throw new Error(- 'useTaxonomicFilterContext must be used inside <TaxonomicFilter.Root>. ' +- 'Wrap your TaxonomicFilter sub-components in <TaxonomicFilter.Root>.'- )- }- return ctx-}diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/headless.test.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/headless.test.tsxdeleted file mode 100644index 4cfc40a92f3f..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/headless.test.tsx+++ /dev/null@@ -1,308 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, renderHook, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { Provider } from 'kea'--import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { groupsModel } from '~/models/groupsModel'-import { performQuery } from '~/queries/query'-import { initKeaTests } from '~/test/init'-import { emptyPaginated } from '~/test/mocks/taxonomicFilterApiMock'-import { PropertyFilterType, PropertyOperator } from '~/types'--import { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'-import { recentTaxonomicFiltersLogic } from '../recentTaxonomicFiltersLogic'-import { taxonomicFilterPinnedPropertiesLogic } from '../taxonomicFilterPinnedPropertiesLogic'-import { TaxonomicFilterGroupType } from '../types'-import { TaxonomicFilterHeadless, useTaxonomicAutocompleteShortcutItems } from './index'--jest.mock('~/queries/query', () => ({- performQuery: jest.fn(),-}))--jest.mock('lib/api', () =>- require('~/test/mocks/taxonomicFilterApiMock').buildTaxonomicFilterApiMock({ get: jest.fn() })-)--const apiGet = jest.requireMock('lib/api').default.get as jest.MockedFunction<any>--describe('TaxonomicFilterHeadless integration', () => {- let onChangeMock: jest.Mock- let user: ReturnType<typeof userEvent.setup>-- beforeEach(() => {- __clearTaxonomicResourceCache()- apiGet.mockReset()- apiGet.mockImplementation(emptyPaginated)- ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })- useMocks({- get: { '/api/projects/:team/event_definitions': { results: [], count: 0 } },- post: { '/api/environments/:team/query': { results: [] } },- })- initKeaTests()- actionsModel.mount()- groupsModel.mount()- onChangeMock = jest.fn()- user = userEvent.setup()- })-- afterEach(() => cleanup())-- function renderHeadless(): void {- render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Wildcards]}- onChange={onChangeMock}- optionsFromProp={{- [TaxonomicFilterGroupType.Wildcards]: [{ name: 'wildcard-a' }, { name: 'wildcard-b' }],- }}- >- <TaxonomicFilterHeadless.Input />- <TaxonomicFilterHeadless.Categories />- <TaxonomicFilterHeadless.Panel- emptyState={<div data-attr="empty">No results</div>}- loadingState={<div data-attr="loading">Loading…</div>}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )- }-- it('mounts Root, Input, Categories and Panel without throwing', () => {- apiGet.mockResolvedValue({ results: [{ id: 1, name: 'pageview' }], count: 1 })- renderHeadless()- expect(screen.getByTestId('taxonomic-filter-searchfield')).toBeInTheDocument()- expect(screen.getByTestId('taxonomic-tab-events')).toBeInTheDocument()- expect(screen.getByTestId('taxonomic-tab-wildcard')).toBeInTheDocument()- })-- it("renders the active tab's items in the Panel", async () => {- apiGet.mockResolvedValue({- results: [- { id: 1, name: 'pageview' },- { id: 2, name: 'click' },- ],- count: 2,- })- renderHeadless()- // Events group prepends a static "All events" option, then remote results follow.- await waitFor(() => expect(screen.getByText('pageview')).toBeInTheDocument())- expect(screen.getByText('click')).toBeInTheDocument()- })-- it('typing in the Input filters via the search query', async () => {- apiGet.mockImplementation((url: string) => {- if (url.includes('search=click')) {- return Promise.resolve({ results: [{ id: 2, name: 'click' }], count: 1 })- }- return Promise.resolve({- results: [- { id: 1, name: 'pageview' },- { id: 2, name: 'click' },- ],- count: 2,- })- })- renderHeadless()- await waitFor(() => expect(screen.getByText('pageview')).toBeInTheDocument())- await user.type(screen.getByTestId('taxonomic-filter-searchfield'), 'click')- await waitFor(() => expect(screen.queryByText('pageview')).not.toBeInTheDocument())- expect(screen.getByText('click')).toBeInTheDocument()- })-- it('clicking a row fires onChange', async () => {- const item = { id: 7, name: 'pageview' }- apiGet.mockResolvedValue({ results: [item], count: 1 })- renderHeadless()- await waitFor(() => screen.getByText('pageview'))- await user.click(screen.getByText('pageview'))- expect(onChangeMock).toHaveBeenCalledWith(- expect.objectContaining({ type: TaxonomicFilterGroupType.Events }),- 'pageview',- item- )- })-- it("switching tabs renders the other tab's items", async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })- renderHeadless()- await user.click(screen.getByTestId('taxonomic-tab-wildcard'))- await waitFor(() => expect(screen.getByText('wildcard-a')).toBeInTheDocument())- expect(screen.getByText('wildcard-b')).toBeInTheDocument()- })-- it('Enter selects the highlighted row', async () => {- const item = { id: 1, name: 'pageview' }- apiGet.mockResolvedValue({ results: [item], count: 1 })- renderHeadless()- await waitFor(() => screen.getByText('pageview'))- const input = screen.getByTestId('taxonomic-filter-searchfield')- ;(input as HTMLInputElement).focus()- // Hovering 'pageview' bumps the registered list's index to its row.- // userEvent.hover dispatches mouseenter, which our Panel routes into- // useGroupList.setIndex.- await user.hover(screen.getByText('pageview'))- await user.keyboard('{Enter}')- expect(onChangeMock).toHaveBeenCalledWith(- expect.objectContaining({ type: TaxonomicFilterGroupType.Events }),- 'pageview',- item- )- })-- it.each(['{Enter}', ' '])('retries a failed search with %s without selecting the query', async (key) => {- const onEnter = jest.fn()- apiGet.mockRejectedValue(new Error('search unavailable'))- render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}- onChange={onChangeMock}- onEnter={onEnter}- searchQuery="needle"- >- <TaxonomicFilterHeadless.Panel />- </TaxonomicFilterHeadless.Root>- </Provider>- )- await waitFor(() => expect(screen.getByTestId('taxonomic-panel-retry')).toBeInTheDocument())- apiGet.mockClear()- apiGet.mockResolvedValue({ results: [{ name: 'needle_result' }], count: 1 })-- await user.tab()- expect(screen.getByTestId('taxonomic-panel-retry')).toHaveFocus()- await user.keyboard(key)-- await waitFor(() => expect(screen.getByText('needle_result')).toBeInTheDocument())- expect(apiGet).toHaveBeenCalledTimes(1)- expect(onEnter).not.toHaveBeenCalled()- expect(onChangeMock).not.toHaveBeenCalled()- })-- it('shows the empty-state slot when local search returns nothing', async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })- renderHeadless()- await user.click(screen.getByTestId('taxonomic-tab-wildcard'))- await user.type(screen.getByTestId('taxonomic-filter-searchfield'), 'no-match-zzz')- await waitFor(() => expect(screen.getByTestId('empty')).toBeInTheDocument())- })-- it('renders a complete recent as both a full row and a bare key row', async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })- const recents = recentTaxonomicFiltersLogic.build()- recents.mount()- recents.actions.recordRecentFilter({- groupType: TaxonomicFilterGroupType.EventProperties,- groupName: 'Event properties',- value: '$browser',- item: { name: '$browser' },- propertyFilter: {- type: PropertyFilterType.Event,- key: '$browser',- operator: PropertyOperator.Exact,- value: 'Chrome',- },- })-- render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[- TaxonomicFilterGroupType.EventProperties,- TaxonomicFilterGroupType.RecentFilters,- ]}- onChange={onChangeMock}- >- <TaxonomicFilterHeadless.Input />- <TaxonomicFilterHeadless.Categories />- <TaxonomicFilterHeadless.Panel />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- await user.click(screen.getByTestId('taxonomic-tab-recent_filters'))-- await waitFor(() => {- expect(screen.getByTestId('taxonomic-row-recent_filters-0')).toBeInTheDocument()- })- const bareKeyRow = screen.getByTestId('taxonomic-row-recent_filters-0')- expect(bareKeyRow.textContent).toMatch(/browser/i)- expect(bareKeyRow.textContent).not.toMatch(/Chrome/)- expect(screen.getByTestId('taxonomic-row-recent_filters-1').textContent).toMatch(/Chrome/)-- recents.unmount()- })-- it('expands a complete recent on first render when RecentFilters is the initial group', async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })- const recents = recentTaxonomicFiltersLogic.build()- recents.mount()- recents.actions.recordRecentFilter({- groupType: TaxonomicFilterGroupType.EventProperties,- groupName: 'Event properties',- value: '$browser',- item: { name: '$browser' },- propertyFilter: {- type: PropertyFilterType.Event,- key: '$browser',- operator: PropertyOperator.Exact,- value: 'Chrome',- },- })-- render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[- TaxonomicFilterGroupType.RecentFilters,- TaxonomicFilterGroupType.EventProperties,- ]}- groupType={TaxonomicFilterGroupType.RecentFilters}- onChange={onChangeMock}- >- <TaxonomicFilterHeadless.Panel />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- await waitFor(() => {- expect(screen.getByTestId('taxonomic-list-recent_filters')).toBeInTheDocument()- })- expect(screen.getByTestId('taxonomic-row-recent_filters-0').textContent).toMatch(/browser/i)- expect(screen.getByTestId('taxonomic-row-recent_filters-0').textContent).not.toMatch(/Chrome/)- expect(screen.getByTestId('taxonomic-row-recent_filters-1').textContent).toMatch(/Chrome/)-- recents.unmount()- })-- // A pin outlives the picker it was made in, so without this the shortcut row is another door- // to selecting a value the exclusion forbids.- it.each([- ['$exception', false],- ['checkout_started', true],- ])('offers the pinned shortcut %p: %p', (pinnedName, expected) => {- const pinnedLogic = taxonomicFilterPinnedPropertiesLogic.build()- pinnedLogic.mount()- pinnedLogic.actions.togglePin(TaxonomicFilterGroupType.Events, 'Events', pinnedName, { name: pinnedName })-- const { result } = renderHook(() => useTaxonomicAutocompleteShortcutItems(), {- wrapper: ({ children }) => (- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}- onChange={onChangeMock}- excludedProperties={{ [TaxonomicFilterGroupType.Events]: ['$exception'] }}- >- {children}- </TaxonomicFilterHeadless.Root>- </Provider>- ),- })-- expect(result.current.pinned.some((e) => e.name === pinnedName)).toBe(expected)- pinnedLogic.unmount()- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/index.ts b/frontend/src/lib/components/TaxonomicFilter/headless/index.tsdeleted file mode 100644index a7839d4620f6..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/headless/index.ts+++ /dev/null@@ -1,66 +0,0 @@-/**- * Headless TaxonomicFilter primitives.- *- * <TaxonomicFilter.Root taxonomicGroupTypes={...} onChange={...}>- * <TaxonomicFilter.Input />- * <TaxonomicFilter.Categories />- * <TaxonomicFilter.Panel />- * </TaxonomicFilter.Root>- *- * Each primitive accepts an `className` (single, no plural classNames slot)- * and most accept an explicit render override for full control.- */-import { TaxonomicAutocomplete, TaxonomicFilterAutocompleteInput } from './AutocompleteInput'-import { TaxonomicFilterCategories } from './Categories'-import { TaxonomicFilterInput } from './Input'-import { TaxonomicFilterPanel } from './Panel'-import { TaxonomicFilterRoot } from './Root'--export const TaxonomicFilterHeadless = {- Root: TaxonomicFilterRoot,- Input: TaxonomicFilterInput,- AutocompleteInput: TaxonomicFilterAutocompleteInput,- Autocomplete: TaxonomicAutocomplete,- Categories: TaxonomicFilterCategories,- Panel: TaxonomicFilterPanel,-}--export {- TaxonomicAutocomplete,- useTaxonomicAutocomplete,- useTaxonomicAutocompleteCategories,- useTaxonomicAutocompleteItemDetails,- useTaxonomicAutocompleteShortcutItems,-} from './AutocompleteInput'-export { TaxonomicFilterContext, useTaxonomicFilterContext } from './context'-export type { TaxonomicFilterRootProps } from './Root'-export type { TaxonomicFilterInputProps } from './Input'-export type {- TaxonomicAutocompleteCategory,- TaxonomicAutocompleteCategoryMode,- TaxonomicAutocompleteChipsProps,- TaxonomicAutocompleteConfigureState,- TaxonomicAutocompleteConfigureViewProps,- TaxonomicAutocompleteContentProps,- TaxonomicAutocompleteDetailsState,- TaxonomicAutocompleteDetailsViewProps,- TaxonomicAutocompleteEmptyProps,- TaxonomicAutocompleteEntry,- TaxonomicAutocompleteHeaderProps,- TaxonomicAutocompleteInputProps,- TaxonomicAutocompleteItemDetails,- TaxonomicAutocompleteItemsProps,- TaxonomicAutocompleteListProps,- TaxonomicAutocompleteMenuTriggerProps,- TaxonomicAutocompletePage,- TaxonomicAutocompletePageKind,- TaxonomicAutocompleteRootProps,- TaxonomicAutocompleteRootViewProps,- TaxonomicAutocompleteSeed,- TaxonomicAutocompleteSegmentedTriggerProps,- TaxonomicAutocompleteTriggerProps,- TaxonomicAutocompleteTriggerState,- TaxonomicFilterAutocompleteInputProps,-} from './AutocompleteInput'-export type { TaxonomicFilterCategoriesProps, TaxonomicFilterCategoryRenderProps } from './Categories'-export type { TaxonomicFilterPanelProps, TaxonomicFilterRowRenderProps } from './Panel'diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.test.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.test.tsdeleted file mode 100644index a7bac98eb522..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.test.ts+++ /dev/null@@ -1,56 +0,0 @@-import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'--import { fetchTaxonomicListPage } from './fetchTaxonomicListPage'--jest.mock('lib/api', () => ({- __esModule: true,- default: { get: jest.fn().mockResolvedValue({ results: [], count: 0 }) },-}))--const apiGet = jest.requireMock('lib/api').default.get as jest.Mock--function group(type: TaxonomicFilterGroupType): TaxonomicFilterGroup {- return { type, name: type, endpoint: `api/projects/1/${type}`, searchAlias: 'search' } as TaxonomicFilterGroup-}--describe('fetchTaxonomicListPage exclude_stale', () => {- beforeEach(() => apiGet.mockClear())-- const cases: [string, TaxonomicFilterGroupType, boolean, boolean][] = [- ['events + excludeStale', TaxonomicFilterGroupType.Events, true, true],- ['custom-events + excludeStale', TaxonomicFilterGroupType.CustomEvents, true, true],- ['events without excludeStale', TaxonomicFilterGroupType.Events, false, false],- ['non-event group + excludeStale', TaxonomicFilterGroupType.EventProperties, true, false],- ]- it.each(cases)('%s -> exclude_stale present=%s', async (_label, groupType, excludeStale, present) => {- await fetchTaxonomicListPage({- group: group(groupType),- searchQuery: 'foo',- offset: 0,- limit: 100,- isExpanded: false,- excludeStale,- })-- const url = apiGet.mock.calls[0][0] as string- expect(url.includes('exclude_stale=true')).toBe(present)- })- it.each([- ['sample', false],- ['sample@', true],- ])('fetches %s only when the group accepts the query', async (searchQuery, shouldFetch) => {- const searchGroup = {- ...group(TaxonomicFilterGroupType.EmailAddresses),- shouldSearch: (query: string): boolean => query.includes('@'),- }- const page = await fetchTaxonomicListPage({- group: searchGroup,- searchQuery,- offset: 0,- limit: 100,- isExpanded: false,- })- expect(apiGet).toHaveBeenCalledTimes(shouldFetch ? 1 : 0)- expect(page).toMatchObject({ searchQuery, results: [], count: 0 })- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.tsdeleted file mode 100644index 941bfd575cd5..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts+++ /dev/null@@ -1,93 +0,0 @@-/**- * Pure-ish data fetcher used by useGroupList. Translates a (group, page, query)- * tuple into a single API request and returns a normalised page result.- *- * Kept separate from the React hook so it can be tested in isolation and- * later swapped out for a TanStack Query queryFn.- */-import { combineUrl } from 'kea-router'--import api from 'lib/api'-import { ListStorage, TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'--export interface FetchTaxonomicPageParams {- group: TaxonomicFilterGroup- searchQuery: string- offset: number- limit: number- isExpanded: boolean- showNumericalPropsOnly?: boolean- hideBehavioralCohorts?: boolean- /** Exclude event definitions not ingested within the staleness window. Only- * applies to the event / custom-event endpoints (mirrors legacy `exclude_stale`). */- excludeStale?: boolean- signal?: AbortSignal-}--const EMPTY_LIST: ListStorage = { results: [], searchQuery: '', count: 0 }--export async function fetchTaxonomicListPage({- group,- searchQuery,- offset,- limit,- isExpanded,- showNumericalPropsOnly,- hideBehavioralCohorts,- excludeStale,- signal,-}: FetchTaxonomicPageParams): Promise<ListStorage> {- const remoteEndpoint = group.endpoint- if (!remoteEndpoint) {- return { ...EMPTY_LIST, searchQuery }- }-- const minSearchQueryLength = group.minSearchQueryLength ?? 0- if (- (minSearchQueryLength > 0 && searchQuery.length < minSearchQueryLength) ||- group.shouldSearch?.(searchQuery) === false- ) {- return { ...EMPTY_LIST, searchQuery }- }-- const searchAlias = group.searchAlias || 'search'- const excluded =- group.excludedProperties && group.excludedProperties.length > 0- ? JSON.stringify(group.excludedProperties)- : undefined- const properties = group.propertyAllowList ? group.propertyAllowList.join(',') : undefined-- const baseParams: Record<string, any> = {- [searchAlias]: searchQuery,- limit,- offset,- excluded_properties: excluded,- properties,- }- if (showNumericalPropsOnly) {- baseParams.is_numerical = 'true'- }- if (hideBehavioralCohorts) {- baseParams.hide_behavioral_cohorts = 'true'- }- const isEventGroup =- group.type === TaxonomicFilterGroupType.Events || group.type === TaxonomicFilterGroupType.CustomEvents- if (excludeStale && isEventGroup) {- baseParams.exclude_stale = 'true'- }-- const useScoped = group.scopedEndpoint && !isExpanded- const primaryUrl = useScoped ? group.scopedEndpoint! : remoteEndpoint-- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.- 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)-- return {- results,- searchQuery,- count,- }-}diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsxdeleted file mode 100644index 2e4a81e460d7..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx+++ /dev/null@@ -1,513 +0,0 @@-import { act, cleanup, renderHook, waitFor } from '@testing-library/react'--import api from 'lib/api'--import { PropertyOperator, PropertyFilterType } from '~/types'--import { QuickFilterItem, TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'-import { NO_ITEM_SELECTED, useGroupList } from './useGroupList'-import { __clearTaxonomicResourceCache } from './useTaxonomicResource'--jest.mock('lib/api', () => ({- __esModule: true,- default: { get: jest.fn() },-}))--const apiGet = api.get as jest.MockedFunction<typeof api.get>--function makeGroup(overrides: Partial<TaxonomicFilterGroup> = {}): TaxonomicFilterGroup {- return {- name: 'Events',- searchPlaceholder: 'events',- type: TaxonomicFilterGroupType.Events,- getName: (item: any) => item.name,- getValue: (item: any) => item.name,- getPopoverHeader: () => 'Event',- ...overrides,- } as TaxonomicFilterGroup-}--describe('useGroupList', () => {- beforeEach(() => {- __clearTaxonomicResourceCache()- apiGet.mockReset()- })-- afterEach(() => cleanup())-- describe('local-only group (no endpoint)', () => {- it('returns rawLocalItems when no search', () => {- const group = makeGroup({- type: TaxonomicFilterGroupType.Wildcards,- options: [{ name: 'foo' }, { name: 'bar' }] as any,- })- const { result } = renderHook(() => useGroupList({ group, searchQuery: '' }))- expect(result.current.items.map((i: any) => i.name)).toEqual(['foo', 'bar'])- expect(result.current.totalResultCount).toBe(2)- expect(result.current.hasRemoteDataSource).toBe(false)- expect(result.current.isLoading).toBe(false)- })-- it('Fuse-filters local items by search query', () => {- const group = makeGroup({- type: TaxonomicFilterGroupType.Wildcards,- options: [{ name: 'apple' }, { name: 'banana' }, { name: 'apricot' }] as any,- })- const { result } = renderHook(() => useGroupList({ group, searchQuery: 'app' }))- const names = result.current.items.map((i: any) => i.name)- expect(names).toContain('apple')- expect(names).not.toContain('banana')- })-- it('uses optionsFromProp when group has no options', () => {- const group = makeGroup({ type: TaxonomicFilterGroupType.Metadata })- const { result } = renderHook(() =>- useGroupList({- group,- searchQuery: '',- optionsFromProp: { [TaxonomicFilterGroupType.Metadata]: [{ name: 'm1' }, { name: 'm2' }] },- })- )- expect(result.current.items.map((i: any) => i.name)).toEqual(['m1', 'm2'])- })-- it('uses localOverride when provided (orchestrator path)', () => {- const group = makeGroup({ type: TaxonomicFilterGroupType.Actions })- const { result } = renderHook(() =>- useGroupList({- group,- searchQuery: '',- localOverride: [{ name: 'override-action' }] as any,- })- )- expect(result.current.items.map((i: any) => i.name)).toEqual(['override-action'])- })-- it('honours group.localItemsSearch override', () => {- const group = makeGroup({- type: TaxonomicFilterGroupType.Logs,- options: [{ name: 'msg-1' }, { name: 'msg-2' }] as any,- localItemsSearch: (items, q) => (q ? [{ name: 'custom: ' + q } as any, ...items] : items),- })- const { result } = renderHook(() => useGroupList({ group, searchQuery: 'hello' }))- expect((result.current.items[0] as any).name).toBe('custom: hello')- })- })-- describe('remote-only group', () => {- it('fetches via the endpoint and exposes results', async () => {- apiGet.mockResolvedValueOnce({ results: [{ name: 'remote-1' }, { name: 'remote-2' }], count: 2 })- const group = makeGroup({ endpoint: 'api/projects/1/event_definitions' })- const { result } = renderHook(() => useGroupList({ group, searchQuery: '' }))- expect(result.current.isLoading).toBe(true)- await waitFor(() => expect(result.current.totalResultCount).toBe(2))- expect(result.current.items.map((i: any) => i.name)).toEqual(['remote-1', 'remote-2'])- expect(result.current.isLoading).toBe(false)- })-- it.each([- {- name: 'different excludedProperties do not share a cache entry',- a: { excludedProperties: ['$mcp_tool_name'] },- b: { excludedProperties: [] },- expectedFetches: 2,- },- {- name: 'different propertyAllowList do not share a cache entry',- a: { propertyAllowList: ['$mcp_tool_name'] },- b: {},- expectedFetches: 2,- },- {- name: 'reordered content-equal excludedProperties share a cache entry',- a: { excludedProperties: ['$mcp_tool_name', '$mcp_is_error'] },- b: { excludedProperties: ['$mcp_is_error', '$mcp_tool_name'] },- expectedFetches: 1,- },- ])('$name', async ({ a, b, expectedFetches }) => {- // Exclusions/allowlists are fetch-time params: dropping them from the cache key- // would let one picker silently serve another's list for the whole staleTime- // window, while keying on order would double-fetch content-equal sets.- apiGet.mockResolvedValue({ results: [], count: 0 })- const base = {- type: TaxonomicFilterGroupType.EventProperties,- endpoint: 'api/projects/1/property_definitions',- }- renderHook(() => useGroupList({ group: makeGroup({ ...base, ...a }), searchQuery: '' }))- renderHook(() => useGroupList({ group: makeGroup({ ...base, ...b }), searchQuery: '' }))- // The exact count is deterministic: fetches fire synchronously from act-flushed- // effects, so both hooks' requests (or cache hits) precede waitFor's first poll.- await waitFor(() => expect(apiGet).toHaveBeenCalledTimes(expectedFetches))- // The differing params must actually reach the request, not just the cache key.- expect(new Set(apiGet.mock.calls.map(([url]) => url)).size).toBe(expectedFetches)- })-- it('respects minSearchQueryLength gating', () => {- const group = makeGroup({- endpoint: 'api/projects/1/whatever',- minSearchQueryLength: 3,- })- const { result } = renderHook(() => useGroupList({ group, searchQuery: 'ab' }))- expect(result.current.needsMoreSearchCharacters).toBe(true)- expect(result.current.isLoading).toBe(false)- expect(apiGet).not.toHaveBeenCalled()- })-- it('clears remote rows without fetching when the query no longer passes the group predicate', async () => {- apiGet.mockResolvedValue({ results: [{ name: '[email protected]' }], count: 1 })- const group = makeGroup({- type: TaxonomicFilterGroupType.EmailAddresses,- endpoint: 'api/projects/1/persons/values',- shouldSearch: (query: string): boolean => query.includes('@'),- })- const { result, rerender } = renderHook(({ q }: { q: string }) => useGroupList({ group, searchQuery: q }), {- initialProps: { q: 'sample@' },- })- await waitFor(() => expect(result.current.items).toEqual([{ name: '[email protected]' }]))- rerender({ q: 'sample' })- expect(result.current.items).toEqual([])- expect(result.current.isLoading).toBe(false)- expect(apiGet).toHaveBeenCalledTimes(1)- })-- 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 and surfaces an error 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)- // Surfaced so the UI can tell "failed" apart from "genuinely empty".- expect(result.current.error).toBeInstanceOf(Error)- expect(result.current.showErrorState).toBe(true)- expect(result.current.showEmptyState).toBe(false)-- apiGet.mockResolvedValueOnce({ results: [{ name: 'beta-result' }], count: 1 })- await act(async () => {- await result.current.refetch()- })- expect(result.current.items).toEqual([{ name: 'beta-result' }])- expect(result.current.showErrorState).toBe(false)- })-- it('refires when searchQuery changes', async () => {- apiGet- .mockResolvedValueOnce({ results: [{ name: 'a' }], count: 1 })- .mockResolvedValueOnce({ results: [{ name: 'b' }], count: 1 })- const group = makeGroup({ endpoint: 'api/projects/1/event_definitions' })- const { result, rerender } = renderHook(({ q }: { q: string }) => useGroupList({ group, searchQuery: q }), {- initialProps: { q: '' },- })- await waitFor(() => expect((result.current.items[0] as any).name).toBe('a'))- rerender({ q: 'x' })- await waitFor(() => expect((result.current.items[0] as any).name).toBe('b'))- expect(apiGet).toHaveBeenCalledTimes(2)- })-- 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- .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, 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 () => {- apiGet- // initial scoped: 1 result- .mockResolvedValueOnce({ results: [{ name: 's' }], count: 1 })- .mockResolvedValueOnce({ count: 9 })- // after expand: 9 results- .mockResolvedValueOnce({ results: Array.from({ length: 9 }, (_, i) => ({ name: `r${i}` })), count: 9 })- 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))- act(() => result.current.expand())- await waitFor(() => expect(result.current.totalResultCount).toBe(9))- })- })-- describe('clientFilterFirstPage', () => {- it('filters the cached first page locally without refetching when the whole list fits one page', async () => {- apiGet.mockResolvedValue({- results: [{ name: 'Internal team' }, { name: 'Power users' }, { name: 'Zzzbeta' }],- count: 3,- })- const group = makeGroup({- type: TaxonomicFilterGroupType.Cohorts,- endpoint: 'api/projects/1/cohorts/',- clientFilterFirstPage: true,- })- const { result, rerender } = renderHook(({ q }: { q: string }) => useGroupList({ group, searchQuery: q }), {- initialProps: { q: '' },- })- await waitFor(() => expect(result.current.totalResultCount).toBe(3))- rerender({ q: 'zzzbeta' })- await waitFor(() => expect(result.current.items.map((i: any) => i.name)).toEqual(['Zzzbeta']))- // First page covered the whole list — no extra request for the typed query.- expect(apiGet).toHaveBeenCalledTimes(1)- })-- it('falls back to a server search when the dataset is larger than the cached first page', async () => {- const firstPage = Array.from({ length: 100 }, (_, i) => ({ name: `Cohort ${i + 1}` }))- apiGet.mockImplementation((url: string) => {- if (url.includes('search=needle')) {- return Promise.resolve({ results: [{ name: 'Needle cohort' }], count: 1 })- }- // Empty-query first page: 100 of 150 total.- return Promise.resolve({ results: firstPage, count: 150 })- })- const group = makeGroup({- type: TaxonomicFilterGroupType.Cohorts,- endpoint: 'api/projects/1/cohorts/',- clientFilterFirstPage: true,- })- const { result, rerender } = renderHook(({ q }: { q: string }) => useGroupList({ group, searchQuery: q }), {- initialProps: { q: '' },- })- await waitFor(() => expect(result.current.totalResultCount).toBe(150))- // "Needle cohort" is not in the first page — only a server search finds it.- rerender({ q: 'needle' })- await waitFor(() => expect(result.current.items.map((i: any) => i.name)).toEqual(['Needle cohort']))- })-- it('surfaces an error (not an empty result) when the server search fails, and refetch retries only it', async () => {- const firstPage = Array.from({ length: 100 }, (_, i) => ({ name: `Cohort ${i + 1}` }))- apiGet.mockImplementation((url: string) => {- if (url.includes('search=needle')) {- return Promise.reject(new Error('search unavailable'))- }- // Empty-query first page: 100 of 150 total.- return Promise.resolve({ results: firstPage, count: 150 })- })- const group = makeGroup({- type: TaxonomicFilterGroupType.Cohorts,- endpoint: 'api/projects/1/cohorts/',- clientFilterFirstPage: true,- })- const { result, rerender } = renderHook(({ q }: { q: string }) => useGroupList({ group, searchQuery: q }), {- initialProps: { q: '' },- })- await waitFor(() => expect(result.current.totalResultCount).toBe(150))- // "needle" matches nothing in the cached first page, so only the (failing)- // server search could tell us whether it exists elsewhere in the other 50 rows.- rerender({ q: 'needle' })- await waitFor(() => expect(result.current.showErrorState).toBe(true))- expect(result.current.error).toBeInstanceOf(Error)- expect(result.current.showEmptyState).toBe(false)- expect(result.current.items).toEqual([])-- // The cached first page is healthy, so a retry must not re-request it: if that- // request failed, it would hide the recovered search behind a new error.- apiGet.mockImplementation((url: string) =>- url.includes('search=needle')- ? Promise.resolve({ results: [{ name: 'Needle cohort' }], count: 1 })- : Promise.reject(new Error('first page unavailable'))- )- await act(async () => {- await result.current.refetch()- })- expect(result.current.items.map((i: any) => i.name)).toEqual(['Needle cohort'])- expect(result.current.showErrorState).toBe(false)- })- })-- describe('keyword shortcuts', () => {- it('prepends QuickFilterItems when enabled and group provides shortcuts', () => {- const shortcut: QuickFilterItem = {- _type: 'quick_filter',- name: 'click (autocapture)',- filterValue: 'click',- operator: PropertyOperator.Exact,- propertyKey: '$event_type',- propertyFilterType: PropertyFilterType.Event,- }- const group = makeGroup({- type: TaxonomicFilterGroupType.Events,- options: [{ name: 'click_event' }] as any,- keywordShortcuts: () => [shortcut],- })- const { result } = renderHook(() =>- useGroupList({ group, searchQuery: 'click', enableKeywordShortcuts: true })- )- // Shortcut comes first, then the Fuse-matched local item.- expect(result.current.items[0]).toBe(shortcut)- expect((result.current.items[1] as any).name).toBe('click_event')- })-- it('skips shortcuts when enableKeywordShortcuts is false', () => {- const group = makeGroup({- type: TaxonomicFilterGroupType.Events,- options: [{ name: 'real' }] as any,- keywordShortcuts: () => [- {- _type: 'quick_filter',- name: 'k',- filterValue: 'k',- operator: PropertyOperator.Exact,- propertyKey: '$event_type',- propertyFilterType: PropertyFilterType.Event,- },- ],- })- // No search → no Fuse filtering, no shortcut prepend.- const { result } = renderHook(() => useGroupList({ group, searchQuery: '' }))- expect(result.current.items.map((i: any) => i.name)).toEqual(['real'])- })- })-- describe('keyboard navigation', () => {- it('moveDown wraps around', () => {- const group = makeGroup({- type: TaxonomicFilterGroupType.Wildcards,- options: [{ name: 'a' }, { name: 'b' }, { name: 'c' }] as any,- })- const { result } = renderHook(() => useGroupList({ group, searchQuery: '' }))- expect(result.current.index).toBe(0)- act(() => result.current.moveDown())- expect(result.current.index).toBe(1)- act(() => result.current.moveDown())- expect(result.current.index).toBe(2)- act(() => result.current.moveDown())- expect(result.current.index).toBe(0)- })-- it('moveUp wraps backwards', () => {- const group = makeGroup({- type: TaxonomicFilterGroupType.Wildcards,- options: [{ name: 'a' }, { name: 'b' }, { name: 'c' }] as any,- })- const { result } = renderHook(() => useGroupList({ group, searchQuery: '' }))- act(() => result.current.moveUp())- expect(result.current.index).toBe(2)- })-- it('selectFirstItem=false starts at NO_ITEM_SELECTED', () => {- const group = makeGroup({- type: TaxonomicFilterGroupType.Wildcards,- options: [{ name: 'a' }] as any,- })- const { result } = renderHook(() => useGroupList({ group, searchQuery: '', selectFirstItem: false }))- expect(result.current.index).toBe(NO_ITEM_SELECTED)- })- })-- describe('empty / loading states', () => {- it('local-only with no items + search shows empty state', () => {- const group = makeGroup({- type: TaxonomicFilterGroupType.Wildcards,- options: [{ name: 'apple' }] as any,- })- const { result } = renderHook(() => useGroupList({ group, searchQuery: 'zzz' }))- expect(result.current.totalResultCount).toBe(0)- expect(result.current.showEmptyState).toBe(true)- })-- it('remote group with no search and no remote data shows loading then settles', async () => {- apiGet.mockResolvedValueOnce({ results: [], count: 0 })- const group = makeGroup({ endpoint: 'api/projects/1/event_definitions' })- const { result } = renderHook(() => useGroupList({ group, searchQuery: '' }))- expect(result.current.showLoadingState).toBe(true)- await waitFor(() => expect(result.current.isLoading).toBe(false))- })-- // Transformation filters exclude `$exception` while allowing uncaptured events, so an excluded- // name must never be offered as "not seen yet".- it.each([- ['unseen', true],- ['$exception', false],- ])('allowNonCapturedEvents offers %p when nothing matches: %p', async (query, expected) => {- apiGet.mockResolvedValueOnce({ results: [], count: 0 })- const group = makeGroup({- type: TaxonomicFilterGroupType.Events,- endpoint: 'api/projects/1/event_definitions',- excludedProperties: ['$exception'],- })- const { result } = renderHook(() =>- useGroupList({ group, searchQuery: query, allowNonCapturedEvents: true })- )- await waitFor(() => expect(result.current.isLoading).toBe(false))- expect(result.current.showNonCapturedEventOption).toBe(expected)- // No rebuild renderer draws the offer row yet, so the empty state is what a person sees.- expect(result.current.showEmptyState).toBe(!expected)- })- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.tsdeleted file mode 100644index 8e3f92b26f63..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts+++ /dev/null@@ -1,569 +0,0 @@-/**- * Per-tab list state hook. Replaces `infiniteListLogic` for the new headless- * `useTaxonomicFilter`. One instance per active TaxonomicFilterGroup.- *- * Owns:- * - `index` (keyboard highlight)- * - `isExpanded` (scoped → full-results toggle)- * - the merged `items` list (local Fuse search OR remote `useTaxonomicResource`)- * - rowCount / loading / empty-state derivations- *- * Does NOT own (delegated to the orchestrator):- * - the search query (passed in)- * - top-match aggregation across groups- * - the recent / pinned prefix injection on SuggestedFilters- * - keyboard nav across tabs- *- * Open follow-ups (not implemented in v1):- * - DataWarehouse pinned-row detail-pane state- * - search-latency telemetry (legacy emits `taxonomic filter search latency`- * from the list-results handler; the rebuild emits its own menu events)- * - the GroupNamesPrefix clickhouse fast path (still goes through generic- * endpoint fetcher; behaviour identical, just slower for large groups)- */-import { useMemo, useState } from 'react'--import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'-import { hasRecentContext } from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'-import {- isQuickFilterItem,- ListStorage,- QuickFilterItem,- SimpleOption,- TaxonomicDefinitionTypes,- TaxonomicFilterGroup,- TaxonomicFilterGroupType,-} from 'lib/components/TaxonomicFilter/types'-import { floatRecentAndPinnedToTop, groupItemKey } from 'lib/components/TaxonomicFilter/utils/floatRecentPinned'-import { createFuse } from 'lib/utils/fuseSearch'--import { getCoreFilterDefinition } from '~/taxonomy/helpers'--import { fetchTaxonomicListPage } from './fetchTaxonomicListPage'-import {- TAXONOMIC_LIST_KEY_FAMILY,- TAXONOMIC_LIST_SEARCH_KEY_FAMILY,- useTaxonomicResource,-} from './useTaxonomicResource'--export const NO_ITEM_SELECTED = -1--const EMPTY_RESULTS: TaxonomicDefinitionTypes[] = []-const EMPTY_LIST_STORAGE: ListStorage = { results: EMPTY_RESULTS, searchQuery: '', count: 0 }--export interface UseGroupListInput {- group: TaxonomicFilterGroup- searchQuery: string- /** Overrides group.logic-based local items. Provide from the orchestrator- * for groups whose source data lives in another kea logic. */- localOverride?: TaxonomicDefinitionTypes[]- /** Static options keyed by group type (e.g. Metadata, Wildcards). */- optionsFromProp?: Partial<Record<TaxonomicFilterGroupType, SimpleOption[]>>- /** When true, emits `is_numerical=true` to remote endpoints and filters- * numeric-only items locally for DataWarehousePersonProperties. */- showNumericalPropsOnly?: boolean- hideBehavioralCohorts?: boolean- /** Exclude event definitions not seen within the staleness window (event /- * custom-event endpoints only). Mirrors legacy's default-on `exclude_stale`. */- excludeStale?: boolean- /** Override per-group minSearchQueryLength. */- minSearchQueryLength?: number- /** Pagination page size. */- limit?: number- /** Allow selecting events that haven't been captured yet. */- allowNonCapturedEvents?: boolean- /** Surface keyword shortcuts as QuickFilterItems alongside real results. */- enableKeywordShortcuts?: boolean- /** When true, disable the auto-select of first item on results refresh. */- autoSelectItem?: boolean- /** When true, the list initialises with index=0; otherwise index=NO_ITEM_SELECTED. */- selectFirstItem?: boolean- /** Set only when this is the filter's sole substantive group (no separate Recent/Pinned- * tabs lead the filter). Floats these recent (most-recent first) then pinned items to- * the top of the un-searched list. Mirrors legacy infiniteListLogic's `soleGroupHasGetValue`- * path. */- promoteRecentItemsToTop?: TaxonomicDefinitionTypes[]- promotePinnedItemsToTop?: TaxonomicDefinitionTypes[]-}--export interface UseGroupListResult {- /** Combined items (local + remote + keyword shortcuts), with QuickFilterItems first when enabled. */- items: TaxonomicDefinitionTypes[]- /** items.length plus synthetic rows like the expand button. */- rowCount: number- /** Number of "real" results (excluding synthetic rows). */- totalResultCount: number- /** Currently highlighted row. NO_ITEM_SELECTED (-1) if no selection. */- index: number- setIndex: (index: number) => void- moveUp: () => void- moveDown: () => void- /** Returns the item at a given index (or current index by default). */- itemAtIndex: (index?: number) => TaxonomicDefinitionTypes | undefined-- isLoading: boolean- isFetching: boolean- needsMoreSearchCharacters: boolean- hasRemoteDataSource: boolean- /** The last error from the active remote source for the current query. Can be truthy- * even when `items` is non-empty (a cached page still has rows while a later search- * fails), so use `showErrorState` when "nothing usable to fall back on" is what matters. */- error: unknown- showEmptyState: boolean- /** A fetch that failed for the current query. Kept separate from `showEmptyState` so a- * timeout or a 5xx doesn't read as "this project has no matching properties". */- showErrorState: boolean- showLoadingState: boolean- showNonCapturedEventOption: boolean-- isExpandable: boolean- isExpanded: boolean- expand: () => void-- /** Retries the failed fetch. Resolves once the retry settles, so a caller can- * disable its retry button for the duration. */- refetch: () => Promise<unknown>-}--const DEFAULT_LIMIT = 100--export function useGroupList(input: UseGroupListInput): UseGroupListResult {- const {- group,- searchQuery,- localOverride,- optionsFromProp,- showNumericalPropsOnly = false,- hideBehavioralCohorts = false,- excludeStale = false,- minSearchQueryLength: minSearchOverride,- limit = DEFAULT_LIMIT,- allowNonCapturedEvents = false,- enableKeywordShortcuts = false,- autoSelectItem = true,- selectFirstItem = true,- promoteRecentItemsToTop,- promotePinnedItemsToTop,- } = input-- const [isExpanded, setIsExpanded] = useState(false)- const [index, setIndex] = useState<number>(- selectFirstItem === false || autoSelectItem === false ? NO_ITEM_SELECTED : 0- )-- // ---- Local data source --------------------------------------------------- const rawLocalItems = useMemo<TaxonomicDefinitionTypes[] | null>(() => {- if (localOverride !== undefined) {- return localOverride- }- if (group.options) {- return group.options as TaxonomicDefinitionTypes[]- }- if (optionsFromProp && optionsFromProp[group.type]) {- return optionsFromProp[group.type] as TaxonomicDefinitionTypes[]- }- return null- }, [localOverride, group, optionsFromProp])-- const filteredLocalItems = useMemo<TaxonomicDefinitionTypes[] | null>(() => {- if (!rawLocalItems) {- return null- }- if (showNumericalPropsOnly && group.type === TaxonomicFilterGroupType.DataWarehousePersonProperties) {- return rawLocalItems.filter((item) => 'property_type' in item && (item as any).property_type === 'Numeric')- }- return rawLocalItems- }, [rawLocalItems, showNumericalPropsOnly, group.type])-- const fuse = useMemo(() => {- if (!filteredLocalItems) {- return null- }- const haystack = filteredLocalItems.map((item) => {- const name = group.getName?.(item) ?? ('name' in item ? (item as { name?: string }).name : '') ?? ''- const posthogName = getCoreFilterDefinition(name, group.type)?.label- const recentLabel =- hasRecentContext(item) && item._recentContext.propertyFilter- ? formatPropertyLabel(item._recentContext.propertyFilter, {})- : undefined- return { name, posthogName, recentLabel, item }- })- return createFuse(haystack, { keys: ['name', 'posthogName', 'recentLabel'], ignoreLocation: true })- }, [filteredLocalItems, group])-- const localItems = useMemo<ListStorage>(() => {- if (group.localItemsSearch) {- const filtered = group.localItemsSearch(filteredLocalItems ?? [], searchQuery)- return { results: filtered, count: filtered.length, searchQuery }- }- if (filteredLocalItems) {- const results =- searchQuery && fuse- ? fuse.search(searchQuery).map((r: any) => r.item.item as TaxonomicDefinitionTypes)- : filteredLocalItems- return { results, count: results.length, searchQuery }- }- return EMPTY_LIST_STORAGE- }, [group, filteredLocalItems, searchQuery, fuse])-- // ---- Remote data source -------------------------------------------------- const hasRemoteDataSource = !!group.endpoint- const minSearchQueryLength = minSearchOverride ?? group.minSearchQueryLength ?? 0- const trimmedSearch = searchQuery.trim()- const needsMoreSearchCharacters = minSearchQueryLength > 0 && trimmedSearch.length < minSearchQueryLength-- const remoteEnabled =- hasRemoteDataSource && !needsMoreSearchCharacters && group.shouldSearch?.(searchQuery) !== false-- // `clientFilterFirstPage` groups (e.g. Cohorts) pin the remote query to- // the empty-search first page and let local Fuse handle keystroke- // filtering — gives the same snappy feel as a local-only group while- // still picking up server-side hidden/excluded filtering. The cache- // key drops `searchQuery` so every keystroke hits the same entry.- const clientFilter = !!group.clientFilterFirstPage- const remoteSearchQuery = clientFilter ? '' : searchQuery-- // The cache is shared across pickers, and two pickers can build the same endpoint with- // different group-level exclusions/allowlists (e.g. the MCP tab excludes its schema from- // Event properties only when present) — those are fetch-time params, so key on them too.- // Sorted so content-equal sets in a different order share an entry: safe because the- // backend set-converts these params, so order never changes the response. (The allowlist- // also rides order-sensitively inside `group.endpoint`, so it doesn't get the collapse.)- const excludedPropertiesKey = JSON.stringify([...(group.excludedProperties ?? [])].sort())- const propertyAllowListKey = JSON.stringify([...(group.propertyAllowList ?? [])].sort())-- const remoteKey = useMemo(- () => [- TAXONOMIC_LIST_KEY_FAMILY,- group.type,- group.endpoint,- group.scopedEndpoint ?? null,- isExpanded,- remoteSearchQuery,- limit,- showNumericalPropsOnly,- hideBehavioralCohorts,- excludeStale,- excludedPropertiesKey,- propertyAllowListKey,- ],- [- group.type,- group.endpoint,- group.scopedEndpoint,- isExpanded,- remoteSearchQuery,- limit,- showNumericalPropsOnly,- hideBehavioralCohorts,- excludeStale,- excludedPropertiesKey,- propertyAllowListKey,- ]- )-- const remote = useTaxonomicResource<ListStorage>(- remoteKey,- ({ signal }) =>- fetchTaxonomicListPage({- group,- searchQuery: remoteSearchQuery,- offset: 0,- limit,- isExpanded,- showNumericalPropsOnly,- hideBehavioralCohorts,- excludeStale,- signal,- }),- // Long staleTime for client-filtered groups — the cached first page- // is the single source of truth for the whole typing session.- // Cohort mutations invalidate both key families via- // `invalidateTaxonomicResourcesWhere` in cohortsModel.- {- enabled: remoteEnabled,- staleTime: clientFilter ? 5 * 60_000 : 60_000,- keepPreviousData: true,- }- )-- // 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- // that page, local fuse silently misses every match outside it (e.g. a- // team with >100 cohorts can't find cohort #137 by name). Once we learn- // the dataset is bigger than one page, fall back to a real server search- // for typed queries; the snappy local path still serves the common case- // where the whole list fits in the first page.- const firstPageIncomplete = clientFilter && remoteItemsRaw.count > remoteItemsRaw.results.length- const serverSearchEnabled = firstPageIncomplete && !!trimmedSearch && !needsMoreSearchCharacters-- const serverSearchKey = useMemo(- () => [- TAXONOMIC_LIST_SEARCH_KEY_FAMILY,- group.type,- group.endpoint,- group.scopedEndpoint ?? null,- isExpanded,- trimmedSearch,- limit,- showNumericalPropsOnly,- hideBehavioralCohorts,- excludeStale,- excludedPropertiesKey,- propertyAllowListKey,- ],- [- group.type,- group.endpoint,- group.scopedEndpoint,- isExpanded,- trimmedSearch,- limit,- showNumericalPropsOnly,- hideBehavioralCohorts,- excludeStale,- excludedPropertiesKey,- propertyAllowListKey,- ]- )-- const serverSearch = useTaxonomicResource<ListStorage>(- serverSearchKey,- ({ signal }) =>- fetchTaxonomicListPage({- group,- searchQuery: trimmedSearch,- offset: 0,- limit,- isExpanded,- showNumericalPropsOnly,- hideBehavioralCohorts,- excludeStale,- signal,- }),- { 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).- const remoteFuse = useMemo(() => {- if (!clientFilter || remoteItemsRaw.results.length === 0) {- return null- }- const haystack = remoteItemsRaw.results.map((item) => {- const name = group.getName?.(item) ?? ('name' in item ? (item as { name?: string }).name : '') ?? ''- const posthogName = getCoreFilterDefinition(name, group.type)?.label- return { name, posthogName, item }- })- return createFuse(haystack, { keys: ['name', 'posthogName'], ignoreLocation: true })- }, [clientFilter, remoteItemsRaw, group])-- const remoteItems: ListStorage = useMemo(() => {- if (!clientFilter || !trimmedSearch) {- return remoteItemsRaw- }- // 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.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,- serverSearch.error,- ])-- // ---- Combined items + keyword shortcuts --------------------------------- const keywordShortcuts: QuickFilterItem[] = useMemo(() => {- if (!enableKeywordShortcuts || !group.keywordShortcuts || !trimmedSearch) {- return []- }- return group.keywordShortcuts(searchQuery)- }, [enableKeywordShortcuts, group, searchQuery, trimmedSearch])-- const items: TaxonomicDefinitionTypes[] = useMemo(() => {- const merged: TaxonomicDefinitionTypes[] = []- merged.push(...keywordShortcuts)- if (localItems.results.length > 0) {- merged.push(...localItems.results)- }- if (remoteItems.results.length > 0) {- merged.push(...remoteItems.results)- }- // Sole substantive group: float its own recent/pinned items to the top of the- // un-searched list (keyword shortcuts only appear while searching, so they're- // never displaced). Mirrors legacy infiniteListLogic's `soleGroupHasGetValue` path.- if (!trimmedSearch && (promoteRecentItemsToTop?.length || promotePinnedItemsToTop?.length)) {- const keyOf = (item: TaxonomicDefinitionTypes): string | null =>- groupItemKey(group.type, group.getValue?.(item) ?? null)- return floatRecentAndPinnedToTop(- merged,- keyOf,- promoteRecentItemsToTop || [],- promotePinnedItemsToTop || []- ) as TaxonomicDefinitionTypes[]- }- return merged- }, [- keywordShortcuts,- localItems,- remoteItems,- trimmedSearch,- promoteRecentItemsToTop,- promotePinnedItemsToTop,- group,- ])-- const isExpandable = !!(- group.endpoint &&- group.scopedEndpoint &&- !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,- // remote groups with paginated results under-report (e.g. Event properties- // shows 100 instead of 310). `rowCount` stays length-based since it drives- // virtualisation.- const totalResultCount = keywordShortcuts.length + localItems.count + (hasRemoteDataSource ? remoteItems.count : 0)- const rowCount = items.length + (isExpandable ? 1 : 0)-- // ---- Loading / empty state ---------------------------------------------- // Fold the server-search fallback into the busy flags so the skeleton- // (not "no results") shows while it's in flight on a >1-page dataset.- const isLoading = remote.isLoading || (serverSearchEnabled && serverSearch.isLoading)- const isFetching = remote.isFetching || (serverSearchEnabled && serverSearch.isFetching)-- const showNonCapturedEventOption = useMemo(() => {- if (!allowNonCapturedEvents) {- return false- }- if (group.type !== TaxonomicFilterGroupType.Events && group.type !== TaxonomicFilterGroupType.CustomEvents) {- return false- }- if (!trimmedSearch || isLoading) {- return false- }- // Offering an excluded name would let it be selected as a non-captured event, committing the- // value the exclusion forbids. Mirrors legacy infiniteListLogic's `showNonCapturedEventOption`.- if (group.excludedProperties?.includes(trimmedSearch)) {- return false- }- const realResults = items.filter((item) => !isQuickFilterItem(item))- return realResults.length === 0- }, [allowNonCapturedEvents, group.type, group.excludedProperties, trimmedSearch, isLoading, items])-- // A fetch that failed for the *current* query with nothing usable to fall back on.- // Mirrors legacy infiniteListLogic's `showErrorState`. When the server search is the- // active source (dataset bigger than one cached page), its failure is what must- // surface — the cached first page already succeeded, so `remote.error` stays unset- // and a failed search would otherwise read as "no results".- const error = serverSearchEnabled ? serverSearch.error : remote.error- const showErrorState = remoteEnabled && !!error && items.length === 0 && !isLoading-- // Empty / loading state checks read array length, not the API-reported- // total — a remote tab can have count > 0 while still loading its first- // page, and we don't want to flash an empty state during that window.- const showEmptyState =- !showErrorState &&- ((items.length === 0 && !isLoading && (!!searchQuery || !hasRemoteDataSource) && !showNonCapturedEventOption) ||- needsMoreSearchCharacters)-- const showLoadingState = isLoading && items.length === 0-- // ---- Index / keyboard nav ----------------------------------------------- const moveUp = (): void => {- if (rowCount === 0) {- return- }- setIndex((cur) => (cur - 1 + rowCount) % rowCount)- }-- const moveDown = (): void => {- if (rowCount === 0) {- return- }- setIndex((cur) => (cur + 1 + rowCount) % rowCount)- }-- const itemAtIndex = (i: number = index): TaxonomicDefinitionTypes | undefined => {- if (i < 0 || i >= items.length) {- return undefined- }- return items[i]- }-- const expand = (): void => {- setIsExpanded(true)- }-- return {- items,- rowCount,- totalResultCount,- index,- setIndex,- moveUp,- moveDown,- itemAtIndex,- isLoading,- isFetching,- needsMoreSearchCharacters,- hasRemoteDataSource,- error,- showEmptyState,- showErrorState,- showLoadingState,- showNonCapturedEventOption,- isExpandable,- isExpanded,- expand,- refetch: () => {- const pending = [serverSearchEnabled ? serverSearch.refetch() : remote.refetch()]- if (remoteEnabled && group.scopedEndpoint && !isExpanded) {- pending.push(expandedCount.refetch())- }- return Promise.all(pending)- },- }-}diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsxdeleted file mode 100644index 6769c23bbf40..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx+++ /dev/null@@ -1,565 +0,0 @@-import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'--import { act, cleanup, renderHook } from '@testing-library/react'-import { Provider } from 'kea'-import { ReactNode } from 'react'--import { teamLogic } from 'scenes/teamLogic'--import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'-import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { groupsModel } from '~/models/groupsModel'-import { performQuery } from '~/queries/query'-import { initKeaTests } from '~/test/init'--import { recentTaxonomicFiltersLogic } from '../recentTaxonomicFiltersLogic'-import { taxonomicFilterPinnedPropertiesLogic } from '../taxonomicFilterPinnedPropertiesLogic'-import { TaxonomicFilterGroupType } from '../types'-import { useTaxonomicFilter } from './useTaxonomicFilter'-import { __clearTaxonomicResourceCache } from './useTaxonomicResource'--jest.mock('~/queries/query', () => ({- performQuery: jest.fn(),-}))--jest.mock('lib/api', () =>- require('~/test/mocks/taxonomicFilterApiMock').buildTaxonomicFilterApiMock({- get: jest.fn().mockResolvedValue({ results: [], count: 0 }),- })-)--const wrapper = ({ children }: { children: ReactNode }): JSX.Element => <Provider>{children}</Provider>--describe('useTaxonomicFilter', () => {- beforeEach(() => {- __clearTaxonomicResourceCache()- // Recents persist to localStorage — clear so no test depends on what ran before it.- localStorage.clear()- ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })- useMocks({- get: { '/api/projects/:team/event_definitions': { results: [], count: 0 } },- post: { '/api/environments/:team/query': { results: [] } },- })- initKeaTests()- actionsModel.mount()- groupsModel.mount()- })-- afterEach(() => cleanup())-- // Nothing enforces parity between the legacy logic and this rebuild, so the same rule is asserted- // on both. The legacy half lives in taxonomicFilterLogic.test.ts.- describe('events whose data is moving out of the events table', () => {- const HIDDEN_EVENT = '$feature_flag_called'-- const renderFilter = (- input: Record<string, any> = {},- mode: FlagEvaluationsModeEnumApi = FlagEvaluationsModeEnumApi.Number1- ): ReturnType<typeof useTaxonomicFilter> => {- teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: mode })- const { result } = renderHook(- () => useTaxonomicFilter({ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events], ...input }),- { wrapper }- )- return result.current- }-- const eventsGroupExclusions = (- input: Record<string, any> = {},- mode?: FlagEvaluationsModeEnumApi- ): (string | null)[] =>- renderFilter(input, mode).groups.find((g) => g.type === TaxonomicFilterGroupType.Events)- ?.excludedProperties ?? []-- it('hides them by default', () => {- expect(eventsGroupExclusions()).toContain(HIDDEN_EVENT)- })-- it.each([- ['a team on the Events mode', {}, FlagEvaluationsModeEnumApi.Number0],- ['a picker that opts out', { includeHiddenEvents: true }, FlagEvaluationsModeEnumApi.Number1],- ])('offers them to %s', (_label, input, mode) => {- expect(eventsGroupExclusions(input, mode)).not.toContain(HIDDEN_EVENT)- })-- // The Recent and Pinned tabs and the menu shortcut rows filter against this record rather- // than the group's own list, so a pin saved before the event was hidden only drops if the- // names reach here too.- it('folds them into the record the Recent and Pinned surfaces read', () => {- expect(renderFilter().excludedProperties?.[TaxonomicFilterGroupType.Events]).toContain(HIDDEN_EVENT)- })- })-- it('exposes groups in the consumer-requested order, with Recent/Pinned auto-injected', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.PersonProperties,- ],- }),- { wrapper }- )- // SuggestedFilters leads (rebuilt menu always surfaces "All" for a multi-content- // picker), then Recent + Pinned auto-inject.- expect(result.current.groupTypes).toEqual([- TaxonomicFilterGroupType.SuggestedFilters,- TaxonomicFilterGroupType.RecentFilters,- TaxonomicFilterGroupType.PinnedFilters,- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.PersonProperties,- ])- expect(result.current.groups.map((g) => g.type)).toEqual(result.current.groupTypes)- })-- it.each([- {- name: 'does not auto-inject SuggestedFilters for a single content group',- requested: [TaxonomicFilterGroupType.Events],- },- {- name: 'does not auto-inject SuggestedFilters for a meta-only picker',- requested: [TaxonomicFilterGroupType.HogQLExpression],- },- {- name: 'does not auto-inject SuggestedFilters when a mutually-exclusive pair collapses',- requested: [TaxonomicFilterGroupType.PageviewUrls, TaxonomicFilterGroupType.PageviewEvents],- },- ])('$name', ({ requested }) => {- const { result } = renderHook(() => useTaxonomicFilter({ taxonomicGroupTypes: requested }), { wrapper })- expect(result.current.groupTypes).not.toContain(TaxonomicFilterGroupType.SuggestedFilters)- })-- // Mirrors the legacy `taxonomicGroupTypes` selector cases in taxonomicFilterLogic.test.ts —- // both surfaces must lead with the sole group, then Recent/Pinned, and drop any prepended All.- it.each([- {- name: 'single substantive group leads, Recent/Pinned follow (no All)',- requested: [TaxonomicFilterGroupType.Events],- },- {- name: 'single substantive group drops an explicitly-prepended All and still leads',- requested: [TaxonomicFilterGroupType.SuggestedFilters, TaxonomicFilterGroupType.Events],- },- ])('$name', ({ requested }) => {- const { result } = renderHook(() => useTaxonomicFilter({ taxonomicGroupTypes: requested }), { wrapper })- expect(result.current.groupTypes).toEqual([- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.RecentFilters,- TaxonomicFilterGroupType.PinnedFilters,- ])- })-- it('auto-injects SuggestedFilters as the default for a multi-content picker', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.PersonProperties],- }),- { wrapper }- )- expect(result.current.groupTypes).toContain(TaxonomicFilterGroupType.SuggestedFilters)- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.SuggestedFilters)- })-- it('SuggestedFilters injected by a late-growing group list becomes the default', () => {- const { result, rerender } = renderHook(- ({ types }: { types: TaxonomicFilterGroupType[] }) => useTaxonomicFilter({ taxonomicGroupTypes: types }),- { wrapper, initialProps: { types: [TaxonomicFilterGroupType.Events] } }- )- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Events)-- rerender({ types: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.PersonProperties] })-- expect(result.current.groupTypes).toContain(TaxonomicFilterGroupType.SuggestedFilters)- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.SuggestedFilters)- })-- it('an explicit choice survives the group list growing', () => {- const { result, rerender } = renderHook(- ({ types }: { types: TaxonomicFilterGroupType[] }) => useTaxonomicFilter({ taxonomicGroupTypes: types }),- { wrapper, initialProps: { types: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions] } }- )- act(() => result.current.setActiveGroupType(TaxonomicFilterGroupType.Actions))-- rerender({- types: [- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.PersonProperties,- ],- })-- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Actions)- })-- it('initial groupType prop is respected', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.PersonProperties],- groupType: TaxonomicFilterGroupType.Events,- }),- { wrapper }- )- // SuggestedFilters is auto-injected for the multi-content picker, but the explicit- // initial groupType still wins as the active tab.- expect(result.current.groupTypes).toContain(TaxonomicFilterGroupType.SuggestedFilters)- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Events)- })-- it('defaults to the first non-meta group when SuggestedFilters is not present', () => {- const { result } = renderHook(- () => useTaxonomicFilter({ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events] }),- { wrapper }- )- expect(result.current.groupTypes).not.toContain(TaxonomicFilterGroupType.SuggestedFilters)- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Events)- })-- it('defaults activeGroupType to props.groupType when valid', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions],- groupType: TaxonomicFilterGroupType.Actions,- }),- { wrapper }- )- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Actions)- })-- it('falls back to SuggestedFilters when present, otherwise first non-meta', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- // Two substantive groups so "All" is retained — a single substantive group drops it- taxonomicGroupTypes: [- TaxonomicFilterGroupType.SuggestedFilters,- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- ],- }),- { wrapper }- )- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.SuggestedFilters)- })-- it('updates active group via setActiveGroupType when included', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions],- }),- { wrapper }- )- act(() => result.current.setActiveGroupType(TaxonomicFilterGroupType.Actions))- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Actions)- })-- it('ignores setActiveGroupType requests for unavailable types', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],- }),- { wrapper }- )- act(() => result.current.setActiveGroupType(TaxonomicFilterGroupType.Cohorts))- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Events)- })-- it('tabLeft / tabRight cycle through visible groups', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.PersonProperties,- ],- groupType: TaxonomicFilterGroupType.Events,- }),- { wrapper }- )- act(() => result.current.tabRight())- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Actions)- act(() => result.current.tabRight())- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.PersonProperties)- act(() => result.current.tabRight()) // already at last; no-op- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.PersonProperties)- act(() => result.current.tabLeft())- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Actions)- })-- it('uncontrolled search query mutates via setSearchQuery', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],- }),- { wrapper }- )- expect(result.current.searchQuery).toBe('')- act(() => result.current.setSearchQuery('hello'))- expect(result.current.searchQuery).toBe('hello')- })-- it('controlled search query notifies via onSearchQueryChange and reflects prop', () => {- const onSearchQueryChange = jest.fn()- const { result, rerender } = renderHook(- ({ q }: { q: string }) =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],- searchQuery: q,- onSearchQueryChange,- }),- { wrapper, initialProps: { q: 'init' } }- )- expect(result.current.searchQuery).toBe('init')- act(() => result.current.setSearchQuery('typed'))- expect(onSearchQueryChange).toHaveBeenCalledWith('typed')- // controlled — internal state is not updated; consumer must re-render with new prop.- expect(result.current.searchQuery).toBe('init')- rerender({ q: 'typed' })- expect(result.current.searchQuery).toBe('typed')- })-- it('selectItem invokes onChange and clears the search query', () => {- const onChange = jest.fn()- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],- onChange,- initialSearchQuery: 'foo',- }),- { wrapper }- )- const eventsGroup = result.current.groups.find((g) => g.type === TaxonomicFilterGroupType.Events)!- act(() => result.current.selectItem(eventsGroup, 'evt', { name: 'evt' }))- expect(onChange).toHaveBeenCalledWith(eventsGroup, 'evt', { name: 'evt' })- expect(result.current.searchQuery).toBe('')- })-- it('selectItem records recents under an option-declared group, not the curated tab group', async () => {- // Mirrors legacy `getItemGroup` resolution: without the remap, an MCP-tab pick is- // recorded as `mcp_properties` while legacy records `event_properties`, and the- // shared recents storage grows near-duplicate rows across the two variants.- // Drain deferred recents writes scheduled by earlier tests first — they are- // skipped while the logic is unmounted, but would land once we mount it.- await act(async () => new Promise((resolve) => setTimeout(resolve, 0)))- recentTaxonomicFiltersLogic.mount()- try {- const { result } = renderHook(- () =>- useTaxonomicFilter({- // Only the curated tab — its canonical EventProperties group isn't a- // visible tab, so the remap must resolve against ALL group definitions.- taxonomicGroupTypes: [TaxonomicFilterGroupType.MCPProperties],- eventNames: ['$mcp_tool_call'],- }),- { wrapper }- )- const mcpGroup = result.current.groups.find((g) => g.type === TaxonomicFilterGroupType.MCPProperties)!- const option = {- name: '$mcp_tool_name',- value: '$mcp_tool_name',- group: TaxonomicFilterGroupType.EventProperties,- }- act(() => result.current.selectItem(mcpGroup, '$mcp_tool_name', option))- // The recents write is deferred one tick — flush the macrotask queue.- await act(async () => new Promise((resolve) => setTimeout(resolve, 0)))- expect(recentTaxonomicFiltersLogic.values.recentFilters).toContainEqual(- expect.objectContaining({- groupType: TaxonomicFilterGroupType.EventProperties,- value: '$mcp_tool_name',- })- )- expect(- recentTaxonomicFiltersLogic.values.recentFilters.map((f: { groupType: string }) => f.groupType)- ).not.toContain(TaxonomicFilterGroupType.MCPProperties)- } finally {- recentTaxonomicFiltersLogic.unmount()- }- })-- it('Escape key clears search', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],- initialSearchQuery: 'wat',- }),- { wrapper }- )- act(() =>- result.current.rootProps.onKeyDown({- key: 'Escape',- preventDefault: jest.fn(),- } as any)- )- expect(result.current.searchQuery).toBe('')- })-- it('Tab key advances active group; Shift+Tab moves back', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions],- groupType: TaxonomicFilterGroupType.Events,- }),- { wrapper }- )- act(() =>- result.current.rootProps.onKeyDown({- key: 'Tab',- shiftKey: false,- preventDefault: jest.fn(),- } as any)- )- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Actions)- act(() =>- result.current.rootProps.onKeyDown({- key: 'Tab',- shiftKey: true,- preventDefault: jest.fn(),- } as any)- )- expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Events)- })-- it('Enter forwards to onEnter when no list is registered', () => {- const onEnter = jest.fn()- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],- onEnter,- initialSearchQuery: 'q',- }),- { wrapper }- )- act(() =>- result.current.rootProps.onKeyDown({- key: 'Enter',- preventDefault: jest.fn(),- } as any)- )- expect(onEnter).toHaveBeenCalledWith('q')- })-- it('Enter selects via the registered active list when present', () => {- const onChange = jest.fn()- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],- onChange,- }),- { wrapper }- )- const eventsGroup = result.current.activeGroup!- const fakeItem = { id: 42, name: 'pageview' }- const fakeApi = {- items: [fakeItem] as any,- rowCount: 1,- totalResultCount: 1,- index: 0,- setIndex: jest.fn(),- moveUp: jest.fn(),- moveDown: jest.fn(),- itemAtIndex: () => fakeItem as any,- isLoading: false,- isFetching: false,- needsMoreSearchCharacters: false,- hasRemoteDataSource: false,- error: undefined,- showEmptyState: false,- showErrorState: false,- showLoadingState: false,- showNonCapturedEventOption: false,- isExpandable: false,- isExpanded: false,- expand: jest.fn(),- refetch: jest.fn(),- }- act(() => result.current.registerActiveList(() => fakeApi))- act(() =>- result.current.rootProps.onKeyDown({- key: 'Enter',- preventDefault: jest.fn(),- } as any)- )- // Events group.getValue returns .name for items with an `id`.- expect(onChange).toHaveBeenCalledWith(eventsGroup, 'pageview', fakeItem)- })-- it('searchPlaceholder composes label fragments from content groups only (Recent + Pinned excluded)', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions],- }),- { wrapper }- )- // Recent + Pinned auto-inject as META groups but are excluded from- // the placeholder — only content categories surface, joined into a- // simple "events, actions" label since there are only 2.- expect(result.current.searchPlaceholder).toBe('events, actions')- })-- it('getGroupListInput returns shape compatible with useGroupList', () => {- const { result } = renderHook(- () =>- useTaxonomicFilter({- taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],- showNumericalPropsOnly: true,- enableKeywordShortcuts: true,- }),- { wrapper }- )- const eventsGroup = result.current.groups.find((g) => g.type === TaxonomicFilterGroupType.Events)!- const input = result.current.getGroupListInput(eventsGroup)- expect(input.group).toBe(eventsGroup)- expect(input.searchQuery).toBe('')- expect(input.showNumericalPropsOnly).toBe(true)- expect(input.enableKeywordShortcuts).toBe(true)- })-- // Pins are stored globally, so this override can carry items from groups the picker does not- // offer. Anything that reads it needs a list the picker can represent.- it('filters the Pinned override to groups this picker offers', () => {- const pinnedLogic = taxonomicFilterPinnedPropertiesLogic.build()- pinnedLogic.mount()- pinnedLogic.actions.setPinnedFilters([- {- groupType: TaxonomicFilterGroupType.Events,- groupName: 'Events',- value: 'signed up',- item: { name: 'signed up' },- timestamp: 0,- },- {- groupType: TaxonomicFilterGroupType.Cohorts,- groupName: 'Cohorts',- value: 1,- item: { name: 'Power users' },- timestamp: 0,- },- ])-- const { result } = renderHook(- () => useTaxonomicFilter({ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events] }),- { wrapper }- )-- const pinnedGroup = result.current.groups.find((g) => g.type === TaxonomicFilterGroupType.PinnedFilters)!- const pinned = result.current.getGroupListInput(pinnedGroup).localOverride ?? []- expect(pinned.map((item: any) => item.name)).toEqual(['signed up'])- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.tsdeleted file mode 100644index 268ba6ab0d3c..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts+++ /dev/null@@ -1,645 +0,0 @@-/**- * Top-level orchestrator hook for the headless TaxonomicFilter.- *- * Owns:- * - search query (controlled or uncontrolled)- * - active group type (controlled or uncontrolled)- * - resolved + ordered taxonomicGroups[] (filtered against the consumer's- * `taxonomicGroupTypes` prop, with shortcut group promotion + meta tab- * auto-injection)- * - active-list registration for keyboard nav (each tab list component- * registers its useGroupList api; the orchestrator forwards key events- * to the currently active one)- * - selectItem callback fan-out (dispatches to props.onChange)- *- * Does NOT own:- * - per-tab list state (that's `useGroupList`, called inside each tab- * component)- * - top-match aggregation across groups (deferred to a follow-up; today's- * kea `appendTopMatches` reducer can stay until each tab has migrated)- * - recents / pinned localStorage logic (still in `recentTaxonomicFiltersLogic`- * and `taxonomicFilterPinnedPropertiesLogic`; the orchestrator only reads- * them via the bridge, doesn't write)- */-import { useValues } from 'kea'-import { useCallback, useMemo, useRef, useState } from 'react'--import {- hasRecentContext,- recentTaxonomicFiltersLogic,- stripRecentContext,-} from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'-import {- AllowedProperties,- ExcludedOperators,- ExcludedProperties,- SelectedProperties,- SelectingKeyOnly,- SimpleOption,- TaxonomicDefinitionTypes,- TaxonomicFilterGroup,- TaxonomicFilterGroupType,- TaxonomicFilterValue,- META_GROUP_TYPES,-} from 'lib/components/TaxonomicFilter/types'-import { isQuickFilterItem } from 'lib/components/TaxonomicFilter/types'-import { buildTaxonomicGroups } from 'lib/components/TaxonomicFilter/utils/buildTaxonomicGroups'-import { isContainsShortcutItem } from 'lib/components/TaxonomicFilter/utils/collapsedContainsRow'-import { withHiddenEventsExcluded } from 'lib/components/TaxonomicFilter/utils/hiddenEvents'-import { MaxContextTaxonomicFilterOption } from 'scenes/max/maxTypes'-import { teamLogic } from 'scenes/teamLogic'--import { AnyDataNode } from '~/queries/schema/schema-general'--import { UseGroupListInput, UseGroupListResult } from './useGroupList'-import { useTaxonomicGroupsContext } from './useTaxonomicGroupsContext'-import { useTaxonomicLocalOverrides } from './useTaxonomicLocalOverrides'--export interface UseTaxonomicFilterOptions {- taxonomicGroupTypes: TaxonomicFilterGroupType[]-- // controlled value- value?: TaxonomicFilterValue- onChange?: (group: TaxonomicFilterGroup, value: TaxonomicFilterValue, item: any) => void- onEnter?: (query: string) => void-- // initial / controlled tab- groupType?: TaxonomicFilterGroupType-- // search input- searchQuery?: string- initialSearchQuery?: string- onSearchQueryChange?: (q: string) => void-- // forwarded into useTaxonomicGroupsContext (only fields that affect group config)- eventNames?: string[]- schemaColumns?: import('~/queries/schema/schema-general').DatabaseSchemaField[]- schemaColumnsLoading?: boolean- metadataSource?: AnyDataNode- suggestedFiltersLabel?: string- excludedProperties?: ExcludedProperties- /** Keep offering events whose data is moving out of the `events` table. See `TaxonomicFilterProps`. */- includeHiddenEvents?: boolean- selectedProperties?: SelectedProperties- propertyAllowList?: AllowedProperties- maxContextOptions?: MaxContextTaxonomicFilterOption[]- hideBehavioralCohorts?: boolean- /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */- showCohortFlagTargeting?: boolean- endpointFilters?: Record<string, any>- hogQLGlobals?: Record<string, any>- hogQLExpressionShowBreakdownLabelHint?: boolean-- // forwarded into per-tab useGroupList- optionsFromProp?: Partial<Record<TaxonomicFilterGroupType, SimpleOption[]>>- showNumericalPropsOnly?: boolean- minSearchQueryLength?: number- allowNonCapturedEvents?: boolean- enableKeywordShortcuts?: boolean- selectFirstItem?: boolean- autoSelectItem?: boolean- selectingKeyOnly?: SelectingKeyOnly- excludedOperators?: ExcludedOperators-}--export interface TaxonomicFilterApi {- // group resolution- /** Ordered list of group configs that should appear as tabs. */- groups: TaxonomicFilterGroup[]- /** Just the group types from `groups`, in display order. */- groupTypes: TaxonomicFilterGroupType[]- /** Identity of the meta groups in `groups` (read by per-tab UIs to suppress loaders, top matches etc.). */- metaGroupTypes: Set<TaxonomicFilterGroupType>- activeGroup: TaxonomicFilterGroup | undefined- activeGroupType: TaxonomicFilterGroupType- setActiveGroupType: (groupType: TaxonomicFilterGroupType) => void- tabLeft: () => void- tabRight: () => void-- // search- searchQuery: string- setSearchQuery: (q: string) => void- /** Composite placeholder string (e.g. "events, properties or other..."). */- searchPlaceholder: string-- // selection- selectItem: (group: TaxonomicFilterGroup, value: TaxonomicFilterValue | null, item: any) => void- /** Forwards Enter to the registered active list, falling back to onEnter(query). */- selectSelected: () => void-- // active-list registration (called by the per-tab list component).- // Pass a getter that returns the current `useGroupList` snapshot, or- // `null` to deregister. The orchestrator invokes the getter at the- // moment it needs to read the list (Enter / arrow keys), so the- // returned snapshot is always fresh — even though `useGroupList`- // returns a new object reference on every render of the consumer.- registerActiveList: (getter: (() => UseGroupListResult | null) | null) => void-- // factory for per-tab consumers- /** Build the input object for `useGroupList`, for a given group. */- getGroupListInput: (group: TaxonomicFilterGroup) => UseGroupListInput-- // value passthroughs- value?: TaxonomicFilterValue- selectingKeyOnly?: SelectingKeyOnly- excludedOperators?: ExcludedOperators- excludedProperties?: ExcludedProperties-- // headless-component prop bags- rootProps: { onKeyDown: (e: React.KeyboardEvent<any>) => void }- inputProps: {- value: string- onChange: (e: React.ChangeEvent<HTMLInputElement>) => void- onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void- placeholder: string- }-}--const PRE_INJECTED_META_TAB_ORDER: TaxonomicFilterGroupType[] = [- TaxonomicFilterGroupType.SuggestedFilters,- TaxonomicFilterGroupType.RecentFilters,- TaxonomicFilterGroupType.PinnedFilters,-]--function indexAfterLastMetaGroup(filtered: TaxonomicFilterGroupType[]): number {- for (let i = PRE_INJECTED_META_TAB_ORDER.length - 1; i >= 0; i--) {- const idx = filtered.indexOf(PRE_INJECTED_META_TAB_ORDER[i])- if (idx !== -1) {- return idx + 1- }- }- return 0-}--/** Mirrors the legacy `taxonomicGroupTypes` selector. Resolves the consumer's- * request into a final ordered list of visible tabs by:- * 1. Dropping types that aren't available in the current `groups`- * 2. Resolving mutually-exclusive shortcut pairs (e.g. PageviewUrls vs- * PageviewEvents — keep the first, drop the second)- * 3. Auto-injecting the SuggestedFilters ("All") tab when there's more than- * one substantive group — the rebuilt menu always leads with it (unlike- * the legacy selector, this is unconditional: the rebuild has no- * per-variant arm to protect; see the pill-gated block in- * taxonomicFilterLogic.tsx for the legacy counterpart).- * 4. Auto-injecting Recent/Pinned meta tabs when available.- * 5. Promoting shortcut groups (PageviewUrls / Screens / EmailAddresses- * / Elements when `$autocapture` is in `eventNames`) to right after- * the meta block.- */-const MUTUALLY_EXCLUSIVE_PAIRS: [TaxonomicFilterGroupType, TaxonomicFilterGroupType][] = [- [TaxonomicFilterGroupType.PageviewUrls, TaxonomicFilterGroupType.PageviewEvents],- [TaxonomicFilterGroupType.Screens, TaxonomicFilterGroupType.ScreenEvents],-]--const AUTO_INJECT_META_GROUPS: TaxonomicFilterGroupType[] = [- TaxonomicFilterGroupType.RecentFilters,- TaxonomicFilterGroupType.PinnedFilters,-]--const SHORTCUT_GROUPS_BASE: TaxonomicFilterGroupType[] = [- TaxonomicFilterGroupType.PageviewUrls,- TaxonomicFilterGroupType.Screens,- TaxonomicFilterGroupType.EmailAddresses,-]--function resolveTaxonomicGroupTypes(- requested: TaxonomicFilterGroupType[],- available: Set<TaxonomicFilterGroupType>,- eventNames: string[]-): TaxonomicFilterGroupType[] {- // 1. Mutual exclusion + availability filter- const excluded = new Set<TaxonomicFilterGroupType>()- for (const [a, b] of MUTUALLY_EXCLUSIVE_PAIRS) {- if (requested.includes(a) && requested.includes(b)) {- excluded.add(b)- }- }- const filtered = requested.filter((t) => !excluded.has(t) && available.has(t))-- // 2a. The rebuilt menu always surfaces the SuggestedFilters ("All") tab as the- // default cross-group landing spot when there's more than one substantive group- // to aggregate. With a single substantive group there's nothing for "All" to- // aggregate, so drop it (a call site may have prepended SuggestedFilters); Recent/Pinned- // then follow the group instead of leading, and the group's own list floats recent/pinned- // items to the top.- const substantiveGroupCount = filtered.filter((t) => !META_GROUP_TYPES.has(t)).length- const singleSubstantiveGroup = substantiveGroupCount === 1- if (singleSubstantiveGroup) {- const suggestedIdx = filtered.indexOf(TaxonomicFilterGroupType.SuggestedFilters)- if (suggestedIdx !== -1) {- filtered.splice(suggestedIdx, 1)- }- } else if (- available.has(TaxonomicFilterGroupType.SuggestedFilters) &&- !filtered.includes(TaxonomicFilterGroupType.SuggestedFilters) &&- substantiveGroupCount >= 2- ) {- filtered.unshift(TaxonomicFilterGroupType.SuggestedFilters)- }-- // 2b. Auto-inject Recent/Pinned meta tabs when available and not already present. For a- // single substantive group they follow the group; otherwise they lead, after the meta block.- for (const metaType of AUTO_INJECT_META_GROUPS) {- if (available.has(metaType) && !filtered.includes(metaType)) {- const insertAt = singleSubstantiveGroup ? filtered.length : indexAfterLastMetaGroup(filtered)- filtered.splice(insertAt, 0, metaType)- }- }-- // 3. Promote shortcut groups to right after the meta block. Skipped for a single group,- // where there's nothing to reorder above and it would push the group below its meta tabs.- if (!singleSubstantiveGroup) {- const shortcutGroups: TaxonomicFilterGroupType[] = [- ...SHORTCUT_GROUPS_BASE,- ...(eventNames.includes('$autocapture') ? [TaxonomicFilterGroupType.Elements] : []),- ]- const toInsert: TaxonomicFilterGroupType[] = []- for (const groupType of shortcutGroups) {- const idx = filtered.indexOf(groupType)- if (idx !== -1) {- filtered.splice(idx, 1)- toInsert.push(groupType)- }- }- if (toInsert.length > 0) {- filtered.splice(indexAfterLastMetaGroup(filtered), 0, ...toInsert)- }- }-- return filtered-}--export function useTaxonomicFilter(opts: UseTaxonomicFilterOptions): TaxonomicFilterApi {- const {- taxonomicGroupTypes,- value,- onChange,- onEnter,- groupType: initialGroupType,- searchQuery: controlledSearchQuery,- initialSearchQuery,- onSearchQueryChange,- eventNames,- schemaColumns,- schemaColumnsLoading,- metadataSource,- suggestedFiltersLabel,- excludedProperties: callerExcludedProperties,- includeHiddenEvents,- selectedProperties,- propertyAllowList,- maxContextOptions,- hideBehavioralCohorts,- showCohortFlagTargeting,- endpointFilters,- hogQLGlobals,- hogQLExpressionShowBreakdownLabelHint,- optionsFromProp,- showNumericalPropsOnly,- minSearchQueryLength,- allowNonCapturedEvents,- enableKeywordShortcuts,- selectFirstItem,- autoSelectItem,- selectingKeyOnly,- excludedOperators,- } = opts-- const { currentTeam } = useValues(teamLogic)- const flagEvaluationsMode = currentTeam?.flag_evaluations_mode- // Every surface below reads exclusions from this one record: the group builder, the Recent and- // Pinned tabs, and the menu's shortcut rows. Folding the hidden names in here reaches all of them.- const excludedProperties = useMemo(- () => withHiddenEventsExcluded(callerExcludedProperties, flagEvaluationsMode, includeHiddenEvents),- [callerExcludedProperties, flagEvaluationsMode, includeHiddenEvents]- )-- const ctx = useTaxonomicGroupsContext({- eventNames,- taxonomicGroupTypes,- schemaColumns,- schemaColumnsLoading,- metadataSource,- suggestedFiltersLabel,- excludedProperties,- includeHiddenEvents,- allowNonCapturedEvents,- propertyAllowList,- showNumericalPropsOnly,- selectedProperties,- maxContextOptions,- hideBehavioralCohorts,- showCohortFlagTargeting,- endpointFilters,- hogQLGlobals,- hogQLExpressionShowBreakdownLabelHint,- })-- const allGroups = useMemo(() => buildTaxonomicGroups(ctx), [ctx])- const allGroupTypes = useMemo(() => new Set(allGroups.map((g) => g.type)), [allGroups])-- const groupTypes = useMemo(- () => resolveTaxonomicGroupTypes(taxonomicGroupTypes, allGroupTypes, eventNames ?? []),- [taxonomicGroupTypes, allGroupTypes, eventNames]- )-- const getLocalOverride = useTaxonomicLocalOverrides({- taxonomicGroupTypes: groupTypes,- excludedOperators,- selectingKeyOnly,- excludedProperties,- })-- const groups = useMemo(() => {- const byType = new Map(allGroups.map((g) => [g.type, g]))- return groupTypes.map((t) => byType.get(t)!).filter(Boolean)- }, [allGroups, groupTypes])-- const metaGroupTypes = useMemo(- () => new Set(groups.filter((g) => g.isMetaGroup || META_GROUP_TYPES.has(g.type)).map((g) => g.type)),- [groups]- )-- // The filter's only substantive (non-meta) group, if there is exactly one. That group's- // list floats its own recent/pinned items to the top, since there are no leading- // Recent/Pinned tabs (see resolveTaxonomicGroupTypes and useGroupList).- const soleSubstantiveGroupType = useMemo<TaxonomicFilterGroupType | null>(() => {- const substantive = groupTypes.filter((t) => !META_GROUP_TYPES.has(t))- return substantive.length === 1 ? substantive[0] : null- }, [groupTypes])-- // Recent/pinned items the sole substantive group floats to the top of its own list.- // Memoised so getGroupListInput hands useGroupList a stable array reference: getLocalOverride- // builds a fresh array on every call (filterRecentsForContext maps/filters), which would- // otherwise churn useGroupList's `items` memo every render and drive Combobox's Fetcher- // items effect into a setState loop (Maximum update depth exceeded).- const soleGroupPromoteRecent = useMemo<TaxonomicDefinitionTypes[] | undefined>(- () => (soleSubstantiveGroupType ? getLocalOverride(TaxonomicFilterGroupType.RecentFilters) : undefined),- [soleSubstantiveGroupType, getLocalOverride]- )- const soleGroupPromotePinned = useMemo<TaxonomicDefinitionTypes[] | undefined>(- () => (soleSubstantiveGroupType ? getLocalOverride(TaxonomicFilterGroupType.PinnedFilters) : undefined),- [soleSubstantiveGroupType, getLocalOverride]- )-- // ---- search query (controlled / uncontrolled) ---------------------------- const [internalSearchQuery, setInternalSearchQuery] = useState(initialSearchQuery ?? '')- const isSearchControlled = controlledSearchQuery !== undefined- const searchQuery = isSearchControlled ? controlledSearchQuery : internalSearchQuery-- const setSearchQuery = useCallback(- (q: string) => {- if (!isSearchControlled) {- setInternalSearchQuery(q)- }- onSearchQueryChange?.(q)- },- [isSearchControlled, onSearchQueryChange]- )-- // ---- active group (controlled by initial prop, then internal) ------------ const defaultActiveGroup = useMemo<TaxonomicFilterGroupType>(() => {- if (initialGroupType && groupTypes.includes(initialGroupType)) {- return initialGroupType- }- if (groupTypes.includes(TaxonomicFilterGroupType.SuggestedFilters)) {- return TaxonomicFilterGroupType.SuggestedFilters- }- const firstNonMeta = groupTypes.find((t) => !metaGroupTypes.has(t))- return firstNonMeta ?? groupTypes[0] ?? TaxonomicFilterGroupType.Empty- }, [initialGroupType, groupTypes, metaGroupTypes])-- // Only an explicit choice is stored; the active group derives from it so the- // default keeps tracking groups that arrive after mount (late feature flags,- // async group sources) instead of freezing the first render's answer. An- // explicit choice that's no longer in the tab list falls back to the default.- const [explicitActiveGroup, setExplicitActiveGroup] = useState<TaxonomicFilterGroupType | null>(null)- const activeGroupType =- explicitActiveGroup && groupTypes.includes(explicitActiveGroup) ? explicitActiveGroup : defaultActiveGroup-- const setActiveGroupType = useCallback(- (t: TaxonomicFilterGroupType) => {- if (groupTypes.includes(t)) {- setExplicitActiveGroup(t)- }- },- [groupTypes]- )-- const tabLeft = useCallback(() => {- const idx = groupTypes.indexOf(activeGroupType)- if (idx <= 0) {- return- }- setExplicitActiveGroup(groupTypes[idx - 1])- }, [groupTypes, activeGroupType])-- const tabRight = useCallback(() => {- const idx = groupTypes.indexOf(activeGroupType)- if (idx === -1 || idx >= groupTypes.length - 1) {- return- }- setExplicitActiveGroup(groupTypes[idx + 1])- }, [groupTypes, activeGroupType])-- const activeGroup = useMemo(() => groups.find((g) => g.type === activeGroupType), [groups, activeGroupType])-- // ---- search placeholder -------------------------------------------------- // Skip META groups (Recent/Pinned/Suggested/HogQL/etc.) — they exist- // as shortcut surfaces, not as searchable content categories, and the- // dropdown-menu rebuild now exposes Recent/Pinned as their own entries.- // Listing them here just crowded the placeholder ("Search recent,- // pinned, events…") and pushed real content labels out of the slice.- const searchPlaceholder = useMemo(() => {- const contentGroups = groups.filter((g) => !META_GROUP_TYPES.has(g.type))- const labels = contentGroups- .filter((g) => g.searchPlaceholder)- .map((g) => g.searchPlaceholder as string)- .slice(0, 3)- return labels.length === 0 ? '' : labels.join(', ') + (contentGroups.length > 3 ? ' or other...' : '')- }, [groups])-- // ---- active-list registration for keyboard nav --------------------------- // Consumers register a *getter* (or `null` to deregister) so the- // orchestrator always reads the freshest list snapshot at call time.- // Snapshotting the API directly turned out to be racy: `useGroupList`- // returns a fresh object reference on every render, which made the- // `useEffect([list])` in `Panel.tsx` fire its cleanup + re-register- // continuously and opened a brief null window between the two —- // enough to make `selectSelected()` fall through to `onEnter(query)`- // mid-commit under concurrent rendering. With a getter, the consumer- // can register once on mount and always serve the current value.- const activeListGetterRef = useRef<(() => UseGroupListResult | null) | null>(null)- const registerActiveList = useCallback((getter: (() => UseGroupListResult | null) | null) => {- activeListGetterRef.current = getter- }, [])- const readActiveList = useCallback((): UseGroupListResult | null => {- return activeListGetterRef.current?.() ?? null- }, [])-- const selectItem = useCallback(- (group: TaxonomicFilterGroup, valueIn: TaxonomicFilterValue | null, item: any) => {- // Mirror the legacy `taxonomicFilterLogic.selectItem` recent- // recording so menu commits show up in the dropdown's- // "Recent" entry. Quick-filter items and the synthetic- // "URL contains <query>" shortcut are skipped (they're- // shortcuts, not filterable definitions — and recording the- // shortcut would shadow it on the next search, since the recent- // shares its entryKey but lacks the contains label/telemetry);- // pinned/recent context wrappers get stripped before persisting.- if (valueIn != null && item && !isQuickFilterItem(item) && !isContainsShortcutItem(item)) {- const recentContext = hasRecentContext(item) ? item._recentContext : undefined- const stripped = recentContext ? stripRecentContext(item) : item- // Options in curated tabs (MCP properties, internal event properties) declare- // the canonical group they commit as. Legacy resolves it via `getItemGroup`- // before dispatching, so recents must be recorded under the declared group- // here too — otherwise the same property gets near-duplicate Recent rows- // across variants (recents dedupe on groupType + value and share storage).- const declaredGroup =- !recentContext && stripped && typeof stripped === 'object' && 'group' in stripped- ? // Resolve against every group definition (like legacy `getItemGroup`), not just- // the visible tabs — a curated tab can be requested without its canonical group.- allGroups.find((g) => g.type === stripped.group)- : undefined- const sourceGroupType = recentContext?.sourceGroupType ?? declaredGroup?.type ?? group.type- const cleanItem = {- name: stripped.name,- ...(stripped.id ? { id: stripped.id } : {}),- }- const sourceGroupName = recentContext?.sourceGroupName ?? declaredGroup?.name ?? group.name- const propertyFilterFromRecent = recentContext?.propertyFilter- // Defer one tick — keeps the recents write off the- // commit's render cycle so React doesn't re-render the- // closing popover with a stale list.- setTimeout(() => {- if (recentTaxonomicFiltersLogic.isMounted()) {- recentTaxonomicFiltersLogic.actions.recordRecentFilter({- groupType: sourceGroupType,- groupName: sourceGroupName,- value: valueIn,- item: cleanItem,- teamId: teamLogic.values.currentTeamId ?? undefined,- propertyFilter: propertyFilterFromRecent,- })- }- }, 0)- }- onChange?.(group, valueIn, item)- setSearchQuery('')- },- [allGroups, onChange, setSearchQuery]- )-- const selectSelected = useCallback(() => {- const list = readActiveList()- const selected = list?.itemAtIndex()- if (selected && activeGroup) {- const itemValue = activeGroup.getValue?.(selected) ?? null- selectItem(activeGroup, itemValue, selected)- } else {- onEnter?.(searchQuery)- }- }, [activeGroup, selectItem, onEnter, searchQuery, readActiveList])-- // ---- per-tab input factory ---------------------------------------------- const getGroupListInput = useCallback(- (group: TaxonomicFilterGroup): UseGroupListInput => ({- group,- searchQuery,- optionsFromProp,- showNumericalPropsOnly,- hideBehavioralCohorts,- minSearchQueryLength,- allowNonCapturedEvents,- enableKeywordShortcuts,- selectFirstItem,- autoSelectItem,- // Logic-backed groups (Actions / Cohorts / Experiments / Dashboards- // / Recent / Pinned) get their data via this bridge. Returns- // undefined for groups whose data is `group.options` / endpoint /- // optionsFromProp — useGroupList handles those internally.- localOverride: getLocalOverride(group.type),- // The sole substantive group carries recents/pinned inline (no leading tabs).- ...(group.type === soleSubstantiveGroupType- ? {- promoteRecentItemsToTop: soleGroupPromoteRecent,- promotePinnedItemsToTop: soleGroupPromotePinned,- }- : {}),- }),- [- searchQuery,- optionsFromProp,- showNumericalPropsOnly,- hideBehavioralCohorts,- minSearchQueryLength,- allowNonCapturedEvents,- enableKeywordShortcuts,- selectFirstItem,- autoSelectItem,- getLocalOverride,- soleSubstantiveGroupType,- soleGroupPromoteRecent,- soleGroupPromotePinned,- ]- )-- // ---- keyboard handler --------------------------------------------------- const onKeyDown = useCallback(- (e: React.KeyboardEvent<any>) => {- const list = readActiveList()- switch (e.key) {- case 'ArrowUp':- list?.moveUp()- e.preventDefault()- break- case 'ArrowDown':- list?.moveDown()- e.preventDefault()- break- case 'Tab':- e.shiftKey ? tabLeft() : tabRight()- e.preventDefault()- break- case 'Enter':- selectSelected()- e.preventDefault()- break- case 'Escape':- setSearchQuery('')- e.preventDefault()- break- }- },- [selectSelected, setSearchQuery, tabLeft, tabRight, readActiveList]- )-- return {- groups,- groupTypes,- metaGroupTypes,- activeGroup,- activeGroupType,- setActiveGroupType,- tabLeft,- tabRight,- searchQuery,- setSearchQuery,- searchPlaceholder,- selectItem,- selectSelected,- registerActiveList,- getGroupListInput,- value,- selectingKeyOnly,- excludedOperators,- excludedProperties,- rootProps: { onKeyDown },- inputProps: {- value: searchQuery,- onChange: (e) => setSearchQuery(e.target.value),- onKeyDown,- placeholder: searchPlaceholder ? `Search ${searchPlaceholder}` : 'Search',- },- }-}diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.test.tsxdeleted file mode 100644index 75d68e319f3a..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.test.tsx+++ /dev/null@@ -1,240 +0,0 @@-import { cleanup, renderHook } from '@testing-library/react'-import { Provider } from 'kea'-import { ReactNode } from 'react'--import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'--import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { groupsModel } from '~/models/groupsModel'-import { performQuery } from '~/queries/query'-import { initKeaTests } from '~/test/init'-import { PropertyFilterType } from '~/types'--import { TaxonomicFilterGroupType } from '../types'-import { buildTaxonomicGroups } from '../utils/buildTaxonomicGroups'-import { useTaxonomicGroupsContext } from './useTaxonomicGroupsContext'--jest.mock('~/queries/query', () => ({- performQuery: jest.fn(),-}))--const wrapper = ({ children }: { children: ReactNode }): JSX.Element => <Provider>{children}</Provider>--describe('useTaxonomicGroupsContext', () => {- beforeEach(() => {- ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })- useMocks({- get: {- '/api/projects/:team/event_definitions': { results: [], count: 0 },- },- post: {- '/api/environments/:team/query': { results: [] },- },- })- initKeaTests()- actionsModel.mount()- groupsModel.mount()- })-- afterEach(() => {- cleanup()- })-- it('returns a context with required keys and arrays defaulted', () => {- const { result } = renderHook(() => useTaxonomicGroupsContext({}), { wrapper })- const ctx = result.current- expect(ctx).toMatchObject({- eventNames: [],- schemaColumns: [],- maxContextOptions: [],- hideBehavioralCohorts: false,- propertyFilters: { excludedProperties: {} },- hogQLExpressionComponentProps: { showBreakdownLabelHint: false },- })- expect(ctx.metadataSource).toEqual({ kind: 'HogQLQuery', query: 'select event from events' })- expect(Array.isArray(ctx.groupAnalyticsTaxonomicGroups)).toBe(true)- expect(Array.isArray(ctx.groupAnalyticsTaxonomicGroupNames)).toBe(true)- })-- it('forwards consumer-supplied input fields', () => {- const { result } = renderHook(- () =>- useTaxonomicGroupsContext({- eventNames: ['$pageview'],- suggestedFiltersLabel: 'Top picks',- hideBehavioralCohorts: true,- excludedProperties: { [TaxonomicFilterGroupType.Events]: ['blocked'] },- hogQLGlobals: { foo: 1 },- hogQLExpressionShowBreakdownLabelHint: true,- }),- { wrapper }- )- expect(result.current.eventNames).toEqual(['$pageview'])- expect(result.current.suggestedFiltersLabel).toBe('Top picks')- expect(result.current.hideBehavioralCohorts).toBe(true)- expect(result.current.propertyFilters.excludedProperties).toEqual({- [TaxonomicFilterGroupType.Events]: ['blocked'],- })- expect(result.current.hogQLExpressionComponentProps).toEqual({- globals: { foo: 1 },- showBreakdownLabelHint: true,- })- })-- it('memoises identity across renders when inputs are referentially stable', () => {- const input = { eventNames: ['$pageview'] }- const { result, rerender } = renderHook(() => useTaxonomicGroupsContext(input), { wrapper })- const first = result.current- rerender()- expect(result.current).toBe(first)- })-- it.each([- {- description: 'promotes the taxonomy-default primary property for $pageview',- eventNames: ['$pageview'],- expectedPromoted: ['$pathname'],- expectedSuggestedOptions: ['$pathname'],- },- {- description: 'promotes the taxonomy-default primary property for $mcp_tool_call',- eventNames: ['$mcp_tool_call'],- expectedPromoted: ['$mcp_tool_name'],- // The Suggested tab also seeds MCP_TOOL_CALL_SUGGESTED_PROPERTIES- // ($mcp_is_error) after the promoted primary property.- expectedSuggestedOptions: ['$mcp_tool_name', '$mcp_is_error'],- },- {- description: 'promotes nothing when no event is in context',- eventNames: [] as string[],- expectedPromoted: [],- expectedSuggestedOptions: [],- },- ])('$description', ({ eventNames, expectedPromoted, expectedSuggestedOptions }) => {- const { result } = renderHook(() => useTaxonomicGroupsContext({ eventNames }), { wrapper })- expect(result.current.promotedPropertiesForContextEvents).toEqual(expectedPromoted)- const suggestedGroup = buildTaxonomicGroups(result.current).find(- (g) => g.type === TaxonomicFilterGroupType.SuggestedFilters- )- expect(suggestedGroup?.options).toEqual(- expectedSuggestedOptions.map((name) => ({ name, group: TaxonomicFilterGroupType.EventProperties }))- )- })-- it.each([- { restriction: 'none', input: {}, expected: true },- {- restriction: 'exclusion',- input: { excludedProperties: { [TaxonomicFilterGroupType.EventProperties]: ['$pathname'] } },- expected: false,- },- {- restriction: 'allowlist mismatch',- input: { propertyAllowList: { [TaxonomicFilterGroupType.EventProperties]: ['$host'] } },- expected: false,- },- {- restriction: 'empty allowlist',- input: { propertyAllowList: { [TaxonomicFilterGroupType.EventProperties]: [] } },- expected: false,- },- {- restriction: 'allowlist match',- input: { propertyAllowList: { [TaxonomicFilterGroupType.EventProperties]: ['$pathname'] } },- expected: true,- },- { restriction: 'numeric properties only', input: { showNumericalPropsOnly: true }, expected: false },- ])('offers a primary property in Suggested with $restriction', ({ input, expected }) => {- const { result } = renderHook(() => useTaxonomicGroupsContext({ eventNames: ['$pageview'], ...input }), {- wrapper,- })- const suggested = buildTaxonomicGroups(result.current).find(- (group) => group.type === TaxonomicFilterGroupType.SuggestedFilters- )- expect(suggested?.options?.some((option) => option.name === '$pathname')).toBe(expected)- })-- it('feeds buildTaxonomicGroups end-to-end and produces a non-empty groups array', () => {- const { result } = renderHook(() => useTaxonomicGroupsContext({ eventNames: ['$pageview'] }), {- wrapper,- })- const groups = buildTaxonomicGroups(result.current)- expect(groups.length).toBeGreaterThan(20)- // Sanity-check a couple of well-known group types are present.- const types = new Set(groups.map((g) => g.type))- expect(types.has(TaxonomicFilterGroupType.Events)).toBe(true)- expect(types.has(TaxonomicFilterGroupType.PersonProperties)).toBe(true)- expect(types.has(TaxonomicFilterGroupType.Cohorts)).toBe(true)- expect(types.has(TaxonomicFilterGroupType.HogQLExpression)).toBe(true)- expect(types.has(TaxonomicFilterGroupType.SuggestedFilters)).toBe(true)- })-- it.each([- [TaxonomicFilterGroupType.Events, 'test', false, 'true'],- [TaxonomicFilterGroupType.CustomEvents, 'test', false, 'true'],- [TaxonomicFilterGroupType.Events, 'test', true, 'false'],- [TaxonomicFilterGroupType.CustomEvents, 'test', true, 'false'],- [TaxonomicFilterGroupType.Events, 'control', false, 'false'],- [TaxonomicFilterGroupType.CustomEvents, 'control', false, 'false'],- [TaxonomicFilterGroupType.Events, false, false, 'false'],- [TaxonomicFilterGroupType.CustomEvents, false, false, 'false'],- ])(- 'for %s with the flag %p and allowNonCapturedEvents %p, fuzzy_search is %p',- (groupType, flagValue, allowNonCapturedEvents, expected) => {- featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([], {- [FEATURE_FLAGS.TAXONOMIC_FILTER_FUZZY_EVENT_SEARCH]: flagValue,- })- const { result } = renderHook(() => useTaxonomicGroupsContext({ allowNonCapturedEvents }), { wrapper })- const group = buildTaxonomicGroups(result.current).find((item) => item.type === groupType)- expect(new URL(group!.endpoint!, 'http://localhost').searchParams.get('fuzzy_search')).toBe(expected)- }- )-- it('makes exception properties commit as event property filters', () => {- const { result } = renderHook(() => useTaxonomicGroupsContext({}), { wrapper })- const exceptionGroup = buildTaxonomicGroups(result.current).find(- (group) => group.type === TaxonomicFilterGroupType.ErrorTrackingProperties- )- const exceptionValue = exceptionGroup?.options?.find((option) => option.name === '$exception_values') as- | { name: string; propertyFilterType: PropertyFilterType }- | undefined-- expect(exceptionGroup?.getValue?.(exceptionValue)).toBe('$exception_values')- expect(exceptionValue?.propertyFilterType).toBe(PropertyFilterType.Event)- })-- it.each([- {- description: 'an active flag is selectable',- flag: { id: 1, key: 'my-flag', name: 'My flag', active: true },- expectedDisabled: false,- expectedName: 'my-flag',- },- {- description: 'an explicitly inactive flag is disabled',- flag: { id: 1, key: 'my-flag', name: 'My flag', active: false },- expectedDisabled: true,- expectedName: 'my-flag (disabled)',- },- {- // Recents/pinned entries are persisted stripped to { name, id }, so they carry no- // `active` field; a missing `active` must not read as disabled or recently-used- // flags can no longer be picked as flag-dependency match criteria in this (rebuild)- // group definition either. See the same guard in taxonomicFilterLogic.test.ts.- description: 'a recently-used flag missing the active field stays selectable',- flag: { name: '732889', id: 732889 },- expectedDisabled: false,- expectedName: '732889',- },- ])('Feature Flags group getIsDisabled/getName: $description', ({ flag, expectedDisabled, expectedName }) => {- const { result } = renderHook(() => useTaxonomicGroupsContext({}), { wrapper })- const groups = buildTaxonomicGroups(result.current)- const flagGroup = groups.find((g) => g.type === TaxonomicFilterGroupType.FeatureFlags)- expect(flagGroup?.getIsDisabled).toBeDefined() // oxlint-disable-line jest/no-restricted-matchers- expect(flagGroup?.getIsDisabled?.(flag as any)).toBe(expectedDisabled)- expect(flagGroup?.getName?.(flag as any)).toBe(expectedName)- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.tsdeleted file mode 100644index de7919a57f83..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts+++ /dev/null@@ -1,199 +0,0 @@-/**- * Bridge hook between PostHog's kea logics and the pure `buildTaxonomicGroups`- * builder. Reads the same connections that `taxonomicFilterLogic.connect`- * declares, layers in prop-derived defaults, and returns a memoised- * `BuildTaxonomicGroupsContext` ready to feed into `buildTaxonomicGroups(ctx)`.- *- * This is the only kea-coupled layer of the new headless `useTaxonomicFilter`.- * Everything else operates on the returned plain-object context, so swapping- * kea for direct API calls later is a single-file change.- */-import { useActions, useValues } from 'kea'-import { useEffect, useMemo } from 'react'--import {- AllowedProperties,- ExcludedProperties,- SelectedProperties,- TaxonomicFilterGroupType,-} from 'lib/components/TaxonomicFilter/types'-import {- buildGroupAnalyticsTaxonomicGroupNames,- buildGroupAnalyticsTaxonomicGroups,-} from 'lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups'-import { BuildTaxonomicGroupsContext } from 'lib/components/TaxonomicFilter/utils/buildTaxonomicGroups'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { distinctPrimaryPropertiesForEvents } from 'lib/utils/events'-import { dataWarehouseSettingsSceneLogic } from 'scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic'-import { MaxContextTaxonomicFilterOption } from 'scenes/max/maxTypes'-import { projectLogic } from 'scenes/projectLogic'-import { teamLogic } from 'scenes/teamLogic'--import { groupsModel } from '~/models/groupsModel'-import { primaryEventPropertiesModel } from '~/models/primaryEventPropertiesModel'-import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'-import { AnyDataNode, DatabaseSchemaField, NodeKind } from '~/queries/schema/schema-general'--import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'--/**- * Inputs the headless hook needs from its consumer. A subset of- * `TaxonomicFilterProps` — only the fields that affect group definitions.- */-export interface UseTaxonomicGroupsContextInput {- allowNonCapturedEvents?: boolean- eventNames?: string[]- /** Requested group types — read by group definitions that adapt to which tabs are present. */- taxonomicGroupTypes?: TaxonomicFilterGroupType[]- schemaColumns?: DatabaseSchemaField[]- schemaColumnsLoading?: boolean- metadataSource?: AnyDataNode- suggestedFiltersLabel?: string- excludedProperties?: ExcludedProperties- /** Keep offering events whose data is moving out of the `events` table. See `TaxonomicFilterProps`. */- includeHiddenEvents?: boolean- propertyAllowList?: AllowedProperties- showNumericalPropsOnly?: boolean- selectedProperties?: SelectedProperties- maxContextOptions?: MaxContextTaxonomicFilterOption[]- hideBehavioralCohorts?: boolean- /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */- showCohortFlagTargeting?: boolean- endpointFilters?: Record<string, any>- hogQLGlobals?: Record<string, any>- hogQLExpressionShowBreakdownLabelHint?: boolean-}--const DEFAULT_METADATA_SOURCE: AnyDataNode = {- kind: NodeKind.HogQLQuery,- query: 'select event from events',-}--const EMPTY_OBJECT = Object.freeze({}) as Record<string, never>-const EMPTY_ARRAY: readonly never[] = Object.freeze([])--export function useTaxonomicGroupsContext(input: UseTaxonomicGroupsContextInput): BuildTaxonomicGroupsContext {- const { currentTeam } = useValues(teamLogic)- const { currentProjectId } = useValues(projectLogic)- const { groupTypes, aggregationLabel } = useValues(groupsModel)- // Mounted purely so the dataWarehouse popover doesn't error out when the- // logic isn't otherwise on the page — same reason taxonomicFilterLogic- // does it.- useValues(dataWarehouseSettingsSceneLogic)- useValues(joinsLogic)- const { eventMetadataPropertyDefinitions, personMetadataPropertyDefinitions } = useValues(propertyDefinitionsModel)- const { featureFlags } = useValues(featureFlagLogic)- const { primaryProperties } = useValues(primaryEventPropertiesModel)- const { ensureLoadedForEvents } = useActions(primaryEventPropertiesModel)-- // Mirrors taxonomicFilterLogic's afterMount/propsChanged: fetch any- // team-configured primary-property overrides for the events in context.- // Content-keyed like the ctx memo below — consumers pass fresh array- // literals per render, and ensureLoadedForEvents shouldn't refire for a- // referentially-new-but-equal list.- const eventNames = input.eventNames- const eventNamesKey = JSON.stringify(eventNames ?? [])- useEffect(() => {- if (eventNames?.length) {- ensureLoadedForEvents(eventNames)- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [eventNamesKey, ensureLoadedForEvents])-- // Mirrors the `eventNamesWithPrimaryProperties` selector in- // taxonomicFilterLogic: the distinct promoted properties for the events in- // context (taxonomy default first, then team override).- const promotedPropertiesForContextEvents = useMemo(- () => distinctPrimaryPropertiesForEvents(eventNames ?? [], primaryProperties),- // eslint-disable-next-line react-hooks/exhaustive-deps- [eventNamesKey, primaryProperties]- )-- return useMemo<BuildTaxonomicGroupsContext>(() => {- const propertyFilters = {- excludedProperties: (input.excludedProperties ?? EMPTY_OBJECT) as Record<- TaxonomicFilterGroupType,- (string | number | null)[]- >,- propertyAllowList: input.propertyAllowList as- | Record<TaxonomicFilterGroupType, (string | number | null)[]>- | undefined,- showNumericalPropsOnly: input.showNumericalPropsOnly,- }- const hogQLExpressionComponentProps = {- globals: input.hogQLGlobals,- showBreakdownLabelHint: input.hogQLExpressionShowBreakdownLabelHint ?? false,- }- return {- // `BuildTaxonomicGroupsContext.currentTeam` is non-nullable; the- // logic-backed value is nullable until the team boots. Cast- // through `unknown` — the consuming `buildTaxonomicGroups`- // path tolerates a missing team for the early-mount frame.- currentTeam: currentTeam as unknown as BuildTaxonomicGroupsContext['currentTeam'],- projectId: currentProjectId,- groupAnalyticsTaxonomicGroups: buildGroupAnalyticsTaxonomicGroups(- groupTypes,- currentProjectId,- aggregationLabel- ),- groupAnalyticsTaxonomicGroupNames: buildGroupAnalyticsTaxonomicGroupNames(- groupTypes,- currentTeam?.id ?? 0,- aggregationLabel- ),- eventNames: input.eventNames ?? (EMPTY_ARRAY as unknown as string[]),- taxonomicGroupTypes: input.taxonomicGroupTypes,- promotedPropertiesForContextEvents,- schemaColumns: input.schemaColumns ?? (EMPTY_ARRAY as unknown as DatabaseSchemaField[]),- schemaColumnsLoading: input.schemaColumnsLoading,- metadataSource: input.metadataSource ?? DEFAULT_METADATA_SOURCE,- suggestedFiltersLabel: input.suggestedFiltersLabel,- propertyFilters,- eventMetadataPropertyDefinitions,- personMetadataPropertyDefinitions,- maxContextOptions: input.maxContextOptions ?? (EMPTY_ARRAY as unknown as MaxContextTaxonomicFilterOption[]),- hideBehavioralCohorts: input.hideBehavioralCohorts ?? false,- showCohortFlagTargeting: input.showCohortFlagTargeting ?? false,- endpointFilters: input.endpointFilters,- hogQLExpressionComponentProps,- // `featureFlags` from featureFlagLogic returns the project's- // own `FeatureFlagsSet` shape; widen to the looser- // `Record<string, boolean | string | undefined>` the- // taxonomic-groups builder accepts.- featureFlags: featureFlags as unknown as BuildTaxonomicGroupsContext['featureFlags'],- includeHiddenEvents: input.includeHiddenEvents,- allowNonCapturedEvents: input.allowNonCapturedEvents ?? false,- }- }, [- currentTeam,- currentProjectId,- groupTypes,- aggregationLabel,- eventMetadataPropertyDefinitions,- personMetadataPropertyDefinitions,- featureFlags,- promotedPropertiesForContextEvents,- // Content-keyed: consumers pass fresh array literals per render. The legacy logic- // stabilizes the same props differently — reference-equality inputs with objectsEqual- // on the selector result (see eventNamesWithPrimaryProperties) — same end effect.- // eslint-disable-next-line react-hooks/exhaustive-deps- JSON.stringify(input.eventNames),- // eslint-disable-next-line react-hooks/exhaustive-deps- JSON.stringify(input.taxonomicGroupTypes),- input.schemaColumns,- input.schemaColumnsLoading,- input.metadataSource,- input.suggestedFiltersLabel,- input.excludedProperties,- input.includeHiddenEvents,- input.allowNonCapturedEvents,- input.propertyAllowList,- input.showNumericalPropsOnly,- input.maxContextOptions,- input.hideBehavioralCohorts,- input.showCohortFlagTargeting,- input.endpointFilters,- input.hogQLGlobals,- input.hogQLExpressionShowBreakdownLabelHint,- ])-}diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicLocalOverrides.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicLocalOverrides.tsdeleted file mode 100644index 62b03eef1c92..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicLocalOverrides.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * Bridge hook that subscribes to every kea logic the legacy- * `infiniteListLogic.rawLocalItems` selector reads via `group.logic` +- * `group.value`. Returns a `getLocalOverride(groupType)` function the- * orchestrator threads into per-tab `useGroupList(...)` calls so that- * logic-backed groups (Actions, Cohorts, Experiments, Dashboards, Recent,- * Pinned) populate their counts and item lists correctly.- *- * Without this bridge, headless `useGroupList` would only see `group.options`- * + `optionsFromProp` and report `0` for every logic-backed tab.- */-import { useValues } from 'kea'-import { useCallback, useMemo } from 'react'--import { recentTaxonomicFiltersLogic } from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'-import { taxonomicFilterPinnedPropertiesLogic } from 'lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic'-import {- ExcludedOperators,- ExcludedProperties,- SelectingKeyOnly,- TaxonomicDefinitionTypes,- TaxonomicFilterGroupType,-} from 'lib/components/TaxonomicFilter/types'-import {- filterPinnedForContext,- filterRecentsForContext,-} from 'lib/components/TaxonomicFilter/utils/suggestedContextFilters'-import { dataWarehouseSettingsSceneLogic } from 'scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic'--import { actionsModel } from '~/models/actionsModel'-import { dashboardsModel } from '~/models/dashboardsModel'--import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'-import { experimentsLogic } from 'products/experiments/frontend/scenes/experimentsLogic'--export type GetLocalOverride = (groupType: TaxonomicFilterGroupType) => TaxonomicDefinitionTypes[] | undefined--export function useTaxonomicLocalOverrides(context: {- taxonomicGroupTypes: TaxonomicFilterGroupType[]- excludedOperators?: ExcludedOperators- selectingKeyOnly?: SelectingKeyOnly- excludedProperties?: ExcludedProperties-}): GetLocalOverride {- const { taxonomicGroupTypes, excludedOperators, selectingKeyOnly, excludedProperties } = context- const { actionsSorted } = useValues(actionsModel)- const { recentFilterItems } = useValues(recentTaxonomicFiltersLogic)- const { pinnedFilterItems } = useValues(taxonomicFilterPinnedPropertiesLogic)- const { nameSortedDashboards } = useValues(dashboardsModel)- const { experiments } = useValues(experimentsLogic)- const { dataWarehouseTablesAndViews } = useValues(dataWarehouseSettingsSceneLogic)- const { columnsJoinedToPersons } = useValues(joinsLogic)-- // Memoized so repeated calls return the same array reference — the result feeds- // `useGroupList` memo deps and `useEffect` deps (e.g. the sole-substantive-group- // recents promotion), where a fresh array per render means an infinite update loop.- const contextFilteredRecentItems = useMemo(- () =>- filterRecentsForContext(- recentFilterItems,- taxonomicGroupTypes,- excludedOperators,- selectingKeyOnly,- excludedProperties- ),- [recentFilterItems, taxonomicGroupTypes, excludedOperators, selectingKeyOnly, excludedProperties]- )- const contextFilteredPinnedItems = useMemo(- () => filterPinnedForContext(pinnedFilterItems, taxonomicGroupTypes, excludedProperties),- [pinnedFilterItems, taxonomicGroupTypes, excludedProperties]- )-- return useCallback(- (groupType: TaxonomicFilterGroupType): TaxonomicDefinitionTypes[] | undefined => {- switch (groupType) {- case TaxonomicFilterGroupType.Actions:- return actionsSorted as unknown as TaxonomicDefinitionTypes[]- case TaxonomicFilterGroupType.RecentFilters:- return contextFilteredRecentItems- case TaxonomicFilterGroupType.PinnedFilters:- return contextFilteredPinnedItems- case TaxonomicFilterGroupType.Dashboards:- return nameSortedDashboards as unknown as TaxonomicDefinitionTypes[]- case TaxonomicFilterGroupType.Experiments:- return experiments as unknown as TaxonomicDefinitionTypes[]- case TaxonomicFilterGroupType.DataWarehouse:- return dataWarehouseTablesAndViews as unknown as TaxonomicDefinitionTypes[]- case TaxonomicFilterGroupType.DataWarehousePersonProperties:- return columnsJoinedToPersons as unknown as TaxonomicDefinitionTypes[]- default:- return undefined- }- },- [- actionsSorted,- contextFilteredRecentItems,- contextFilteredPinnedItems,- nameSortedDashboards,- experiments,- dataWarehouseTablesAndViews,- columnsJoinedToPersons,- ]- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.test.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.test.tsdeleted file mode 100644index da81c8508ed9..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.test.ts+++ /dev/null@@ -1,267 +0,0 @@-import { act, renderHook, waitFor } from '@testing-library/react'--import {- __clearTaxonomicResourceCache,- invalidateTaxonomicResource,- invalidateTaxonomicResourcesWhere,- peekTaxonomicResource,- useTaxonomicResource,-} from './useTaxonomicResource'--describe('useTaxonomicResource', () => {- beforeEach(() => {- __clearTaxonomicResourceCache()- })-- it('runs the query function and exposes data', async () => {- const fn = jest.fn().mockResolvedValue({ results: ['a', 'b'] })- const { result } = renderHook(() => useTaxonomicResource(['k', 1], fn))-- expect(result.current.isLoading).toBe(true)- expect(result.current.data).toBeUndefined()-- await waitFor(() => expect(result.current.data).toEqual({ results: ['a', 'b'] }))- expect(result.current.isLoading).toBe(false)- expect(result.current.isFetching).toBe(false)- expect(fn).toHaveBeenCalledTimes(1)- })-- it('returns cached data within staleTime without refetching', async () => {- const fn = jest.fn().mockResolvedValue('first')- const { result, unmount } = renderHook(() => useTaxonomicResource(['cached'], fn, { staleTime: 60_000 }))- await waitFor(() => expect(result.current.data).toBe('first'))- unmount()-- const fn2 = jest.fn().mockResolvedValue('second')- const r2 = renderHook(() => useTaxonomicResource(['cached'], fn2, { staleTime: 60_000 }))- // Should be served from cache, no new fetch.- expect(r2.result.current.data).toBe('first')- expect(fn2).not.toHaveBeenCalled()- })-- it('refetches after staleTime elapses', async () => {- const fn = jest.fn().mockResolvedValueOnce('v1').mockResolvedValueOnce('v2')- // staleTime 0 means always stale → always refetch on mount.- const { result, unmount } = renderHook(() => useTaxonomicResource(['stale'], fn, { staleTime: 0 }))- await waitFor(() => expect(result.current.data).toBe('v1'))- expect(fn).toHaveBeenCalledTimes(1)- unmount()-- const r2 = renderHook(() => useTaxonomicResource(['stale'], fn, { staleTime: 0 }))- await waitFor(() => expect(r2.result.current.data).toBe('v2'))- expect(fn).toHaveBeenCalledTimes(2)- })-- it('skips execution when enabled=false', () => {- const fn = jest.fn().mockResolvedValue('x')- const { result } = renderHook(() => useTaxonomicResource(['gated'], fn, { enabled: false }))- expect(fn).not.toHaveBeenCalled()- expect(result.current.isLoading).toBe(false)- expect(result.current.data).toBeUndefined()- })-- it('keepPreviousData returns prior data while a new key is loading', async () => {- let resolveSecond: (v: string) => void = () => {}- const fn = jest- .fn()- .mockResolvedValueOnce('a')- .mockImplementationOnce(() => new Promise<string>((r) => (resolveSecond = r)))-- const { result, rerender } = renderHook(- ({ id }: { id: number }) => useTaxonomicResource(['kpd', id], fn, { keepPreviousData: true }),- { initialProps: { id: 1 } }- )- await waitFor(() => expect(result.current.data).toBe('a'))-- rerender({ id: 2 })- // Second key still loading, previous data should be visible.- expect(result.current.data).toBe('a')- expect(result.current.isFetching).toBe(true)-- await act(async () => {- resolveSecond('b')- await Promise.resolve()- })- await waitFor(() => expect(result.current.data).toBe('b'))- })-- it('without keepPreviousData, data is undefined while new key loads', async () => {- let resolveSecond: (v: string) => void = () => {}- const fn = jest- .fn()- .mockResolvedValueOnce('a')- .mockImplementationOnce(() => new Promise<string>((r) => (resolveSecond = r)))-- const { result, rerender } = renderHook(- ({ id }: { id: number }) => useTaxonomicResource(['nkpd', id], fn, { keepPreviousData: false }),- { initialProps: { id: 1 } }- )- await waitFor(() => expect(result.current.data).toBe('a'))-- rerender({ id: 2 })- expect(result.current.data).toBeUndefined()- expect(result.current.isLoading).toBe(true)-- await act(async () => {- resolveSecond('b')- await Promise.resolve()- })- await waitFor(() => expect(result.current.data).toBe('b'))- })-- it('dedupes concurrent identical requests', async () => {- const fn = jest.fn().mockImplementation(() => new Promise((r) => setTimeout(() => r('once'), 10)))- const a = renderHook(() => useTaxonomicResource(['dedup'], fn))- const b = renderHook(() => useTaxonomicResource(['dedup'], fn))- await waitFor(() => expect(a.result.current.data).toBe('once'))- expect(b.result.current.data).toBe('once')- expect(fn).toHaveBeenCalledTimes(1)- })-- it('exposes errors and stops loading', async () => {- const fn = jest.fn().mockRejectedValue(new Error('boom'))- const { result } = renderHook(() => useTaxonomicResource(['err'], fn))- await waitFor(() => expect(result.current.error).toBeInstanceOf(Error))- expect((result.current.error as Error).message).toBe('boom')- expect(result.current.isLoading).toBe(false)- expect(result.current.data).toBeUndefined()- })-- it('refetch() bypasses staleTime and updates data', async () => {- const fn = jest.fn().mockResolvedValueOnce('first').mockResolvedValueOnce('second')- const { result } = renderHook(() => useTaxonomicResource(['refetch'], fn, { staleTime: 60_000 }))- await waitFor(() => expect(result.current.data).toBe('first'))-- await act(async () => {- await result.current.refetch()- })- await waitFor(() => expect(result.current.data).toBe('second'))- expect(fn).toHaveBeenCalledTimes(2)- })-- it('aborts in-flight request when last subscriber unmounts, not when it re-renders', async () => {- const seenSignals: AbortSignal[] = []- const fn = jest.fn().mockImplementation(({ signal }: { signal: AbortSignal }) => {- seenSignals.push(signal)- return new Promise(() => {})- })- const { rerender, unmount } = renderHook(() => useTaxonomicResource(['abort'], fn))- expect(seenSignals).toHaveLength(1)- expect(seenSignals[0].aborted).toBe(false)- rerender()- expect(seenSignals).toHaveLength(1)- expect(seenSignals[0].aborted).toBe(false)- unmount()- expect(seenSignals[0].aborted).toBe(true)- })-- it('does not poison the cache key when an in-flight request is aborted', async () => {- // First call rejects with an AbortError when its signal aborts;- // second call (after re-mount) resolves normally.- const fn = jest- .fn()- .mockImplementationOnce(- ({ signal }: { signal: AbortSignal }) =>- new Promise<string>((_resolve, reject) => {- signal.addEventListener('abort', () =>- reject(new DOMException('The operation was aborted.', 'AbortError'))- )- })- )- .mockResolvedValueOnce('second')-- // Mount, then unmount before the request settles → aborts it.- const { unmount } = renderHook(() => useTaxonomicResource(['poison'], fn))- unmount()- // Let the abort rejection settle.- await act(async () => {- await Promise.resolve()- })-- // Re-mounting the same key must re-fetch — the aborted request must- // not have stored an error that halts auto-fetch forever.- const r2 = renderHook(() => useTaxonomicResource(['poison'], fn))- await waitFor(() => expect(r2.result.current.data).toBe('second'))- expect(r2.result.current.error).toBeUndefined()- expect(fn).toHaveBeenCalledTimes(2)- })-- it('passes a fresh AbortSignal that is not aborted while a subscriber is mounted', async () => {- const seen: AbortSignal[] = []- const fn = jest.fn().mockImplementation(({ signal }: { signal: AbortSignal }) => {- seen.push(signal)- return Promise.resolve('ok')- })- const { result } = renderHook(() => useTaxonomicResource(['signal'], fn))- await waitFor(() => expect(result.current.data).toBe('ok'))- expect(seen[0].aborted).toBe(false)- })-- it('hashes the key as JSON so identical content shares the cache slot', async () => {- const fn = jest.fn().mockResolvedValue('shared')- const r1 = renderHook(() => useTaxonomicResource(['hash', { a: 1, b: 2 }], fn))- const r2 = renderHook(() => useTaxonomicResource(['hash', { a: 1, b: 2 }], fn))- await waitFor(() => expect(r1.result.current.data).toBe('shared'))- expect(r2.result.current.data).toBe('shared')- expect(fn).toHaveBeenCalledTimes(1)- })-- it('invalidateTaxonomicResource() forces refetch on next read', async () => {- const fn = jest.fn().mockResolvedValueOnce('x').mockResolvedValueOnce('y')- const { result, rerender } = renderHook(() => useTaxonomicResource(['inv'], fn, { staleTime: 60_000 }))- await waitFor(() => expect(result.current.data).toBe('x'))- invalidateTaxonomicResource(['inv'])- rerender()- await waitFor(() => expect(result.current.data).toBe('y'))- expect(fn).toHaveBeenCalledTimes(2)- })-- it('invalidateTaxonomicResourcesWhere() invalidates every key matching the predicate', async () => {- const fnA = jest.fn().mockResolvedValueOnce('a1').mockResolvedValueOnce('a2')- const fnB = jest.fn().mockResolvedValueOnce('b1').mockResolvedValueOnce('b2')- const fnC = jest.fn().mockResolvedValueOnce('c1')-- const ra = renderHook(() => useTaxonomicResource(['taxonomic-list', 'cohorts', 'k1'], fnA))- const rb = renderHook(() => useTaxonomicResource(['taxonomic-list', 'cohorts', 'k2'], fnB))- const rc = renderHook(() => useTaxonomicResource(['taxonomic-list', 'events', 'k3'], fnC))-- await waitFor(() => expect(ra.result.current.data).toBe('a1'))- await waitFor(() => expect(rb.result.current.data).toBe('b1'))- await waitFor(() => expect(rc.result.current.data).toBe('c1'))-- // Invalidate only the cohort entries — events stays cached.- invalidateTaxonomicResourcesWhere((key) => key[0] === 'taxonomic-list' && key[1] === 'cohorts')-- ra.rerender()- rb.rerender()- rc.rerender()-- await waitFor(() => expect(ra.result.current.data).toBe('a2'))- await waitFor(() => expect(rb.result.current.data).toBe('b2'))- expect(fnA).toHaveBeenCalledTimes(2)- expect(fnB).toHaveBeenCalledTimes(2)- expect(fnC).toHaveBeenCalledTimes(1)- })-- it('peekTaxonomicResource() returns current cached value', async () => {- const fn = jest.fn().mockResolvedValue({ items: [1, 2] })- const { result } = renderHook(() => useTaxonomicResource(['peek'], fn))- await waitFor(() => expect(result.current.data).toEqual({ items: [1, 2] }))- expect(peekTaxonomicResource(['peek'])).toEqual({ items: [1, 2] })- expect(peekTaxonomicResource(['peek', 'missing'])).toBeUndefined()- })-- it('survives changing fn identity without re-fetching when data is fresh', async () => {- const fn1 = jest.fn().mockResolvedValue('once')- const fn2 = jest.fn().mockResolvedValue('twice')- const { result, rerender } = renderHook(- ({ f }: { f: jest.Mock }) => useTaxonomicResource(['fnid'], f, { staleTime: 60_000 }),- { initialProps: { f: fn1 } }- )- await waitFor(() => expect(result.current.data).toBe('once'))- rerender({ f: fn2 })- // Fresh data, fn identity change must not trigger a new fetch.- expect(fn2).not.toHaveBeenCalled()- expect(result.current.data).toBe('once')- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.tsdeleted file mode 100644index 7aa1a6cda719..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.ts+++ /dev/null@@ -1,310 +0,0 @@-/**- * Internal data-fetching hook scoped to TaxonomicFilter.- *- * Shaped intentionally like `@tanstack/react-query`'s `useQuery` so we can- * swap to TanStack later without touching call-sites:- *- * const { data, isLoading, isFetching, error, refetch } = useTaxonomicResource(- * ['event_definitions', search, offset],- * ({ signal }) => fetchEventDefinitions(search, offset, { signal }),- * { staleTime: 60_000, keepPreviousData: true }- * )- *- * Behaviour mirrors react-query semantics for: cache key shape, staleTime,- * keepPreviousData, dedup of in-flight identical requests, AbortController- * propagation, and refetch().- *- * Differences from react-query (intentionally minimal):- * - No retries, no suspense, no infinite queries (we paginate via key).- * - No global QueryClient or React context — single module-scoped cache.- * - No background refetch on window focus / interval.- *- * If we need any of those, swap `useTaxonomicResource` for `useQuery` from- * `@tanstack/react-query`. The signatures are call-compatible.- */-import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'--/** Leading element of `useGroupList`'s `remoteKey` — the cached-first-page / full remote fetch.- * Owned here beside the cache so key producers and invalidation predicates share one source. */-export const TAXONOMIC_LIST_KEY_FAMILY = 'taxonomic-list'-/** Leading element of `useGroupList`'s `serverSearchKey` — the server-side search fallback for- * `clientFilterFirstPage` groups whose dataset exceeds one page. */-export const TAXONOMIC_LIST_SEARCH_KEY_FAMILY = 'taxonomic-list-search'--export interface UseTaxonomicResourceOptions {- /** Disable execution. Defaults to true. */- enabled?: boolean- /** Time in ms during which a cached entry is considered fresh and not re-fetched. Default 60_000. */- staleTime?: number- /** When the key changes, return the previous data while the new request is in flight. Default true. */- keepPreviousData?: boolean-}--export interface UseTaxonomicResourceResult<T> {- data: T | undefined- isLoading: boolean- isFetching: boolean- error: unknown- refetch: () => Promise<T | undefined>-}--export type ResourceQueryFn<T> = (ctx: { signal: AbortSignal }) => Promise<T>--const DEFAULT_STALE_TIME = 60_000--interface CacheEntry {- data: unknown- error: unknown- /** ms timestamp of last successful resolution. 0 if no data yet. */- ts: number- /** in-flight request, deduped across consumers. undefined when settled. */- inflight?: Promise<unknown>- /** abort controller for the in-flight request. */- abort?: AbortController- /** subscribers to notify on entry change. */- subscribers: Set<() => void>-}--const cache = new Map<string, CacheEntry>()--function hashKey(key: ReadonlyArray<unknown>): string {- // Stable JSON for deterministic cache keys. Object key order matters here —- // callers should pass arrays of primitives or objects with stable shape.- return JSON.stringify(key)-}--function getEntry(hash: string): CacheEntry {- let entry = cache.get(hash)- if (!entry) {- entry = { data: undefined, error: undefined, ts: 0, subscribers: new Set() }- cache.set(hash, entry)- }- return entry-}--function notify(entry: CacheEntry): void {- for (const sub of entry.subscribers) {- sub()- }-}--function isFresh(entry: CacheEntry, staleTime: number): boolean {- return entry.ts > 0 && Date.now() - entry.ts < staleTime-}--function execute<T>(hash: string, fn: ResourceQueryFn<T>): Promise<T> {- const entry = getEntry(hash)- if (entry.inflight) {- return entry.inflight as Promise<T>- }- const abort = new AbortController()- entry.abort = abort- entry.error = undefined- const promise = (async () => {- try {- const data = await fn({ signal: abort.signal })- // If a newer execute() replaced our controller, ignore stale resolve.- if (entry.abort !== abort) {- return data- }- entry.data = data- entry.error = undefined- entry.ts = Date.now()- entry.inflight = undefined- entry.abort = undefined- notify(entry)- return data- } catch (err) {- if (entry.abort !== abort) {- throw err- }- // An abort is not a real failure. Storing it as `entry.error`- // would poison this cache key — the error-halts-autofetch guard- // in the effect then refuses to ever re-fetch it, so revisiting- // the same query key (e.g. backspacing to a search term whose- // in-flight request was cancelled by the next keystroke) shows a- // permanently empty list. Leave the entry clean (no data, no- // error, ts untouched) so a later visit re-fetches.- if (abort.signal.aborted) {- entry.inflight = undefined- entry.abort = undefined- notify(entry)- throw err- }- entry.error = err- entry.inflight = undefined- entry.abort = undefined- notify(entry)- throw err- }- })()- entry.inflight = promise as Promise<unknown>- return promise-}--export function useTaxonomicResource<T>(- key: ReadonlyArray<unknown>,- fn: ResourceQueryFn<T>,- opts: UseTaxonomicResourceOptions = {}-): UseTaxonomicResourceResult<T> {- const { enabled = true, staleTime = DEFAULT_STALE_TIME, keepPreviousData = true } = opts- const hash = hashKey(key)- const entry = getEntry(hash)-- // Capture latest fn in a ref so we don't trigger refetches when fn identity changes.- const fnRef = useRef(fn)- fnRef.current = fn-- // Subscribe to cache entry changes. Aborts any in-flight request- // when the last consumer unmounts, but deliberately leaves the- // settled entry in the cache — `staleTime` preserves data for- // re-mounts within the freshness window (one of the documented- // behaviours: see the "returns cached data within staleTime- // without refetching" test). Memory growth from long-lived- // sessions with many distinct cache keys is a real concern but- // belongs in a separate eviction strategy (LRU cap or time-based- // purge), not on unsubscribe — the latter conflicts with the- // staleTime contract.- //- // `subscribe` keeps one identity per cache entry because React unsubscribes and- // subscribes again each time this function changes. With a new function on every- // render, any re-render of the sole consumer aborts its in-flight request and the- // fetch effect sends it again. Two such resources in one component then abort each- // other in turn, because the abort of one re-renders the component, and that- // re-render aborts the other. The result is an endless loop of requests.- const subscribe = useCallback(- (notifyChange: () => void) => {- entry.subscribers.add(notifyChange)- return () => {- entry.subscribers.delete(notifyChange)- if (entry.subscribers.size === 0 && entry.abort) {- entry.abort.abort()- }- }- },- [entry]- )- useSyncExternalStore(- subscribe,- () => entry.ts + ':' + (entry.error ? 'e' : 'd') + ':' + (entry.inflight ? '1' : '0'),- () => '0:d:0'- )-- // Track previous data for keepPreviousData behaviour.- const previousDataRef = useRef<T | undefined>(undefined)- if (entry.data !== undefined) {- previousDataRef.current = entry.data as T- }-- // Track which hash this hook instance has already kicked off a fetch for.- // Without this, after a successful resolve the entry.ts change re-fires- // the effect under `staleTime: 0`, looping forever.- const lastFiredHashRef = useRef<string | null>(null)-- // Kick off the fetch in an effect (mutating the cache during render breaks- // useSyncExternalStore — the snapshot would change between render and- // commit, causing tearing). dedup via entry.inflight makes this idempotent- // across StrictMode double-mount and concurrent consumers.- useEffect(() => {- if (!enabled) {- return- }- // We've already fired for this (instance, hash) and a resolve has happened.- // Don't auto-refire — let the consumer call refetch() or remount.- if (lastFiredHashRef.current === hash && entry.ts > 0) {- return- }- if (entry.inflight || entry.error !== undefined) {- return- }- if (isFresh(entry, staleTime)) {- lastFiredHashRef.current = hash- return- }- lastFiredHashRef.current = hash- execute(hash, fnRef.current).catch(() => {})- // Re-run when the key changes or staleness markers move (entry.ts after- // resolve/invalidate, entry.inflight, entry.error).- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [hash, enabled, staleTime, entry.ts, entry.inflight, entry.error])-- // Fold the "we're about to fetch (effect hasn't run yet)" state into- // isLoading/isFetching so consumers see a stable busy flag from the very- // first render, matching react-query's useQuery semantics. Errors halt- // auto-fetch — consumers must call refetch() to retry. Mirrors react-query's- // default behaviour (no automatic retry on error).- const willFetch = enabled && !isFresh(entry, staleTime) && !entry.inflight && entry.error === undefined- const isLoading = enabled && entry.data === undefined && (entry.inflight !== undefined || willFetch)- const isFetching = enabled && (entry.inflight !== undefined || willFetch)-- let data: T | undefined = entry.data as T | undefined- if (data === undefined && keepPreviousData) {- data = previousDataRef.current- }-- const refetch = async (): Promise<T | undefined> => {- try {- return await execute<T>(hash, fnRef.current)- } catch {- return undefined- }- }-- return { data, isLoading, isFetching, error: entry.error, refetch }-}--/** Test/utility: clear the entire cache. Not exported in production code paths. */-export function __clearTaxonomicResourceCache(): void {- for (const entry of cache.values()) {- entry.abort?.abort()- }- cache.clear()-}--/** Imperatively invalidate (mark stale) a single key. Clears any prior error. */-export function invalidateTaxonomicResource(key: ReadonlyArray<unknown>): void {- const entry = cache.get(hashKey(key))- if (entry) {- entry.ts = 0- entry.error = undefined- notify(entry)- }-}--/**- * Invalidate every cached entry whose key matches a predicate. Used by- * domain models (e.g. cohortsModel) to flush taxonomic cache slices when- * the underlying data mutates. The hash is the JSON-stringified key so- * we re-parse to feed structured input back to the predicate — keys are- * always plain arrays of JSON-safe values so the round-trip is lossless.- */-export function invalidateTaxonomicResourcesWhere(predicate: (key: unknown[]) => boolean): void {- for (const [hash, entry] of cache) {- let key: unknown[]- try {- key = JSON.parse(hash) as unknown[]- } catch {- continue- }- if (!predicate(key)) {- continue- }- entry.ts = 0- entry.error = undefined- notify(entry)- }-}--/** Subscribe to a key without rendering. Returns an unsubscribe fn. */-export function subscribeTaxonomicResource(key: ReadonlyArray<unknown>, listener: () => void): () => void {- const entry = getEntry(hashKey(key))- entry.subscribers.add(listener)- return () => {- entry.subscribers.delete(listener)- }-}--/** Synchronously read the current cached value (or undefined). For DevTools/debugging. */-export function peekTaxonomicResource<T>(key: ReadonlyArray<unknown>): T | undefined {- return cache.get(hashKey(key))?.data as T | undefined-}diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.tsindex 2663f76c2de1..51bc579def07 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts@@ -1873,11 +1873,10 @@ export const infiniteListLogic = kea<infiniteListLogicType>([promoteSelectedItemToFirstPosition: boolean | undefined) => {const { group, groupType, value } = selectionPromotionContext- // Collapse URL groups to a single "URL contains <query>" shortcut row- // (mirrors the rebuild menu's `COLLAPSED_TO_CONTAINS_ROW`). Only once- // the remote fetch for the *current* query has returned at least one- // match — otherwise the list is empty and the standard empty/loading- // states apply.+ // Collapse URL groups to a single "URL contains <query>" shortcut row.+ // Only once the remote fetch for the *current* query has returned at+ // least one match — otherwise the list is empty and the standard+ // empty/loading states apply.if (collapseUrlsToContainsRow && COLLAPSED_TO_CONTAINS_ROW.has(listGroupType)) {const trimmed = (searchQuery ?? '').trim()// The remote fetch is debounced and lags the typed query, so guard against a@@ -1897,7 +1896,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([const isSuggested = listGroupType === TaxonomicFilterGroupType.SuggestedFiltersconst recentPrefix = isSuggested && !searchQuery ? (contextFilteredRecentItems || []).slice(0, 3) : []// An item that is both recent and pinned shows once, under the section that- // renders first — recents (mirrors the rebuild Combobox's prefix dedupe).+ // renders first — recents.const pinnedPrefix =isSuggested && !searchQuery? withoutPinnedDuplicatesOfRecents(contextFilteredPinnedItems || [], recentPrefix).slice(0, 3)@@ -1954,8 +1953,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([} else {orderedBase = combinedResults}- // Mirrors the rebuild menu's Combobox idle promotion: with no search query,- // the committed selection leads the list so the user can see at a glance+ // With no search query, the committed selection leads the list so the user can see at a glance// what is currently picked — floated in place when the real row is loaded,// otherwise statically inserted as a synthetic row (the selection is known// at open; there's no need to wait for the loader). A leading null-valueddiff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsxdeleted file mode 100644index bad89783d026..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx+++ /dev/null@@ -1,1517 +0,0 @@-import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'--import '@testing-library/jest-dom'--import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { Provider } from 'kea'-import { useState } from 'react'--import { FEATURE_FLAGS } from 'lib/constants'-import * as featureFlagLogicModule from 'lib/logic/featureFlagLogic'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { teamLogic } from 'scenes/teamLogic'--import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'-import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { groupsModel } from '~/models/groupsModel'-import { performQuery } from '~/queries/query'-import { initKeaTests } from '~/test/init'-import { emptyPaginated } from '~/test/mocks/taxonomicFilterApiMock'--import { TaxonomicFilterHeadless } from '../headless'-import { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'-import { TaxonomicDefinitionTypes, TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'-import { MenuFilterCombobox, SEARCH_QUERY_DEBOUNCE_MS } from './Combobox'-import { MenuFilterEntry } from './types'--jest.mock('~/queries/query', () => ({- performQuery: jest.fn(),-}))--jest.mock('posthog-js', () => ({- __esModule: true,- default: { capture: jest.fn() },-}))--jest.mock('lib/api', () => require('~/test/mocks/taxonomicFilterApiMock').buildTaxonomicFilterApiMock())--const apiGet = jest.requireMock('lib/api').default.get as jest.MockedFunction<any>-const captureMock = jest.requireMock('posthog-js').default.capture as jest.Mock--function renderCombobox(): ReturnType<typeof render> {- return render(- <Provider>- <TaxonomicFilterHeadless.Root taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]} onChange={jest.fn()}>- <MenuFilterCombobox- drillTo={TaxonomicFilterGroupType.Cohorts}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )-}--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,- ...(endpoint ? { endpoint } : {}),- },- name,- }-}--function renderAll(options: {- groupTypes: TaxonomicFilterGroupType[]- recentEntries?: any[]- pinnedEntries?: any[]- searchQuery?: string- onCommit?: any- eventNames?: string[]- drillTo?: TaxonomicFilterGroupType-}): ReturnType<typeof render> {- return render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={options.groupTypes}- onChange={jest.fn()}- searchQuery={options.searchQuery ?? ''}- eventNames={options.eventNames}- >- <MenuFilterCombobox- drillTo={options.drillTo ?? 'all'}- recentEntries={options.recentEntries}- pinnedEntries={options.pinnedEntries}- onCommit={options.onCommit ?? jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )-}--function rowTexts(): string[] {- return Array.from(document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]')).map(- (el) => el.textContent ?? ''- )-}--// The category Select popup portal — scoping option lookups here avoids matching-// row badges/labels that repeat the option text (e.g. "Recent", "Pinned").-async function openedCategoryPopup(): Promise<HTMLElement> {- return await waitFor(() => {- const popup = document.querySelector<HTMLElement>('[data-slot="select-content"]')- if (!popup) {- throw new Error('category select popup not open')- }- return popup- })-}--function setFlagEvaluationsMode(mode: FlagEvaluationsModeEnumApi): void {- teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: mode })-}--const ANNOUNCEMENT_URL = 'https://example.com/announcement'--function setMoveNotices(enabled: boolean, url: string | null): void {- featureFlagLogicModule.featureFlagLogic.mount()- featureFlagLogicModule.featureFlagLogic.actions.setFeatureFlags([], {- [FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES]: enabled,- })- jest.spyOn(featureFlagLogicModule, 'getFeatureFlagPayload').mockReturnValue({ url })-}--describe('MenuFilterCombobox', () => {- beforeEach(() => {- __clearTaxonomicResourceCache()- apiGet.mockReset()- apiGet.mockImplementation(emptyPaginated)- captureMock.mockClear()- ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })- useMocks({})- initKeaTests()- actionsModel.mount()- groupsModel.mount()- })-- afterEach(() => cleanup())-- it('shows a loading skeleton while the cohorts fetch is in flight (not the empty state)', async () => {- // Hold the request open so the component sees `isLoading=true`.- let resolveFetch!: (value: { results: any[]; count: number }) => void- apiGet.mockImplementation(- () =>- new Promise((resolve) => {- resolveFetch = resolve- })- )-- renderCombobox()-- // While loading: skeleton present, no "No Cohorts found" copy.- await waitFor(() => {- expect(screen.getByTestId('menu-filter-loading')).toBeInTheDocument()- })- expect(screen.queryByTestId('menu-filter-empty')).not.toBeInTheDocument()- expect(screen.queryByText(/No "Cohorts" found/)).not.toBeInTheDocument()-- // Resolve to an empty list: skeleton disappears, empty state takes over.- resolveFetch({ results: [], count: 0 })- await waitFor(() => {- expect(screen.getByTestId('menu-filter-empty')).toBeInTheDocument()- })- expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument()- expect(within(screen.getByTestId('menu-filter-empty')).getByText(/No "Cohorts" found/)).toBeInTheDocument()- })-- it('renders results once the fetch resolves with items', async () => {- apiGet.mockResolvedValue({- results: [- { id: 1, name: 'Internal team' },- { id: 2, name: 'Power users' },- ],- count: 2,- })-- renderCombobox()-- await waitFor(() => {- expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument()- })- // Skeleton gone + empty state not shown — items must have rendered.- expect(screen.queryByTestId('menu-filter-empty')).not.toBeInTheDocument()- // Row text appears inside the result rows.- expect(screen.getAllByText('Internal team').length).toBeGreaterThan(0)- expect(screen.getAllByText('Power users').length).toBeGreaterThan(0)- })-- it('shows an error state with retry when the cohorts fetch fails (not the empty state), captures it once, and retry re-fetches', async () => {- const user = userEvent.setup()- apiGet.mockImplementation((url: string) =>- url.includes('cohorts') ? Promise.reject(new Error('network error')) : emptyPaginated()- )-- renderCombobox()-- await waitFor(() => {- expect(screen.getByTestId('menu-filter-error')).toBeInTheDocument()- })- expect(screen.getByText("Couldn't load results")).toBeInTheDocument()- expect(screen.queryByTestId('menu-filter-empty')).not.toBeInTheDocument()- expect(screen.queryByText(/No "Cohorts" found/)).not.toBeInTheDocument()- // Fires once for the failed fetch — mirrors legacy's per-group+query dedup.- expect(captureMock).toHaveBeenCalledWith(- 'taxonomic filter fetch failed',- expect.objectContaining({ groupType: TaxonomicFilterGroupType.Cohorts, searchQuery: '' })- )- expect(- captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')- ).toHaveLength(1)-- apiGet.mockResolvedValueOnce({ results: [{ id: 1, name: 'Internal team' }], count: 1 })- await user.click(screen.getByText('Try again'))-- await waitFor(() => {- expect(screen.queryByTestId('menu-filter-error')).not.toBeInTheDocument()- })- expect(screen.getAllByText('Internal team').length).toBeGreaterThan(0)- })-- it('does not capture a stale `taxonomic filter fetch failed` or show the error block after a failed query is followed by a new one that succeeds', async () => {- apiGet.mockImplementation((url: string) =>- url.includes('search=fail') ? Promise.reject(new Error('network error')) : emptyPaginated()- )- const tree = (q: string): JSX.Element => (- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}- onChange={jest.fn()}- searchQuery={q}- >- <MenuFilterCombobox- drillTo={TaxonomicFilterGroupType.Events}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- const { rerender } = render(tree('fail'))- await waitFor(() => expect(screen.getByTestId('menu-filter-error')).toBeInTheDocument())- expect(- captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')- ).toHaveLength(1)- // A failed fetch is not a dead-end search — it must not also inflate the- // `taxonomic filter empty result` metric.- expect(- captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter empty result')- ).toHaveLength(0)-- apiGet.mockImplementation((url: string) =>- url.includes('search=fail')- ? Promise.reject(new Error('network error'))- : Promise.resolve({ results: [{ name: 'ok_event' }], count: 1 })- )- rerender(tree('ok'))-- await waitFor(() => expect(screen.getAllByText('ok_event').length).toBeGreaterThan(0))- expect(screen.queryByTestId('menu-filter-error')).not.toBeInTheDocument()- // The new query's own fetch never failed, so the dedup count must stay at the one- // genuine failure — a stale report for "fail" must not recapture under "ok".- expect(- captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')- ).toHaveLength(1)- })-- it('does not recapture `taxonomic filter fetch failed` for a trailing-whitespace edit of the same failing query', async () => {- apiGet.mockImplementation((url: string) =>- url.includes('search=ab') ? Promise.reject(new Error('network error')) : emptyPaginated()- )- const tree = (q: string): JSX.Element => (- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}- onChange={jest.fn()}- searchQuery={q}- >- <MenuFilterCombobox- drillTo={TaxonomicFilterGroupType.Events}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- const { rerender } = render(tree('ab'))- await waitFor(() => expect(screen.getByTestId('menu-filter-error')).toBeInTheDocument())- expect(- captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')- ).toHaveLength(1)-- // A trailing space is a different cache key (and a different raw query tag for one- // render) but the same trimmed query — it must not read as a fresh failure.- rerender(tree('ab '))- await waitFor(() => expect(screen.getByTestId('menu-filter-error')).toBeInTheDocument())- expect(- captureMock.mock.calls.filter(([event]: [string]) => event === 'taxonomic filter fetch failed')- ).toHaveLength(1)- })-- it('dedups a synthetic selected entry against the real remote entry (no double checkmark)', async () => {- apiGet.mockResolvedValue({- results: [- { id: 5, name: 'Internal team' },- { id: 6, name: 'Power users' },- ],- count: 2,- })-- // Simulate what TaxonomicPopoverMenu builds: a synthetic entry with- // `name: String(value)` and a getValue that returns name-or-id. The- // real Cohorts group returns `cohort.id` (number) — without string- // coercion in the dedup check, both rows would render side by side.- const syntheticSelected = {- item: { id: '5', name: '5' },- group: {- type: TaxonomicFilterGroupType.Cohorts,- getName: (t: any) => t?.name,- getValue: (t: any) => t?.name ?? t?.id,- },- name: '5',- } as any-- render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]}- onChange={jest.fn()}- >- <MenuFilterCombobox- drillTo={TaxonomicFilterGroupType.Cohorts}- selectedEntry={syntheticSelected}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- await waitFor(() => {- expect(screen.getAllByText('Internal team').length).toBeGreaterThan(0)- })- const rowEls = document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]')- expect(rowEls.length).toBe(2)- // No row should be the synthetic placeholder ("5" / N/A) — the real- // cohort with id 5 must absorb the selected state.- const rowsText = Array.from(rowEls)- .map((el) => el.textContent ?? '')- .join('\n')- expect(rowsText).toContain('Internal team')- expect(rowsText).toContain('Power users')- })-- // Mirrors the synthetic entry built by `TaxonomicPopoverMenu` for an- // already-selected event value (e.g. the trends series picker reopened on- // "Pageview"). `value` is whatever the call site threads through — the raw- // event key `$pageview` or, when `filter.name` holds the label, `Pageview`.- // getValue returns name-or-id just like the adapter.- function syntheticEventSelected(value: string): MenuFilterEntry {- return {- item: { id: value, name: value } as TaxonomicDefinitionTypes,- // Deliberate partial — only the three fields the menu reads from a- // synthetic selection. Cast (as the production adapter does) rather- // than populate the full group shape. The `MenuFilterEntry` return- // type is what keeps the entry contract compiler-checked.- group: {- type: TaxonomicFilterGroupType.Events,- getName: (t) => t?.name,- getValue: (t) => t?.name ?? t?.id,- } as TaxonomicFilterGroup,- name: value,- }- }-- function renderEventsWithSelection(options: {- searchQuery?: string- selectedEntry?: MenuFilterEntry- selectedRename?: { label: string; raw: string }- }): ReturnType<typeof render> {- return render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}- onChange={jest.fn()}- searchQuery={options.searchQuery ?? ''}- >- <MenuFilterCombobox- drillTo="all"- selectedEntry={options.selectedEntry}- selectedRename={options.selectedRename}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )- }-- // The committed selection arrives as a synthetic entry whose value is- // either the raw event key (`$pageview`) or — when `ActionFilterRow` threads- // `filter.name` and that holds the display label — the friendly label- // (`Pageview`). Both must collapse onto the real endpoint row instead of- // stranding a placeholder beside it with a second checkmark and a blank- // preview.- it.each([- ['the raw key', '$pageview'],- ['the friendly label', 'Pageview'],- ])(- 'dedups the synthetic selected event against the real endpoint event when the value is %s',- async (_label, selectedValue) => {- apiGet.mockImplementation((url: string) => {- if (url.includes('event_definitions')) {- return Promise.resolve({- results: [- { id: 'def-1', name: '$pageview' },- { id: 'def-2', name: '$bot_pageview' },- ],- count: 2,- })- }- return Promise.resolve({ results: [], count: 0 })- })-- renderEventsWithSelection({- searchQuery: 'pagev',- selectedEntry: syntheticEventSelected(selectedValue),- })-- await waitFor(() => expect(rowTexts().some((t) => t.includes('$bot_pageview'))).toBe(true))- // Exactly one "Pageview" row…- const pageviewRows = rowTexts().filter((t) => t.includes('Pageview') && !t.includes('bot'))- expect(pageviewRows).toHaveLength(1)- // …and the surviving row is the real definition (carries the raw- // `$pageview` value), not the synthetic placeholder (which would render- // just the label with no raw value).- expect(pageviewRows[0]).toContain('$pageview')- // The selection resolves onto the real row so the checkmark + preview- // track it: the real row's DOM id must exist to be targeted.- expect(document.getElementById('menu-filter-row-events-$pageview')).toBeInTheDocument()- // …and the synthetic placeholder row — the one that carried the- // stray second checkmark in the bug — must not be rendered at all.- expect(document.getElementById('menu-filter-row-events-Pageview')).not.toBeInTheDocument()- // The preview pane picks up the real definition ("Sent as $pageview"),- // not the synthetic placeholder (which has no core definition and so- // renders neither a raw value nor a description).- const preview = document.querySelector('[data-slot="menu-filter-preview"]')- expect(preview?.textContent).toContain('Sent as')- expect(preview?.textContent).toContain('$pageview')- }- )-- it('labels the committed selection with the series rename, keeping the raw event key visible', async () => {- apiGet.mockImplementation((url: string) => {- if (url.includes('event_definitions')) {- return Promise.resolve({- results: [- { id: 'def-1', name: 'user signed up' },- { id: 'def-2', name: '$pageview' },- ],- count: 2,- })- }- return Promise.resolve({ results: [], count: 0 })- })-- renderEventsWithSelection({- selectedEntry: syntheticEventSelected('user signed up'),- selectedRename: { label: 'Signed up', raw: 'user signed up' },- })-- await waitFor(() => expect(rowTexts().length).toBeGreaterThan(1))- // Idle promotion floats the committed selection to the first row; its label is- // the series' rename, with the raw event key kept inline so the connection to- // the underlying event is visible.- expect(rowTexts()[0]).toContain('Signed up')- expect(rowTexts()[0]).toContain('user signed up')- })-- it('prefers an exact value match over the friendly-label heuristic when a custom event shares the label', async () => {- // A custom event literally named "Pageview" coexists with core- // "$pageview" (friendly label "Pageview"). A selection whose value is- // "Pageview" must resolve to the custom event (exact value match), not- // the core row it only label-matches — and both real rows stay (they're- // distinct definitions), with no synthetic placeholder.- apiGet.mockImplementation((url: string) => {- if (url.includes('event_definitions')) {- return Promise.resolve({- results: [- { id: 'def-core', name: '$pageview' },- { id: 'def-custom', name: 'Pageview' },- ],- count: 2,- })- }- return Promise.resolve({ results: [], count: 0 })- })-- renderEventsWithSelection({- searchQuery: 'pagev',- selectedEntry: syntheticEventSelected('Pageview'),- })-- await waitFor(() => expect(document.getElementById('menu-filter-row-events-Pageview')).toBeInTheDocument())- // Both distinct events render — the custom "Pageview" did not dedup the- // core "$pageview" away, and no synthetic placeholder was prepended.- expect(document.getElementById('menu-filter-row-events-$pageview')).toBeInTheDocument()- const rows = Array.from(document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]'))- expect(rows).toHaveLength(2)- // The persistent selected tint (`bg-(--fill-hover)`, a discrete class- // token distinct from the `data-selected:`-prefixed hover variant) lands- // on the exact-match custom event, not the label-match core row.- const customRow = document.getElementById('menu-filter-row-events-Pageview')- const coreRow = document.getElementById('menu-filter-row-events-$pageview')- expect(customRow?.classList.contains('bg-(--fill-hover)')).toBe(true)- expect(coreRow?.classList.contains('bg-(--fill-hover)')).toBe(false)- })-- it('caches the cohorts first page and filters typed queries locally (no per-keystroke refetch)', async () => {- // Track every cohorts request — there must be exactly one even after- // typing, because client-side fuse takes over after the first page.- let cohortCalls = 0- apiGet.mockImplementation((url: string) => {- if (url.includes('/cohorts/')) {- cohortCalls += 1- return Promise.resolve({- results: [- { id: 1, name: 'Internal team' },- { id: 2, name: 'Power users' },- { id: 3, name: 'Zzzbeta cohort' },- ],- count: 3,- })- }- return Promise.resolve({ results: [], count: 0 })- })-- // Wrap in a stateful host so we can change the controlled- // searchQuery without remounting the Root (a remount would reset- // kea state and force a fresh request even with the cache fix).- let setQuery!: (q: string) => void- function Host(): JSX.Element {- const [q, setQ] = useState('')- setQuery = setQ- return (- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]}- onChange={jest.fn()}- searchQuery={q}- >- <MenuFilterCombobox- drillTo={TaxonomicFilterGroupType.Cohorts}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )- }-- render(<Host />)-- await waitFor(() => expect(cohortCalls).toBe(1))- // Initial render shows all three items.- await waitFor(() => expect(screen.getAllByText('Zzzbeta cohort').length).toBeGreaterThan(0))-- // Now "type" a query — fuse should filter the cached page in place.- act(() => setQuery('zzzbeta'))-- await waitFor(() => {- const rowsText = Array.from(document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]'))- .map((el) => el.textContent ?? '')- .join('\n')- expect(rowsText).toContain('Zzzbeta cohort')- expect(rowsText).not.toContain('Internal team')- expect(rowsText).not.toContain('Power users')- })-- // The crucial assertion — no additional fetch fired for the typed query.- expect(cohortCalls).toBe(1)- })-- it('leads the "All" surface with recents then pinned, above the content rows', async () => {- apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.EventProperties],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'my_recent_event', 'Events')],- pinnedEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, 'my_pinned_prop', 'Event properties')],- })-- await waitFor(() => expect(rowTexts().some((t) => t.includes('autocapture'))).toBe(true))- const rows = rowTexts()- // Fixed, learnable order: recent first, pinned second, content after.- expect(rows[0]).toContain('my_recent_event')- expect(rows[1]).toContain('my_pinned_prop')- const recentIdx = rows.findIndex((t) => t.includes('my_recent_event'))- const contentIdx = rows.findIndex((t) => t.includes('autocapture'))- expect(contentIdx).toBeGreaterThan(recentIdx)- })-- it("promotes the context event's primary property after recents, above the content rows", async () => {- apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.EventProperties],- eventNames: ['$mcp_tool_call'],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'my_recent_event', 'Events')],- })-- await waitFor(() => expect(rowTexts().some((t) => t.includes('autocapture'))).toBe(true))- const rows = rowTexts()- expect(rows[0]).toContain('my_recent_event')- expect(rows[1]).toContain('MCP tool name')- const contentIdx = rows.findIndex((t) => t.includes('autocapture'))- expect(contentIdx).toBeGreaterThan(1)- })-- it('shows a promoted property that is also a recent only once, under recents', async () => {- apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.EventProperties],- eventNames: ['$mcp_tool_call'],- recentEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, '$mcp_tool_name', 'Event properties')],- })-- await waitFor(() => expect(rowTexts().some((t) => t.includes('autocapture'))).toBe(true))- const promotedRows = rowTexts().filter((t) => t.includes('MCP tool name') || t.includes('$mcp_tool_name'))- expect(promotedRows).toHaveLength(1)- })-- it('shows a recent that is also in the catalog only once (deduped from content)', async () => {- apiGet.mockResolvedValue({ results: [{ id: 1, name: 'pageview' }], count: 1 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'pageview', 'Events')],- })-- await waitFor(() => expect(screen.getAllByText('pageview').length).toBeGreaterThan(0))- const pageviewRows = rowTexts().filter((t) => t.includes('pageview'))- expect(pageviewRows).toHaveLength(1)- })-- it('shows a complete recent as both a full value row and a separate bare key row', async () => {- renderAll({- groupTypes: [TaxonomicFilterGroupType.EventProperties],- recentEntries: [- {- ...makeEntry(TaxonomicFilterGroupType.EventProperties, '$browser', 'Event properties'),- recentPropertyFilter: { key: '$browser', operator: 'exact', value: 'Chrome' },- recentLabel: 'Browser = Chrome',- },- makeEntry(TaxonomicFilterGroupType.EventProperties, '$browser', 'Event properties'),- ],- })-- await waitFor(() => expect(rowTexts().length).toBeGreaterThan(0))- const texts = rowTexts()- expect(texts.some((t) => t.includes('Browser = Chrome'))).toBe(true)- expect(texts.some((t) => t.includes('$browser') && !t.includes('Chrome'))).toBe(true)- })-- it.each([- ['email', '$email'],- ['url', '$current_url'],- ['path', '$pathname'],- ])('floats the promoted property to the top of the content when searching %p', async (searchTerm, promotedName) => {- apiGet.mockImplementation((url: string) => {- if (url.includes('property_definitions')) {- // The decoy is returned first so a passing assertion can only mean- // promotion reordered the result, not the server order.- return Promise.resolve({- results: [- { id: 1, name: 'other_prop' },- { id: 2, name: promotedName },- ],- count: 2,- })- }- return Promise.resolve({ results: [], count: 0 })- })-- renderAll({ groupTypes: [TaxonomicFilterGroupType.EventProperties], searchQuery: searchTerm })-- await waitFor(() => expect(screen.getByText('other_prop')).toBeInTheDocument())- const rows = rowTexts()- const promotedIdx = rows.findIndex((t) => t.includes(promotedName))- const otherIdx = rows.findIndex((t) => t.includes('other_prop'))- expect(promotedIdx).toBeGreaterThanOrEqual(0)- 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.each([- { kind: 'a plain word', query: 'checkout', offersRow: false },- { kind: 'a path', query: '/checkout', offersRow: true },- ])('offers the URL contains row for $kind only when it looks like a URL', async ({ query, offersRow }) => {- mockUrlValues(['https://app.posthog.com/checkout'])-- renderAll({ groupTypes: [TaxonomicFilterGroupType.PageviewUrls], searchQuery: query })-- await waitFor(() =>- expect(apiGet.mock.calls.some(([url]: unknown[]) => String(url).includes('events/values'))).toBe(true)- )- await waitFor(() => expect(screen.queryByTestId('menu-filter-loading')).not.toBeInTheDocument())- expect(rowTexts().some((t) => t.includes(`URL contains "${query}"`))).toBe(offersRow)- })-- 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.each([- { groupType: TaxonomicFilterGroupType.PageviewUrls, name: 'Pageview URLs' },- { groupType: TaxonomicFilterGroupType.EmailAddresses, name: 'Email addresses' },- { groupType: TaxonomicFilterGroupType.AutocaptureEvents, name: 'Autocapture events' },- ])('does not offer $name as a navigable category', async ({ groupType, name }) => {- const user = userEvent.setup()- mockUrlValues(['https://app.posthog.com/checkout'])-- renderAll({- groupTypes: [- TaxonomicFilterGroupType.EventProperties,- TaxonomicFilterGroupType.PersonProperties,- groupType,- ],- })-- await user.click(screen.getByLabelText('Filter category'))- const popup = within(await openedCategoryPopup())- expect(popup.getByText('Person properties')).toBeInTheDocument()- expect(popup.queryByText(name)).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 })- }- if (url.includes('events/values')) {- return Promise.resolve([])- }- // Paginated floor for everything else (dashboardsModel & co load on mount)- return Promise.resolve({ results: [], count: 0 })- })- // 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.getByLabelText('Filter category')).toHaveTextContent('All')- // The committed selection stays reachable via the selected-entry prepend.- expect(rowTexts().some((t) => t.includes('checkout'))).toBe(true)- })- })-- // Spec for the insight series picker (e.g. funnel steps include Pageview events):- // opening the menu shows "All" with event-context recents/pinned; searching a term- // that matches pageview URLs surfaces ONE "url contains <query>" shortcut as the very- // first row — ahead of recents, pinned, and event rows. These fail today because the- // series (PageviewEvents) group is not collapsed and the shortcut never leads the list.- describe('pageview url-contains shortcut leads the series picker All surface', () => {- 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('defaults to the All scope with event-context recents and pinned shown', async () => {- mockUrlValues([])- renderAll({- groupTypes: [TaxonomicFilterGroupType.PageviewEvents, TaxonomicFilterGroupType.Events],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'recent_signup', 'Events')],- pinnedEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'pinned_purchase', 'Events')],- })-- await waitFor(() => expect(rowTexts().some((t) => t.includes('recent_signup'))).toBe(true))- expect(rowTexts().some((t) => t.includes('pinned_purchase'))).toBe(true)- expect(screen.getByLabelText('Filter category')).toHaveTextContent('All')- })-- it('opens focused on All, not the selected item category, when an event is already selected', async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })- // Reopening the series picker on an existing `$pageview` selection: the menu- // should land on the "All" scope, not jump to the Events category.- const selectedEntry = makeEntry(TaxonomicFilterGroupType.Events, '$pageview', 'Events')- render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]}- onChange={jest.fn()}- >- <MenuFilterCombobox- drillTo="all"- selectedEntry={selectedEntry}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- const category = await screen.findByLabelText('Filter category')- // Wait for the Select to paint its active-category label before asserting.- await waitFor(() => expect(category.textContent || '').toMatch(/All|Events/))- expect(category).toHaveTextContent('All')- expect(category).not.toHaveTextContent('Events')- })-- it('leads with the committed selection as the first row when idle (no search)', async () => {- apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })- // Reopening on an existing selection: the user often just wants to check what's- // chosen, so the committed value is the first row even ahead of recents.- const selectedEntry = makeEntry(TaxonomicFilterGroupType.Events, 'my_current_event', 'Events')- render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}- onChange={jest.fn()}- >- <MenuFilterCombobox- drillTo="all"- selectedEntry={selectedEntry}- recentEntries={[makeEntry(TaxonomicFilterGroupType.Events, 'recent_event', 'Events')]}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- await waitFor(() => expect(rowTexts().some((t) => t.includes('my_current_event'))).toBe(true))- expect(rowTexts()[0]).toContain('my_current_event')- })-- it('puts the "url contains <query>" shortcut first, then recent, then pinned', async () => {- mockUrlValues(['https://app.posthog.com/replay', 'https://app.posthog.com/replay/home'])- renderAll({- groupTypes: [TaxonomicFilterGroupType.PageviewEvents, TaxonomicFilterGroupType.Events],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'replay_recent', 'Events')],- pinnedEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'replay_pinned', 'Events')],- searchQuery: 'replay',- })-- // Wait on a stable post-search signal (a matching recent) so the ordering- // assertions fail fast rather than timing out waiting for a row that never renders.- await waitFor(() => expect(rowTexts().some((t) => t.includes('replay_recent'))).toBe(true))- const rows = rowTexts()- const shortcutIdx = rows.findIndex((t) => /contains/i.test(t) && /replay/i.test(t))- const recentIdx = rows.findIndex((t) => t.includes('replay_recent'))- const pinnedIdx = rows.findIndex((t) => t.includes('replay_pinned'))-- // The contains shortcut leads the whole list, ahead of recents/pinned/events.- expect(shortcutIdx).toBe(0)- // Assert both rows are actually present (findIndex returns -1 when absent) so a- // regression that drops the recent/pinned row fails loudly, not on index arithmetic.- expect(recentIdx).toBeGreaterThan(0)- expect(pinnedIdx).toBeGreaterThan(recentIdx)- // and the raw matched URLs are collapsed away into the single shortcut.- expect(rows.some((t) => t.includes('https://app.posthog.com/replay'))).toBe(false)- })- })-- it('drops the recents/pinned prefix once the query no longer matches them', async () => {- apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'my_recent_event', 'Events')],- searchQuery: 'zzz_no_match',- })-- await waitFor(() => expect(screen.getAllByText('autocapture').length).toBeGreaterThan(0))- // The recent does not match the query, so it must not lead the list.- expect(screen.queryByText('my_recent_event')).not.toBeInTheDocument()- })-- it.each(['Recent', 'Pinned'])(- 'filters %s rows in All 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('All'))-- 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 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'my_recent_event', 'Events')],- pinnedEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, 'my_pinned_prop', 'Event properties')],- })-- await waitFor(() => expect(rowTexts().some((t) => t.includes('autocapture'))).toBe(true))- const rows = rowTexts()- // Recency shows as a right-side badge ("Recent" / "Pinned"); the source- // group still reads as the row's category label.- const recentRow = rows.find((t) => t.includes('my_recent_event'))- const pinnedRow = rows.find((t) => t.includes('my_pinned_prop'))- expect(recentRow).toContain('Recent')- expect(recentRow).toContain('Events')- expect(pinnedRow).toContain('Pinned')- expect(pinnedRow).toContain('Event properties')- })-- it('renders the tag a group supplies, from the row it is handed', async () => {- // The classic list renders `getTag`, so a group relying on it to mark a row (a cohort that- // feature flags cannot target yet) would silently lose that mark in this menu. The tag has- // to come off the item, not the group: a recent is stored stripped to its name and id, so- // the cohort group's `getTag` gets a record with no readiness on it and renders nothing.- const tagged = makeEntry(TaxonomicFilterGroupType.Events, 'my_tagged_event', 'Events')- tagged.item.tagLabel = 'Preparing'- const stripped = makeEntry(TaxonomicFilterGroupType.Events, 'my_stripped_event', 'Events')- const getTag = (item: any): JSX.Element | null => (item?.tagLabel ? <span>{item.tagLabel}</span> : null)- tagged.group.getTag = getTag- stripped.group.getTag = getTag-- renderAll({ groupTypes: [TaxonomicFilterGroupType.Events], recentEntries: [tagged, stripped] })-- await waitFor(() => expect(rowTexts().some((t) => t.includes('my_tagged_event'))).toBe(true))- expect(rowTexts().find((t) => t.includes('my_tagged_event'))).toContain('Preparing')- expect(rowTexts().find((t) => t.includes('my_stripped_event'))).not.toContain('Preparing')- })-- it('recent leads the list at row 0 even when content also matches the search query', async () => {- // Endpoint returns a row that matches the same query as the recent.- apiGet.mockImplementation((url: string) => {- if (url.includes('event_definitions') || url.includes('property_definitions')) {- return Promise.resolve({- results: [{ id: 1, name: 'signup' }],- count: 1,- })- }- return Promise.resolve({ results: [], count: 0 })- })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'signup', 'Events')],- searchQuery: 'signup',- })-- await waitFor(() => expect(rowTexts().some((t) => t.includes('signup'))).toBe(true))- // The recent prefix must still be at index 0 — it leads even when- // the content list also matches the query.- expect(rowTexts()[0]).toContain('signup')- })-- it.each([- [TaxonomicFilterGroupType.EmailAddresses, 'Search for an email address or domain.'],- [TaxonomicFilterGroupType.PageviewUrls, 'Search for a URL, domain, or path.'],- [TaxonomicFilterGroupType.PageviewEvents, 'Search for a URL, domain, or path.'],- ])('explains a skipped value search in %s', async (groupType, hint) => {- featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TAXONOMIC_FILTER_VALUE_SEARCH_GATING]: true })- renderAll({ groupTypes: [groupType], searchQuery: 'sample', drillTo: groupType })- expect(await screen.findByText(hint)).toBeInTheDocument()- expect(- apiGet.mock.calls.filter(- ([url]: string[]) => url.includes('/events/values') || url.includes('/persons/values')- )- ).toHaveLength(0)- expect(captureMock).not.toHaveBeenCalledWith('taxonomic filter empty result', expect.anything())- })-- it('keeps recents and pins in All without separate category options', async () => {- const user = userEvent.setup()- apiGet.mockResolvedValue({ results: [], count: 0 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'recent_choice', 'Events')],- pinnedEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, 'pinned_choice', 'Event properties')],- })-- await user.click(screen.getByLabelText('Filter category'))- const popup = await openedCategoryPopup()- expect(within(popup).queryByText('Recent')).not.toBeInTheDocument()- expect(within(popup).queryByText('Pinned')).not.toBeInTheDocument()- expect(rowTexts().some((text) => text.includes('recent_choice'))).toBe(true)- expect(rowTexts().some((text) => text.includes('pinned_choice'))).toBe(true)- })-- it('forwards row selection context on commit and does not emit the legacy event itself', async () => {- const user = userEvent.setup()- apiGet.mockResolvedValue({ results: [], count: 0 })- const onCommit = jest.fn()-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events],- recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'pageview', 'Events')],- onCommit,- })-- await waitFor(() => expect(document.querySelector('[data-slot="taxonomic-filter-menu-row"]')).toBeTruthy())- await user.click(document.querySelector('[data-slot="taxonomic-filter-menu-row"]') as HTMLElement)-- expect(onCommit).toHaveBeenCalledWith(- expect.objectContaining({ group: expect.objectContaining({ type: TaxonomicFilterGroupType.Events }) }),- undefined,- // groupType is undefined for the 'all' meta scope; the final-commit funnel- // (TaxonomicFilterMenu) turns this context into the legacy event.- {- groupType: undefined,- position: 0,- wasFromRecents: true,- wasFromPinnedList: false,- }- )- // The combobox no longer fires the legacy event on row click — that moved to- // the final-commit funnel so cancelable DWH table picks are not counted.- expect(captureMock).not.toHaveBeenCalledWith('taxonomic filter item selected', expect.anything())- })-- it('forwards wasFromPinnedList=true in the commit context for a pinned row', async () => {- const user = userEvent.setup()- apiGet.mockResolvedValue({ results: [], count: 0 })- const onCommit = jest.fn()-- renderAll({- groupTypes: [TaxonomicFilterGroupType.EventProperties],- pinnedEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, 'plan', 'Event properties')],- onCommit,- })-- await waitFor(() => expect(document.querySelector('[data-slot="taxonomic-filter-menu-row"]')).toBeTruthy())- await user.click(document.querySelector('[data-slot="taxonomic-filter-menu-row"]') as HTMLElement)-- expect(onCommit).toHaveBeenCalledWith(- expect.anything(),- undefined,- expect.objectContaining({ wasFromPinnedList: true, wasFromRecents: false })- )- })-- it('captures debounced `taxonomic_filter_search_query` for a typed query', async () => {- // Fake timers only here — the rest of the suite drives real async via- // userEvent/waitFor. Scoped so advancing the debounce is deterministic and- // instant instead of blocking on a real 500 ms timeout.- jest.useFakeTimers()- try {- apiGet.mockResolvedValue({ results: [], count: 0 })-- renderAll({ groupTypes: [TaxonomicFilterGroupType.Events], searchQuery: 'pageview' })-- await act(async () => {- // Flush the data-fetch microtasks the debounce effect rides behind…- await Promise.resolve()- // …then fire the debounce timer.- jest.advanceTimersByTime(SEARCH_QUERY_DEBOUNCE_MS)- })-- expect(captureMock).toHaveBeenCalledWith(- 'taxonomic_filter_search_query',- expect.objectContaining({- surface: 'rebuild-menu',- searchQuery: 'pageview',- inputMode: 'typed',- pastedFraction: 0,- // Stale events hidden by default → excludeStale reads true at search time.- excludeStale: true,- })- )- } finally {- jest.useRealTimers()- }- })-- it('captures `taxonomic filter empty result` for a no-match search', async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })-- renderAll({ groupTypes: [TaxonomicFilterGroupType.Events], searchQuery: 'zzz_no_match' })-- await waitFor(() =>- expect(captureMock).toHaveBeenCalledWith(- 'taxonomic filter empty result',- expect.objectContaining({ searchQuery: 'zzz_no_match', scope: 'all' })- )- )- })-- it('fires `taxonomic filter empty result` exactly once per scope+query (dedup)', async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })-- renderAll({ groupTypes: [TaxonomicFilterGroupType.Events], searchQuery: 'zzz_no_match' })-- await waitFor(() =>- expect(captureMock).toHaveBeenCalledWith(- 'taxonomic filter empty result',- expect.objectContaining({ searchQuery: 'zzz_no_match' })- )- )-- const emptyResultCalls = captureMock.mock.calls.filter(- ([event, props]: [string, any]) =>- event === 'taxonomic filter empty result' && props?.searchQuery === 'zzz_no_match'- )- expect(emptyResultCalls).toHaveLength(1)- })-- it('re-fires empty result for a query revisited after a different one (last-key dedup, matches legacy)', async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })- const emptyFor = (q: string): number =>- captureMock.mock.calls.filter(- ([event, props]: [string, any]) => event === 'taxonomic filter empty result' && props?.searchQuery === q- ).length- const tree = (q: string): JSX.Element => (- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}- onChange={jest.fn()}- searchQuery={q}- >- <MenuFilterCombobox drillTo="all" onCommit={jest.fn()} onBack={jest.fn()} />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- const { rerender } = render(tree('aaa'))- await waitFor(() => expect(emptyFor('aaa')).toBe(1))-- rerender(tree('bbb'))- await waitFor(() => expect(emptyFor('bbb')).toBe(1))-- // Returning to "aaa" re-fires — an unbounded set would have suppressed it.- rerender(tree('aaa'))- await waitFor(() => expect(emptyFor('aaa')).toBe(2))- })-- it('hides stale events by default and refetches including them when the empty-state button is clicked', async () => {- const user = userEvent.setup()- apiGet.mockResolvedValue({ results: [], count: 0 })-- render(- <Provider>- <TaxonomicFilterHeadless.Root- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}- onChange={jest.fn()}- searchQuery="zzz_no_match"- >- <MenuFilterCombobox- drillTo={TaxonomicFilterGroupType.Events}- onCommit={jest.fn()}- onBack={jest.fn()}- />- </TaxonomicFilterHeadless.Root>- </Provider>- )-- // Default: the events fetch hides stale definitions.- await waitFor(() =>- expect(apiGet.mock.calls.some(([url]: [string]) => url.includes('exclude_stale=true'))).toBe(true)- )-- const callsBeforeOptIn = apiGet.mock.calls.length- await user.click(await screen.findByText('Include stale events'))-- // Opting in emits the legacy toggle event…- expect(captureMock).toHaveBeenCalledWith(- 'taxonomic filter include stale toggled',- expect.objectContaining({ surface: 'rebuild-menu', includeStaleEvents: true })- )-- // …and refetches the events list without the stale exclusion.- await waitFor(() => {- const newUrls: string[] = apiGet.mock.calls.slice(callsBeforeOptIn).map(([url]: [string]) => url)- expect(newUrls.length).toBeGreaterThan(0)- expect(newUrls.every((url: string) => !url.includes('exclude_stale=true'))).toBe(true)- })- })-- it('offers a jump to All when a single category comes up empty, and clicking it switches scope', async () => {- const user = userEvent.setup()- apiGet.mockResolvedValue({ results: [], count: 0 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Cohorts, TaxonomicFilterGroupType.Events],- searchQuery: 'zzz_no_match',- })-- // Narrow to a single category so the cross-category jump becomes relevant- await user.click(screen.getByLabelText('Filter category'))- await user.click(await within(await openedCategoryPopup()).findByText('Cohorts'))-- const jumpButton = await screen.findByText('Check for results in other categories')- await user.click(jumpButton)-- expect(captureMock).toHaveBeenCalledWith(- 'taxonomic filter menu category changed',- expect.objectContaining({ toChip: 'all', via: 'empty-state' })- )- // Back on the All scope, the jump no longer applies- await waitFor(() => {- expect(screen.getByLabelText('Filter category')).toHaveTextContent('All')- expect(screen.queryByText('Check for results in other categories')).not.toBeInTheDocument()- })- })-- it('does not offer the jump on the All scope', async () => {- apiGet.mockResolvedValue({ results: [], count: 0 })-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Cohorts, TaxonomicFilterGroupType.Events],- searchQuery: 'zzz_no_match',- })-- await waitFor(() => expect(screen.getByTestId('menu-filter-empty')).toBeInTheDocument())- expect(screen.queryByText('Check for results in other categories')).not.toBeInTheDocument()- })-- // Parity with the legacy picker, whose half lives in TaxonomicFilter.test.tsx. Nothing enforces- // that the two agree, so the same rule is asserted on both.- describe('an event hidden because its data is moving', () => {- beforeEach(() => {- apiGet.mockResolvedValue({ results: [], count: 0 })- setFlagEvaluationsMode(FlagEvaluationsModeEnumApi.Number1)- })-- afterEach(() => {- jest.restoreAllMocks()- localStorage.clear()- })-- it.each([- ['links the announcement', true, ANNOUNCEMENT_URL, ANNOUNCEMENT_URL],- [- 'links the announcement when its URL has leading whitespace',- true,- ` ${ANNOUNCEMENT_URL}`,- ANNOUNCEMENT_URL,- ],- ['has no link while the announcement has no URL', true, null, undefined],- ['has no link while the move notices are off', false, ANNOUNCEMENT_URL, undefined],- ])(- 'explains the absence, drops recovery buttons that cannot recover it, and %s',- async (_label, moveNoticesOn, url, expectedHref) => {- setMoveNotices(moveNoticesOn, url)- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events],- searchQuery: '$feature_flag_called',- })-- const empty = await waitFor(() => screen.getByTestId('menu-filter-empty'))- expect(within(empty).getByText(/\$feature_flag_called isn't available here/)).toBeInTheDocument()- expect(screen.queryByTestId('menu-filter-include-stale-events')).not.toBeInTheDocument()- expect(screen.queryByTestId('menu-filter-check-other-categories')).not.toBeInTheDocument()- const link = within(empty).queryByTestId('taxonomic-hidden-event-announcement')- expect(link?.getAttribute('href')).toBe(expectedHref)- }- )-- it('reports no matches as usual for a team on the Events mode', async () => {- setFlagEvaluationsMode(FlagEvaluationsModeEnumApi.Number0)-- renderAll({- groupTypes: [TaxonomicFilterGroupType.Events],- searchQuery: '$feature_flag_called',- })-- const empty = await waitFor(() => screen.getByTestId('menu-filter-empty'))- expect(within(empty).queryByText(/isn't available here/)).not.toBeInTheDocument()- })- })-- 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'])('keeps %s available in All without skeletons during a 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('All'))- 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- 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.getByText('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.tsxdeleted file mode 100644index 6073a44c6562..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx+++ /dev/null@@ -1,1636 +0,0 @@-/**- * Combobox panel — search input + (optional) category chips + result list.- *- * Drives the popover when the user picks "New filter…", "Recent",- * "Pinned", or any specific group. When `drillTo` is set, chips are- * hidden and the list is locked to that drill scope. Search filters- * within the active scope only.- *- * Built on `@base-ui/react/autocomplete` for keyboard navigation +- * `aria-activedescendant` plumbing. Single-cell rows. Click or Enter to- * commit. Esc → onBack.- */-import { Autocomplete } from '@base-ui/react/autocomplete'-import { useValues } from 'kea'-import posthog from 'posthog-js'-import { MutableRefObject, ReactElement, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'--import { IconCheck, IconChevronRight, IconClock, IconPinFilled, IconWarning } from '@posthog/icons'-import {- Badge,- Button,- cn,- InputGroup,- InputGroupAddon,- InputGroupInput,- MenuLabel,- ScrollArea,- Select,- SelectContent,- SelectGroup,- SelectItem,- SelectTrigger,- SelectValue,- Separator,- Skeleton,-} from '@posthog/quill'--import type { SeriesRename } from 'lib/components/EntityFilterInfo'-import { LemonInput } from 'lib/lemon-ui/LemonInput'-import { createFuse } from 'lib/utils/fuseSearch'-import { surveyQuestionLabelsLogic } from 'scenes/surveys/surveyQuestionLabelsLogic'--import { getCoreFilterDefinition } from '~/taxonomy/helpers'--import { useTaxonomicFilterContext } from '../headless/context'-import { HiddenEventExplanation } from '../HiddenEventExplanation'-import { useGroupList } from '../hooks/useGroupList'-import {- OPEN_AS_SELF_ON_REOPEN,- META_GROUP_TYPES,- TaxonomicDefinitionTypes,- TaxonomicFilterGroup,- TaxonomicFilterGroupType,- withoutSearchOnlyGroups,-} from '../types'-import {- COLLAPSED_TO_CONTAINS_ROW,- offersUrlContainsRow,- partitionContainsShortcuts,- urlContainsRowLabel,-} from '../utils/collapsedContainsRow'-import { floatToFront } from '../utils/floatToFront'-import { hiddenEventMatchingSearch } from '../utils/hiddenEvents'-import { promoteMatchingBy } from '../utils/promoteProperties'-import { MenuFilterHeader } from './Header'-import { MatchedValueBadge } from './MatchedValueBadge'-import { PreviewPane } from './PreviewPane'-import { CommitFn, CommitSelectionContext, DrillCategory, MenuFilterEntry, TAXONOMIC_FILTER_SURFACE } from './types'-import { VerificationBadge } from './VerificationBadge'--// `threshold` + `ignoreDiacritics` come from `createFuse` defaults; we-// only override what's specific to the menu (keys + the-// `ignoreLocation` switch so a typo near the end of the string still-// matches).-const FUSE_OPTIONS = {- keys: ['name', 'friendlyLabel', 'recentLabel'],- ignoreLocation: true,-}--/** Categories filtered out of the chip row when drillTo === 'all'. */-const HIDDEN_FROM_CHIPS: ReadonlySet<TaxonomicFilterGroupType> = new Set([- // `SuggestedFilters` is a tiny set of primary-property promotions for the- // *currently-selected event* + autocapture text/selector. It's empty for- // almost every flow without an event-in-context, so it doesn't earn a chip- // — its options surface via `suggestedPrefix` on the idle "All" list- // instead, right after recents/pinned.- TaxonomicFilterGroupType.SuggestedFilters,- // RecentFilters / PinnedFilters surface via the dropdown menu- // (Recent / Pinned entries with chevrons) and lead the "All" surface;- // DataWarehouse + HogQL expression have their own dedicated panels —- // none of them belong in the in-combobox chip row.- TaxonomicFilterGroupType.RecentFilters,- TaxonomicFilterGroupType.PinnedFilters,- TaxonomicFilterGroupType.DataWarehouse,- TaxonomicFilterGroupType.HogQLExpression,-])--/** 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--/** An entry's canonical value — what the dedup key, the DOM id, and the- * selection match all key off. They MUST agree (a row keyed one way but- * matched another is the bug class this file guards against), so they share- * this single derivation rather than repeating it. */-function entryValue(entry: MenuFilterEntry): string {- return String(entry.canonicalValue ?? entry.group.getValue?.(entry.item) ?? entry.name)-}--/** Identity for an entry's underlying definition — source group + value.- * Uses `::` as separator to serve as a dedup key (distinct from DOM ids). */-function entryKey(entry: MenuFilterEntry): string {- return `${entry.group.type}::${entryValue(entry)}${entry.recentPropertyFilter ? '::full' : ''}`-}--/** Stable DOM id for a menu row — used for scroll-into-view, checkmark- * lookups, and `aria-activedescendant`. The format must be identical- * everywhere it is constructed. */-function rowDomId(entry: MenuFilterEntry): string {- return `menu-filter-row-${entry.group.type}-${entryValue(entry)}${entry.recentPropertyFilter ? '-full' : ''}`-}--/** Exact match: the entry's canonical value equals the selection's. This is the- * authoritative match — when it holds, the two are the same definition. */-function entryValueMatchesSelection(entry: MenuFilterEntry, selected: MenuFilterEntry): boolean {- return entry.group.type === selected.group.type && entryValue(entry) === entryValue(selected)-}--/** Heuristic match: the selection's stored value equals the entry's raw name or- * resolved friendly label. `ActionFilterRow` threads `filter.name`, which can- * be the friendly label (`Pageview`) rather than the raw key (`$pageview`), so- * a synthetic entry built from the label won't match the real row on value- * alone — this bridges that gap. Looser than the value match: a custom event- * literally named `Pageview` would label-match the core `$pageview` row, so- * callers must prefer `entryValueMatchesSelection` first (see `selectedRowId`). */-function entryLabelMatchesSelection(entry: MenuFilterEntry, selected: MenuFilterEntry): boolean {- if (entry.group.type !== selected.group.type) {- return false- }- const target = entryValue(selected)- return entry.name === target || (entry.friendlyLabel != null && entry.friendlyLabel === target)-}--/** Either kind of match — used for dedup, where any real row representing the- * selection means we must not also prepend a synthetic placeholder. */-function entryMatchesSelection(entry: MenuFilterEntry, selected: MenuFilterEntry): boolean {- return entryValueMatchesSelection(entry, selected) || entryLabelMatchesSelection(entry, selected)-}--function fuseMatchEntries(entries: MenuFilterEntry[], query: string): MenuFilterEntry[] {- if (entries.length === 0) {- return []- }- return createFuse(entries, FUSE_OPTIONS as Parameters<typeof createFuse<MenuFilterEntry>>[1])- .search(query)- .map((r) => r.item)-}--export interface MenuFilterComboboxProps {- drillTo: DrillCategory- /** Pre-resolved entries for `drillTo='recent' | 'pinned'`. Skips fetching. */- drillItems?: MenuFilterEntry[]- /** Recents/pinned (each resolved to its source group). Lead the default- * "All" surface: top-3 of each when idle, query matches when searching. */- recentEntries?: MenuFilterEntry[]- pinnedEntries?: MenuFilterEntry[]- placeholder?: string- onCommit: CommitFn- onBack: () => void- /** Title shown in the header. Defaults to drill category name. */- title?: string- /** Currently-committed selection — rendered with a checkmark + scrolled into view. */- selectedEntry?: MenuFilterEntry | null- /** Rename (custom name) carried by the series being edited — applied to the selected row. */- selectedRename?: SeriesRename | null- /** Shared ref to the search input so the popover can target it for focus.- * Mutable because the adapter assigns the input element onto it. */- inputRef?: MutableRefObject<HTMLInputElement | null>- /**- * Filter-icon menu button shown as the field's prefix in input-trigger- * mode (where the field is a `LemonInput` in the trigger row). Omitted in- * the popover/button mode, which renders the field as a quill input.- */- iconButton?: ReactElement-}--export function MenuFilterCombobox({- drillTo,- drillItems,- recentEntries,- pinnedEntries,- placeholder,- onCommit,- onBack,- title,- selectedEntry,- selectedRename,- inputRef: externalInputRef,- iconButton,-}: MenuFilterComboboxProps): JSX.Element {- // Sync our local query to the orchestrator's so remote-endpoint groups- // (Pageview URLs, Screens, etc.) actually fetch — `useGroupList` reads- // `searchQuery` from the orchestrator's `getGroupListInput`, not from- // us. Keeping a local mirror just for the controlled input ergonomics.- const { groups, searchQuery, setSearchQuery } = useTaxonomicFilterContext()- // Open on the drill scope ("All" for the default surface). Reopening with a committed- // selection used to jump to that item's category; we now lead with "All" so the user- // lands on recents/pinned + a cross-category search (the selection still surfaces via- // the selected-entry prepend). The exception is config/edit flows (data-warehouse- // columns reach the combobox as DataWarehouseProperties) — they reopen on their own- // chip so the user can reconfigure, mirroring the legacy `activeTab`.- const [activeChip, setActiveChip] = useState<DrillCategory>(() =>- drillTo === 'all' && selectedEntry && OPEN_AS_SELF_ON_REOPEN.has(selectedEntry.group.type)- ? selectedEntry.group.type- : drillTo- )- // The scope the user is actually looking at: the active chip when chips show- // (drillTo='all'), otherwise the drilled-to category. Single source for the- // telemetry group type, empty state, stale-toggle gating, and reset trigger.- const activeScope: DrillCategory = drillTo === 'all' ? activeChip : drillTo- const [itemsByType, setItemsByType] = useState<Record<string, TaxonomicDefinitionTypes[]>>({})- // Per-group loading flags reported up by `Fetcher`. We need this in the- // parent so the empty-state vs. skeleton decision sees the freshest- // 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, { query?: string; fetching: boolean }>>({})- // Per-group "failed with nothing to fall back on" flag, reported by `Fetcher`, tagged with- // the query it belongs to. Drives the error state (instead of "No results") and gates which- // groups `handleRetry` re-fetches. The query tag matters because a group reports its error- // asynchronously: typing a new query can change `searchQuery` before the previous query's- // failed report clears, and an error reported for a stale query must not read as a failure- // of the current one.- const [errorByType, setErrorByType] = useState<Record<string, { query?: string; hasError: boolean }>>({})- // Latest retry function per group, kept out of state since identity changes every render- // and it's only read imperatively from `handleRetry`.- const retryFnsRef = useRef<Record<string, () => Promise<unknown>>>({})- const [retrying, setRetrying] = useState(false)- // 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- // stale/partial list and rows don't jump around. Mirrors `revealBarrierOpen`.- // Start closed when mounting already searching (e.g. a drilled-in query- // preserved across reopen); otherwise recents/pinned, which render from- // props with no fetch involved, paint immediately while the async groups- // 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- // `filtered` (selected entry promoted to index 0) keeps the- // highlight on the same row.- const [highlightedEntry, setHighlightedEntry] = useState<MenuFilterEntry | null>(selectedEntry ?? null)- const localInputRef = useRef<HTMLInputElement | null>(null)- const inputRef = externalInputRef ?? localInputRef-- // Stale events (event definitions not ingested within the staleness window)- // are hidden by default to match the legacy picker. The opt-in is per-search:- // reset whenever the query or active scope changes so stale results never- // carry across unrelated searches (mirrors legacy `setSearchQuery`/`setActiveTab`).- const [includeStaleEvents, setIncludeStaleEvents] = useState(false)- useEffect(() => {- setIncludeStaleEvents(false)- }, [searchQuery, activeScope])- // Read inside the debounced search-query capture without re-triggering it on- // toggle (the toggle changes results, not the query).- const includeStaleEventsRef = useRef(includeStaleEvents)- useEffect(() => {- includeStaleEventsRef.current = includeStaleEvents- }, [includeStaleEvents])-- const reportItems = useCallback((type: string, next: TaxonomicDefinitionTypes[]): void => {- setItemsByType((prev) => (prev[type] === next ? prev : { ...prev, [type]: next }))- }, [])-- const reportLoading = useCallback((type: string, loading: boolean): void => {- setLoadingByType((prev) => (prev[type] === loading ? prev : { ...prev, [type]: loading }))- }, [])-- 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 } }- )- }, [])-- const reportError = useCallback(- (type: string, hasError: boolean, retry: () => Promise<unknown>, query?: string): void => {- retryFnsRef.current[type] = retry- setErrorByType((prev) =>- prev[type]?.hasError === hasError && prev[type]?.query === query- ? prev- : { ...prev, [type]: { query, hasError } }- )- },- []- )-- // Chips show only when `drillTo='all'` — drilled scopes lock to one- // category and hide the chip row per spec.- const showChips = drillTo === 'all'- const visibleChipGroups = useMemo(() => groups.filter((g) => !HIDDEN_FROM_CHIPS.has(g.type)), [groups])-- // Ordered category list — drives the category dropdown and Tab cycling- // (kept in sync so the dropdown trigger reflects the active scope).- // Recent / Pinned lead the content categories (when present) so they're- // navigable from the combobox the way the pill variant's category column- // exposes them, not only via the outer dropdown menu.- const categoryOptions = useMemo<{ value: DrillCategory; label: string }[]>(() => {- const opts: { value: DrillCategory; label: string }[] = [{ value: 'all', label: 'All' }]- const categoryGroups = withoutSearchOnlyGroups(- visibleChipGroups,- (g) => g.type,- (type) => META_GROUP_TYPES.has(type)- )- for (const g of categoryGroups) {- // 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- }, [visibleChipGroups])-- // Resolve which groups feed the visible list, based on the active chip- // (or the drill scope when chips are hidden).- const targetGroups = useMemo<TaxonomicFilterGroup[]>(() => {- if (activeScope === 'all') {- return visibleChipGroups- }- if (activeScope === 'recent' || activeScope === 'pinned') {- return [] // items come from `drillItems`- }- const g = groups.find((gr) => gr.type === activeScope)- return g ? [g] : []- }, [activeScope, groups, visibleChipGroups])-- // Mount + subscribe so `$survey_response_<question-id>` keys resolve to the- // actual question text. `getFriendlyLabel` reads through `getCoreFilterDefinition`,- // which falls back to a static label until `surveyQuestionLabelsLogic` has- // loaded. Subscribing here ensures `indexed` recomputes the labels once they- // arrive — without this, each entry's `friendlyLabel` would be frozen to the- // pre-load fallback for the lifetime of the popover.- const { surveyQuestionLabels } = useValues(surveyQuestionLabelsLogic)-- // Indexed entries — flat list across all visible groups (or- // pre-resolved `drillItems` for recent/pinned).- const indexed = useMemo<MenuFilterEntry[]>(() => {- const scope = showChips ? activeChip : drillTo- if (drillItems) {- return drillItems- }- // Recent / Pinned scopes selected from the combobox dropdown read the- // pre-resolved entries directly (the outer menu drill passes the same- // lists via `drillItems`).- if (scope === 'recent') {- return recentEntries ?? []- }- if (scope === 'pinned') {- 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 && offersUrlContainsRow(group.type, trimmedQuery) && items.length > 0) {- const label = urlContainsRowLabel(trimmedQuery)- merged.push({- // A plain item (not a QuickFilterItem): the commit reads its value via- // `group.getValue` (the query) and the group `type` drives the host's- // expansion — PageviewUrls -> `$current_url IContains`, PageviewEvents ->- // a `$pageview` event with that filter (ActionFilterRow's group-type- // branch). The legacy list reaches the same filter via the QuickFilterItem- // `eventName` path instead — see `buildUrlContainsShortcut`.- // `isContainsShortcut` tags it for commit telemetry + the lead-first ordering.- item: {- name: trimmedQuery,- isContainsShortcut: true,- } as unknown as TaxonomicDefinitionTypes,- group,- name: label,- friendlyLabel: label,- })- }- continue- }- for (const item of items) {- merged.push(buildMenuFilterEntry(item, group))- }- }- // Make sure the committed selection is reachable from the list- // even when the remote endpoint paginated past it (limit=100,- // alphabetical ordering — long-tail custom events get cut off- // and the user can't see what they previously picked). Prepend- // it if missing so it's clickable, scroll-able, and feeds the- // preview pane. Skip when the active chip filters it out- // (showing it under the wrong category would lie to the user).- if (selectedEntry) {- // `recent`/`pinned` scopes already returned above, so the only- // mixed scope left here is `all`.- const fitsScope = scope === 'all' || scope === selectedEntry.group.type- if (fitsScope) {- // `entryMatchesSelection` reconciles a synthetic `selected`- // shimmed in by callers like `TaxonomicPopoverMenu` against the- // real endpoint row — by value (`cohort.id === 5` vs `'5'`) or- // by friendly label (a value of `Pageview` vs the real- // `$pageview` row). Only prepend the placeholder when the real- // row genuinely isn't loaded (paginated past it).- const present = merged.some((e) => entryMatchesSelection(e, selectedEntry))- if (!present) {- merged.unshift(selectedEntry)- }- }- }- return merged- // `surveyQuestionLabels` is a deliberate recompute trigger: it isn't read- // directly in the body, but `getFriendlyLabel` → `getCoreFilterDefinition`- // reads its value via `findMounted()`. Without this dep the memo would- // freeze each entry's `friendlyLabel` to the pre-load fallback.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [- drillItems,- recentEntries,- pinnedEntries,- targetGroups,- itemsByType,- selectedEntry,- showChips,- activeChip,- drillTo,- searchQuery,- surveyQuestionLabels,- ])-- // Stable DOM id for the selected row — drives `Row`'s checkmark, the- // scroll-into-view below, and the `filtered` idle-promotion. Resolve the- // committed selection to the real loaded row when one matches (the stored- // value may be a friendly label, not the row's raw value), so all three- // land on the canonical row rather than a synthetic placeholder. Falls back- // to the selection itself when the real row hasn't loaded (paginated past).- const selectedRowId = useMemo<string | null>(() => {- if (!selectedEntry) {- return null- }- // Prefer an exact value match over the label heuristic so a custom event- // sharing a core event's friendly label can't steal the selection.- const real =- indexed.find((e) => entryValueMatchesSelection(e, selectedEntry)) ??- indexed.find((e) => entryLabelMatchesSelection(e, selectedEntry))- return rowDomId(real ?? selectedEntry)- }, [indexed, selectedEntry])-- // Scroll the selected row into view after the list mounts. Polls a few- // animation frames because rows render after the underlying group's- // items resolve (remote endpoints), so the element won't exist on the- // first paint. Stops as soon as the node appears or after ~10 frames.- useEffect(() => {- if (!selectedRowId) {- return- }- let cancelled = false- let attempts = 0- const tick = (): void => {- if (cancelled) {- return- }- const el = document.getElementById(selectedRowId)- if (el) {- // `center` keeps a comfortable buffer above + below the- // selected row so it never lands flush against the edge- // of the scroll viewport (where the scroll-to button or- // the scrollbar fade can obscure it).- el.scrollIntoView({ block: 'center' })- return- }- if (attempts++ < 10) {- requestAnimationFrame(tick)- }- }- tick()- return () => {- cancelled = true- }- }, [selectedRowId])-- // Recents + pinned that lead the default "All" surface (fixed order:- // recents, then pinned). Idle shows the top-3 of each; searching shows the- // query matches. Computed outside `filtered` so the endpoint-passthrough- // there can't re-introduce a non-matching endpoint-backed recent.- const recentsPinnedPrefix = useMemo<MenuFilterEntry[]>(() => {- const scope = showChips ? activeChip : drillTo- if (scope !== 'all') {- return []- }- const recents = recentEntries ?? []- const pinned = pinnedEntries ?? []- const q = searchQuery.trim()- const recentSegment = q ? fuseMatchEntries(recents, q) : recents.slice(0, RECENT_PINNED_PREFIX_LIMIT)- const recentSegmentKeys = new Set(recentSegment.map(entryKey))- const pinnedPool = (q ? fuseMatchEntries(pinned, q) : pinned).filter((e) => !recentSegmentKeys.has(entryKey(e)))- const pinnedSegment = q ? pinnedPool : pinnedPool.slice(0, RECENT_PINNED_PREFIX_LIMIT)- return [...recentSegment, ...pinnedSegment]- }, [showChips, activeChip, drillTo, recentEntries, pinnedEntries, searchQuery])-- // Promoted properties for the events in context (the SuggestedFilters- // group's options, e.g. `$pageview` -> `$pathname`, `$mcp_tool_call` ->- // `$mcp_tool_name`). The group itself is hidden from chips, but its- // options lead the idle "All" surface right after recents/pinned — the- // rebuild counterpart of the legacy Suggested tab's promotion. Deduped- // against recents/pinned so a promoted property the user already has to- // hand shows once, under the section that renders first.- const suggestedPrefix = useMemo<MenuFilterEntry[]>(() => {- const scope = showChips ? activeChip : drillTo- if (scope !== 'all' || searchQuery.trim()) {- return []- }- const suggestedGroup = groups.find((g) => g.type === TaxonomicFilterGroupType.SuggestedFilters)- const options = (suggestedGroup?.options ?? []) as { name: string; group: TaxonomicFilterGroupType }[]- const prefixKeys = new Set(recentsPinnedPrefix.map(entryKey))- const entries: MenuFilterEntry[] = []- for (const option of options) {- const realGroup = groups.find((g) => g.type === option.group)- if (!realGroup) {- continue- }- const item = { name: option.name } as unknown as TaxonomicDefinitionTypes- const entry = buildMenuFilterEntry(item, realGroup)- if (!prefixKeys.has(entryKey(entry))) {- entries.push(entry)- }- }- return entries- }, [showChips, activeChip, drillTo, searchQuery, groups, recentsPinnedPrefix])-- // Recency lookup so any row that is one of the user's recents/pinned gets a- // "- recent" / "- pinned" tag on its category label, wherever it appears- // (matching the pill variant's per-row source tags).- const recentKeys = useMemo(() => new Set((recentEntries ?? []).map(entryKey)), [recentEntries])- const pinnedKeys = useMemo(() => new Set((pinnedEntries ?? []).map(entryKey)), [pinnedEntries])- const recencyForEntry = useCallback(- (entry: MenuFilterEntry): 'recent' | 'pinned' | null => {- const key = entryKey(entry)- if (recentKeys.has(key)) {- return 'recent'- }- if (pinnedKeys.has(key)) {- return 'pinned'- }- return null- },- [recentKeys, pinnedKeys]- )-- const filtered = useMemo<MenuFilterEntry[]>(() => {- const q = searchQuery.trim()- 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- // server-side behavioral-cohort exclusion). Re-running the- // client Fuse over already-server-searched results filters them- // a *second*, fuzzier time — and Fuse scoring isn't monotonic as- // the query grows, so a valid match shown for "posthog te" can- // vanish at "posthog team". So only Fuse locally-sourced groups- // (Actions, etc., which load their full list client-side); pass- // server-searched entries through untouched, preserving order.- const localSourced = indexed.filter((e) => !e.group.endpoint)- const localMatches =- localSourced.length > 0- ? new Set(- createFuse(localSourced, FUSE_OPTIONS as Parameters<typeof createFuse<MenuFilterEntry>>[1])- .search(q)- .map((r) => r.item)- )- : null- base = indexed.filter((e) => !!e.group.endpoint || (localMatches?.has(e) ?? false))- }- const scope = showChips ? activeChip : drillTo- // Promote the committed selection to index 0 so base-ui's- // `autoHighlight="always"` lands on it the moment the list mounts — keyboard nav- // starts on the selected row, the preview shows the right definition, and `Enter`- // re-commits without scrolling. Skip while searching (relevance wins). The All scope- // re-floats after its recents/pinned assembly below, so only do it here for drilled scopes.- if (!q && selectedRowId && scope !== 'all') {- base = floatToFront(- base,- base.findIndex((e) => rowDomId(e) === selectedRowId)- )- }- // Default "All" surface leads with recents/pinned (fixed order), then- // the cross-tab content with `email`/`url` promotion. Recents/pinned- // stay above the content rows so users can learn the order.- if (scope === 'all') {- const prefixKeys = new Set([...recentsPinnedPrefix, ...suggestedPrefix].map(entryKey))- const content = prefixKeys.size > 0 ? base.filter((e) => !prefixKeys.has(entryKey(e))) : base- // The "URL contains <query>" shortcut leads the whole list — ahead of- // recents/pinned/content — because a URL search almost always means the user- // wants the contains match. Everything else keeps the recents-then-pinned order,- // with the promoted properties for the events in context leading the content.- const [shortcuts, rest] = partitionContainsShortcuts(content, (e) => e.item)- const assembled = [- ...shortcuts,- ...recentsPinnedPrefix,- ...suggestedPrefix,- ...promoteMatchingBy(rest, searchQuery, (e) => (e.item as { name?: string }).name ?? e.name),- ]- // Idle (no search): float the committed selection to the very first row so the- // user can see/verify what's currently chosen without leaving the All surface.- if (!q && selectedRowId) {- return floatToFront(- assembled,- assembled.findIndex((e) => rowDomId(e) === selectedRowId)- )- }- return assembled- }- return base- }, [- 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- // shifts between render and click.- const positionByEntry = useMemo<Map<MenuFilterEntry, number>>(() => {- const map = new Map<MenuFilterEntry, number>()- filtered.forEach((entry, position) => map.set(entry, position))- return map- }, [filtered])-- // Active-chip-aware placeholder. When the user has narrowed to a- // specific category, use that group's `searchPlaceholder` so the- // input reflects the search scope ("Search events" vs. the broad- // "Search events, actions, …").- const activePlaceholder = useMemo(() => {- if (activeChip === 'all') {- return placeholder ?? 'Search…'- }- if (activeChip === 'recent' || activeChip === 'pinned') {- return placeholder ?? 'Search…'- }- const group = groups.find((g) => g.type === activeChip)- const phrase = group?.searchPlaceholder ?? group?.name?.toLowerCase()- return phrase ? `Search ${phrase}…` : (placeholder ?? 'Search…')- }, [activeChip, groups, placeholder])-- // True while any visible group is fetching its first page (or refetching- // with no kept-previous-data) — drives the skeleton fallback so the user- // doesn't see "No X found" before the request resolves. Drilled- // scopes that read from pre-resolved `drillItems` never fetch and stay at- // `false`.- const isAnyLoading = useMemo(() => {- if (drillItems) {- return false- }- return targetGroups.some((g) => loadingByType[g.type])- }, [drillItems, targetGroups, loadingByType])-- // True when a visible group's request failed with nothing to fall back on — takes over- // from the empty state (below) so a dead backend doesn't read as "no matching results".- // Only counts a report tagged with the *current* query — a stale report for a query the- // user has already moved on from must not read as a failure of what's on screen now.- const anyError = useMemo(() => {- if (drillItems) {- return false- }- return targetGroups.some((g) => errorByType[g.type]?.hasError && errorByType[g.type]?.query === searchQuery)- }, [drillItems, targetGroups, errorByType, searchQuery])-- const handleRetry = useCallback(async (): Promise<void> => {- setRetrying(true)- try {- await Promise.all(- targetGroups- .filter((g) => errorByType[g.type]?.hasError && errorByType[g.type]?.query === searchQuery)- .map((g) => retryFnsRef.current[g.type]?.())- )- } finally {- setRetrying(false)- }- }, [targetGroups, errorByType, searchQuery])-- // ---- Reveal barrier ----------------------------------------------------- // 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 || activeScope !== barrierScope) {- setBarrierQuery(searchQuery)- setBarrierScope(activeScope)- setRevealBarrierOpen(!searching)- }- 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- }- if (!anyFetching) {- setRevealBarrierOpen(true)- }- }, [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(() => {- if (!searching) {- return- }- const id = window.setTimeout(() => setRevealBarrierOpen(true), REVEAL_BARRIER_TIMEOUT_MS)- return () => window.clearTimeout(id)- }, [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-- // Empty-state message. Three branches:- // - "needs more characters" — when the active chip resolves to a- // single group with `minSearchQueryLength` and the search query- // is shorter than that. Shows the group's `searchDescription`- // to explain what the typing will reach (matching the- // screenshot in the design).- // - "no matches" — search query is long enough but nothing- // resolved. Names the active category for context.- // - "no items" — initial render with no search and no resolved- // entries (rare for finite groups).- const emptyState = useMemo<{ title: string; body?: ReactNode } | null>(() => {- if (filtered.length > 0) {- return null- }- // Suppress empty-state copy while a remote fetch is in flight —- // the skeleton fallback below takes its place so we don't flash- // "No X found" before the response resolves.- if (isAnyLoading) {- return null- }- const singleGroup =- activeScope !== 'all' && activeScope !== 'recent' && activeScope !== 'pinned'- ? (groups.find((g) => g.type === activeScope) ?? null)- : null- const minLen = singleGroup?.minSearchQueryLength ?? 0- const trimmedLen = searchQuery.trim().length- if (singleGroup && minLen > 0 && trimmedLen < minLen) {- const description = singleGroup.searchDescription ?? singleGroup.name.toLowerCase()- return {- title: singleGroup.name,- body: `Type at least ${minLen} characters to search ${description} we have seen.`,- }- }- // `groups` is already narrowed to the tabs this filter offers, so no group-type gate is- // needed here, unlike the mirror of this branch in InfiniteList.tsx.- const hiddenEventSearched = hiddenEventMatchingSearch(- searchQuery,- groups.find((g) => g.type === TaxonomicFilterGroupType.Events)?.excludedProperties- )- if (hiddenEventSearched) {- // `body` is load-bearing, not decoration: the recovery buttons below render only when it- // is absent, and neither of them can bring back an excluded name.- return {- title: `${hiddenEventSearched} isn't available here`,- body: <HiddenEventExplanation />,- }- }- if (singleGroup?.shouldSearch?.(searchQuery) === false && singleGroup.searchQueryHint) {- return { title: singleGroup.name, body: singleGroup.searchQueryHint }- }- const categoryLabel = singleGroup?.name ?? null- if (trimmedLen > 0) {- return {- title: categoryLabel ? `No "${categoryLabel}" found` : 'No matches',- }- }- return {- title: categoryLabel ? `No "${categoryLabel}" found` : 'No items',- }- }, [filtered.length, activeScope, groups, searchQuery, isAnyLoading])-- // --- Telemetry parity ---------------------------------------------------- // Emit the legacy `taxonomic filter *` contract so the rebuild is- // comparable to the classic picker. The meta scopes- // (all/recent/pinned) have no single source group, so groupType is- // undefined there — matching how legacy reports the active content tab.- const telemetryGroupType = useMemo<TaxonomicFilterGroupType | undefined>(() => {- return activeScope === 'all' || activeScope === 'recent' || activeScope === 'pinned' ? undefined : activeScope- }, [activeScope])-- const pastedCharsRef = useRef(0)-- // `taxonomic_filter_search_query` — debounced; `inputMode`/`pastedFraction`- // distinguish typed vs pasted input. `excludeStale` mirrors legacy: stale events- // are hidden by default (so it reads true at search time, since the per-search- // opt-in resets on every query change).- useEffect(() => {- const trimmed = searchQuery.trim()- if (!trimmed) {- pastedCharsRef.current = 0- return- }- const timer = setTimeout(() => {- const pastedChars = pastedCharsRef.current- pastedCharsRef.current = 0- const totalLength = searchQuery.length- // Mirrors the legacy `taxonomicFilterLogic` classifier (kept in sync until the legacy picker is retired).- const inputMode = classifyInputMode(pastedChars, totalLength)- posthog.capture('taxonomic_filter_search_query', {- surface: TAXONOMIC_FILTER_SURFACE,- searchQuery,- groupType: telemetryGroupType,- inputMode,- pastedFraction: totalLength > 0 ? Math.min(1, pastedChars / totalLength) : 0,- excludeStale: !includeStaleEventsRef.current,- })- }, SEARCH_QUERY_DEBOUNCE_MS)- return () => clearTimeout(timer)- }, [searchQuery, telemetryGroupType])-- // `taxonomic filter empty result` — once per scope+query when a real search- // returns nothing. `emptyState.body` marks the "type more" prompt, which is- // not an empty result. A failed fetch is a different outcome (`taxonomic filter- // fetch failed`, below), so `anyError` rules it out — and `anyFetching` holds off- // capturing until every group has actually reported in: on the first render of a- // query, nothing has reported loading yet, so `emptyState` briefly looks like a- // genuine empty result before the real outcome (success, empty, or error) is known.- // `groupType` is `undefined` for the meta scopes (All/Recent/Pinned) because there's no single content group there- // (legacy fires per-group).- // Dedup mirrors legacy `lastEmptyResultDedupeKey`: remember only the most- // recent fired key so re-typing the same dead-end after an intervening query- // re-fires (an unbounded set would under-count repeated dead-ends vs legacy).- const lastEmptyResultKeyRef = useRef<string | null>(null)- useEffect(() => {- const trimmed = searchQuery.trim()- if (!emptyState || emptyState.body || !trimmed || anyError || anyFetching) {- return- }- const key = `${activeScope}::${trimmed}`- if (lastEmptyResultKeyRef.current === key) {- return- }- lastEmptyResultKeyRef.current = key- posthog.capture('taxonomic filter empty result', {- surface: TAXONOMIC_FILTER_SURFACE,- scope: telemetryGroupType ? 'category' : activeScope,- groupType: telemetryGroupType,- searchQuery: trimmed,- })- }, [emptyState, searchQuery, telemetryGroupType, activeScope, anyError, anyFetching])-- // `taxonomic filter fetch failed` — once per scope+query while the visible list's request- // keeps failing. Mirrors legacy `lastFetchFailedDedupeKey`: the key is only cleared once the- // group settles without an error, so retries that fail again for the same query don't- // recapture, but a later genuine failure for a new query does.- // Clearing on `!anyFetching` rather than `!isAnyLoading` matters: `isAnyLoading` depends on- // the fetch having no cached data yet, so a retry on a key that already holds older data (or- // a raw-query tag that hasn't caught up yet, e.g. a trailing-whitespace edit) reads as- // "settled" for one render even though the request hasn't actually finished. `anyFetching`- // treats that same stale tag as still busy, so the key survives the gap.- const lastFetchFailedKeyRef = useRef<string | null>(null)- useEffect(() => {- const trimmed = searchQuery.trim()- if (!anyError) {- if (!anyFetching) {- lastFetchFailedKeyRef.current = null- }- return- }- const key = `${telemetryGroupType ?? 'all'}::${trimmed}`- if (lastFetchFailedKeyRef.current === key) {- return- }- lastFetchFailedKeyRef.current = key- posthog.capture('taxonomic filter fetch failed', {- surface: TAXONOMIC_FILTER_SURFACE,- groupType: telemetryGroupType,- searchQuery: trimmed,- })- }, [anyError, anyFetching, searchQuery, telemetryGroupType])-- // Offered in the empty state whenever an event/custom-event group is among- // the visible targets (drilled Events/CustomEvents, or the merged All surface- // where stale events are also hidden) — mirrors legacy's recovery button:- // no matches behind the default stale filter -> let the user opt in and- // refetch with stale definitions included.- const eventGroupInScope = targetGroups.some(- (g) => g.type === TaxonomicFilterGroupType.Events || g.type === TaxonomicFilterGroupType.CustomEvents- )- const canOfferStaleToggle = !includeStaleEvents && !!searchQuery.trim() && eventGroupInScope- const handleIncludeStaleEvents = useCallback((): void => {- setIncludeStaleEvents(true)- posthog.capture('taxonomic filter include stale toggled', {- surface: TAXONOMIC_FILTER_SURFACE,- includeStaleEvents: true,- groupType: telemetryGroupType,- searchQuery: searchQuery || undefined,- })- }, [telemetryGroupType, searchQuery])-- // Only the active scope's groups are fetched, so a narrowed-to-one-category search- // that comes up empty can't know whether other categories have matches. Offer a jump- // to "All" (which fetches every group) so the user can check without re-typing. This is a- // deliberate divergence from the legacy `InfiniteList` empty state, which can read the- // aggregated count (`allSectionHasResults`) and only offers the jump when All has matches.- const canOfferAllSwitch =- showChips &&- !!searchQuery.trim() &&- activeScope !== 'all' &&- activeScope !== 'recent' &&- activeScope !== 'pinned'- const handleCheckOtherCategories = useCallback((): void => {- posthog.capture('taxonomic filter menu category changed', {- fromChip: activeChip,- toChip: 'all',- via: 'empty-state',- })- setActiveChip('all')- inputRef.current?.focus()- }, [activeChip]) // oxlint-disable-line react-hooks/exhaustive-deps-- const selectionContextFor = useCallback(- (entry: MenuFilterEntry): CommitSelectionContext => {- const key = entryKey(entry)- return {- groupType: telemetryGroupType,- // Rendered-row index; absent (not a sentinel) if the entry somehow- // isn't in `filtered` — `position` then drops out of the payload.- position: positionByEntry.get(entry),- wasFromRecents: recentKeys.has(key),- wasFromPinnedList: pinnedKeys.has(key),- }- },- [telemetryGroupType, recentKeys, pinnedKeys, positionByEntry]- )-- const headerTitle =- title ??- (drillTo === 'all'- ? 'Choose filter'- : drillTo === 'recent'- ? 'Recent'- : drillTo === 'pinned'- ? 'Pinned'- : (groups.find((g) => g.type === drillTo)?.name ?? 'Filter'))-- const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {- if (e.key === 'Escape') {- onBack()- e.preventDefault()- e.stopPropagation()- return- }- if (e.key === 'Enter') {- // mode="none" → no auto-selection. Click the highlighted row- // (tracked by base-ui via `aria-activedescendant`) to commit.- const activeId = e.currentTarget.getAttribute('aria-activedescendant')- if (activeId) {- const el = e.currentTarget.ownerDocument.getElementById(activeId) as HTMLElement | null- el?.click()- e.preventDefault()- e.stopPropagation()- }- return- }- if (e.key === 'Tab' && showChips && visibleChipGroups.length > 0) {- // Cycle categories while focus stays on input. Wraps both- // directions. Shares `categoryOptions` with the dropdown so the- // trigger label stays in sync.- const ordered = categoryOptions.map((o) => o.value)- const idx = ordered.indexOf(activeChip)- const dir = e.shiftKey ? -1 : 1- const next = ordered[(idx + dir + ordered.length) % ordered.length]- posthog.capture('taxonomic filter menu category changed', {- fromChip: activeChip,- toChip: next,- via: 'tab',- direction: e.shiftKey ? 'backward' : 'forward',- })- setActiveChip(next)- e.preventDefault()- e.stopPropagation()- }- }-- // Category dropdown — picks the active scope; replaces the old flex-wrapped- // chip row. Only shown when there's more than the implicit "All" category.- const categorySelect =- showChips && categoryOptions.length > 1 ? (- <Select<DrillCategory>- value={activeChip}- onValueChange={(value) => {- posthog.capture('taxonomic filter menu category changed', {- fromChip: activeChip,- toChip: value ?? 'all',- via: 'dropdown',- })- setActiveChip(value ?? 'all')- inputRef.current?.focus()- }}- itemToStringLabel={(value) => categoryOptions.find((o) => o.value === value)?.label ?? 'All'}- >- <SelectTrigger- size="sm"- aria-label="Filter category"- data-attr="menu-filter-category"- className="mr-0.5"- >- <SelectValue />- </SelectTrigger>- {/* Fit the list to its items: at least as wide as the trigger,- grow to the longest option, capped at the available viewport- width so it never overflows. */}- <SelectContent- align="end"- alignItemWithTrigger={false}- className="w-max min-w-(--anchor-width) max-w-(--available-width)"- >- <SelectGroup>- {categoryOptions.map((o) => (- <SelectItem key={o.value} value={o.value}>- {o.label}- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>- ) : null-- // The search field — a full-width row between the header and the- // list/preview, so the menu chrome wraps it (header above, results below).- // In input-trigger mode it's a LemonInput matching the surrounding scene's- // UI, with base-ui driving the inner input via `render`, the filter-icon- // button as its prefix and the category dropdown as its suffix. The button- // trigger keeps the quill input bar.- const searchField = iconButton ? (- <AutocompleteLemonInput- value={searchQuery}- onValueChange={setSearchQuery}- sharedInputRef={inputRef}- prefix={iconButton}- suffix={categorySelect ?? undefined}- placeholder={activePlaceholder}- data-attr="menu-filter-search"- onKeyDown={handleInputKeyDown}- onPaste={(e) => {- pastedCharsRef.current += e.clipboardData.getData('text').length- }}- />- ) : (- <>- <Autocomplete.Input- render={- <InputGroupInput- ref={inputRef}- autoFocus- data-attr="menu-filter-search"- placeholder={activePlaceholder}- onKeyDown={handleInputKeyDown}- onPaste={(e: React.ClipboardEvent<HTMLInputElement>) => {- pastedCharsRef.current += e.clipboardData.getData('text').length- }}- />- }- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- />- {categorySelect && <InputGroupAddon align="inline-end">{categorySelect}</InputGroupAddon>}- </>- )-- // Full-width input row, sitting between the header and the list/preview- // columns. The LemonInput (input-trigger) is full width on its own; the- // quill input needs the InputGroup wrapper.- const searchFieldRow = (- <div className="p-2 border-b">{iconButton ? searchField : <InputGroup>{searchField}</InputGroup>}</div>- )-- return (- <div className="flex flex-col flex-1 min-h-0">- <MenuFilterHeader- title={headerTitle}- onBack={onBack}- // Tab cycles the chip row — hide the hint when chips- // aren't visible (drilled views, Recent / Pinned), since- // there's nothing to cycle through.- showTabHint={showChips && visibleChipGroups.length > 0}- />- <Autocomplete.Root- items={displayedItems}- mode="none"- inline- defaultOpen- autoHighlight="always"- // `keepHighlight` so moving the pointer off the list (into- // the preview pane to click Pin / Edit / View) doesn't- // reset to the first row and pull the preview out from- // under the user.- keepHighlight- openOnInputClick={false}- itemToStringValue={(entry: MenuFilterEntry) => entry.name}- onItemHighlighted={(entry) => setHighlightedEntry((entry as MenuFilterEntry | undefined) ?? null)}- >- {searchFieldRow}- {/* Flex layout: list flexes, separator is 1px, preview is a- fixed 300px column. `shrink-0` on the preview keeps it- stable when the popover (or list contents) change width. */}- <div className="flex flex-1 min-h-0">- <div className="flex flex-col flex-1 min-w-0 min-h-0">- {!drillItems &&- targetGroups.map((g) => (- <Fetcher- key={g.type}- group={g}- excludeStale={!includeStaleEvents}- onItems={reportItems}- onLoadingChange={reportLoading}- onFetchingChange={reportFetching}- onErrorChange={reportError}- />- ))}- <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 || barrierClosed ? (- <LoadingRows />- ) : anyError ? (- <div- data-attr="menu-filter-error"- className="flex flex-col items-center gap-2 px-4 py-8 text-center"- >- <IconWarning className="text-5xl text-tertiary" />- <div className="text-sm font-semibold">Couldn't load results</div>- <Button- variant="outline"- size="sm"- data-attr="menu-filter-retry"- loading={retrying}- onClick={handleRetry}- >- Try again- </Button>- <div className="text-xs text-secondary italic">- If it keeps happening, contact support.- </div>- </div>- ) : (- emptyState && (- <div- data-attr="menu-filter-empty"- className="flex flex-col items-center gap-2 px-4 py-8 text-center"- >- <div className="text-sm font-semibold">{emptyState.title}</div>- {emptyState.body && (- <div className="text-xs text-secondary leading-relaxed">- {emptyState.body}- </div>- )}- {canOfferStaleToggle && !emptyState.body && (- <Button- variant="outline"- size="sm"- data-attr="menu-filter-include-stale-events"- onClick={handleIncludeStaleEvents}- >- Include stale events- </Button>- )}- {canOfferAllSwitch && !emptyState.body && (- <Button- variant="outline"- size="sm"- data-attr="menu-filter-check-other-categories"- onClick={handleCheckOtherCategories}- >- Check for results in other categories- </Button>- )}- </div>- )- )}- </Autocomplete.Empty>- <Autocomplete.Collection>- {(entry: MenuFilterEntry) => (- <Row- key={rowDomId(entry)}- entry={entry}- // Show the category label on mixed-group views (All,- // Recent, Pinned) — those mix items from multiple- // categories so the label disambiguates. Drilled-to-- // one-group views skip it (the panel header / chip- // already names the category).- showCategory={- activeChip === 'all' ||- activeChip === 'recent' ||- activeChip === 'pinned' ||- drillTo === 'recent' ||- drillTo === 'pinned'- }- // Tag rows that are one of the user's recents/pinned so- // they read e.g. "Events - recent".- recency={recencyForEntry(entry)}- // DWH rows open the column-config- // form, not a final selection —- // signal that with a chevron.- opensSubmenu={drillTo === TaxonomicFilterGroupType.DataWarehouse}- selectedRowId={selectedRowId}- selectedRename={selectedRename}- onSelect={() => onCommit(entry, undefined, selectionContextFor(entry))}- />- )}- </Autocomplete.Collection>- </Autocomplete.List>- </ScrollArea>- </div>- <Separator orientation="vertical" className="h-full hidden md:block" />- <PreviewPane- entry={highlightedEntry}- className="hidden md:flex flex-col w-[300px] shrink-0 min-w-0"- />- </div>- </Autocomplete.Root>- </div>- )-}--interface AutocompleteLemonInputProps {- value: string- onValueChange: (value: string) => void- /** Set alongside base-ui's own ref, so callers (popover `initialFocus`,- * category-select refocus) can reach the input element. */- sharedInputRef?: MutableRefObject<HTMLInputElement | null>- prefix?: ReactElement- suffix?: ReactElement- placeholder?: string- 'data-attr'?: string- /** Runs before base-ui's own keydown handler; base-ui's runs only when this- * one didn't `preventDefault` (so Esc/Enter/Tab can take precedence over the- * autocomplete's arrow-key navigation). */- onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void- onPaste?: (e: React.ClipboardEvent<HTMLInputElement>) => void-}--/**- * The single place that bridges base-ui's `Autocomplete.Input` onto a- * `LemonInput`. base-ui drives a controlled `<input>` through its `render` prop —- * value/onChange/ref/keyboard plus the combobox a11y attrs (`role`,- * `aria-activedescendant`, `aria-expanded`, …). `LemonInput`'s typed props don't- * include those a11y attrs but its inner `<input>` forwards unrecognised props,- * so we strip the props we drive ourselves and pass the rest through. Keeping the- * adapter in one named place (rather than inline in the combobox render) means a- * base-ui upgrade that changes how it drives the input has exactly one site to- * update — the typed destructure below and the input-trigger tests are what guard- * the contract.- */-function AutocompleteLemonInput({- value,- onValueChange,- sharedInputRef,- prefix,- suffix,- placeholder,- onKeyDown,- onPaste,- 'data-attr': dataAttr,-}: AutocompleteLemonInputProps): JSX.Element {- return (- <Autocomplete.Input- value={value}- onChange={(e) => onValueChange(e.target.value)}- render={(autoProps) => {- // Type the incoming contract as input attributes (not `any`), then- // peel off the props we own — base-ui's value/onChange/className,- // its ref (merged below), and its keydown (composed below).- const {- ref,- value: _baseValue,- onChange: _baseOnChange,- className: _baseClassName,- onKeyDown: baseOnKeyDown,- ...baseInputAttrs- } = autoProps as React.InputHTMLAttributes<HTMLInputElement> & {- ref?: React.Ref<HTMLInputElement>- }- const setRef = (el: HTMLInputElement | null): void => {- if (typeof ref === 'function') {- ref(el)- } else if (ref) {- ;(ref as React.MutableRefObject<HTMLInputElement | null>).current = el- }- if (sharedInputRef) {- sharedInputRef.current = el- }- }- return (- <LemonInput- // The remaining base-ui attrs (role, aria-activedescendant…)- // are valid `<input>` attributes LemonInput forwards but- // doesn't type — the one boundary cast the bridge needs.- // eslint-disable-next-line react/no-unknown-property- {...(baseInputAttrs as Record<string, unknown>)}- inputRef={setRef}- size="small"- fullWidth- prefix={prefix}- suffix={suffix}- data-attr={dataAttr}- placeholder={placeholder}- value={value}- onChange={(next) => onValueChange(next)}- onKeyDown={(e) => {- onKeyDown?.(e)- if (!e.defaultPrevented) {- baseOnKeyDown?.(e)- }- }}- onPaste={onPaste}- />- )- }}- />- )-}--interface RowProps {- entry: MenuFilterEntry- /** Render the category label (mixed-group views always; drilled views skip it since the panel header already names the group). */- showCategory: boolean- /** When the row is one of the user's recents/pinned, append the source tag (e.g. "Events - recent"). */- recency?: 'recent' | 'pinned' | null- /** Show a trailing chevron when click drills to another panel (DWH config). */- opensSubmenu?: boolean- /** DOM id of the currently-selected row (for the trailing checkmark). */- selectedRowId?: string | null- /** Rename carried by the series being edited — applied to the selected row so its- * label matches the series the user clicked, with the raw key as the value cell. */- selectedRename?: SeriesRename | null- /** Commit this row (also fires item-selected telemetry). */- onSelect: () => void-}--/**- * Resolve a row's normalized cells:- * - name: human-friendly label (e.g. "Pageview", "/checkout")- * - value: raw underlying value when distinct from the name (the full- * URL, or the raw `$key`). The preview pane is the primary home- * for this ("Sent as"), but the preview is hidden below `md`, so- * the row keeps a narrow-screen-only copy of it.- * - category: group name shown as an uppercase tag at the bottom- *- * URLs surface their path tail as the name; friendly definitions surface- * the friendly label; everything else uses the entry name and has no- * distinct raw value to show.- */-function resolveRowCells(entry: MenuFilterEntry): {- name: string- value?: string- category: string-} {- if (entry.recentLabel) {- return { name: entry.recentLabel, category: entry.group.name }- }- const friendly = entry.friendlyLabel- const pathTail = parseUrlPathTail(entry.name)- if (pathTail !== null) {- return {- name: pathTail,- value: entry.name,- category: entry.group.name,- }- }- if (friendly && friendly.length > 0 && friendly !== entry.name) {- return {- name: friendly,- value: entry.name,- category: entry.group.name,- }- }- return { name: entry.name, category: entry.group.name }-}--function Row({- entry,- showCategory,- recency,- opensSubmenu,- selectedRowId,- selectedRename,- onSelect,-}: RowProps): JSX.Element {- const cells = resolveRowCells(entry)- const stableId = rowDomId(entry)- const isSelected = selectedRowId === stableId- // The committed selection of a renamed series shows the series' name; the raw key- // it queries moves to the value cell, like any other friendly-labelled row.- const isRenamedSelection = isSelected && !!selectedRename && selectedRename.label !== cells.name- const itemTag = entry.group.getTag?.(entry.item)- const name = isRenamedSelection ? selectedRename.label : cells.name- const value = isRenamedSelection && selectedRename.raw !== selectedRename.label ? selectedRename.raw : cells.value- const category = cells.category- return (- <Autocomplete.Item- value={entry}- onClick={(e) => {- e.preventDefault()- onSelect()- }}- data-slot="taxonomic-filter-menu-row"- className={cn(- 'flex flex-row items-center gap-2 rounded-sm px-2 py-1 cursor-pointer outline-none',- // `data-selected` mirrors base-ui's `highlighted` state via- // the render fn below — keyboard / pointer cursor on this- // row gets a soft hover tint.- 'data-selected:bg-(--fill-hover)',- // Persistent tint for the committed selection. Plain- // conditional class — base-ui's `render` override only- // forwards its own computed props, so `data-*` extras- // passed to `Autocomplete.Item` would be dropped.- isSelected && 'bg-(--fill-hover)'- )}- // `id` lives on the rendered `<div>` (not on the Autocomplete.Item- // props) — base-ui omits `id` from its prop typing because it- // assigns its own. The wrap-render lets us pin the stable id- // we need for `scrollIntoView` + checkmark lookups without- // fighting the type.- render={(itemProps, state) => (- <div {...itemProps} id={stableId} data-selected={state.highlighted ? '' : undefined} />- )}- >- <div className="flex flex-col items-start gap-0 min-w-0 flex-1">- <span className="text-sm leading-tight truncate max-w-full">{name}</span>- {/* The preview pane (hidden below `md`) is the primary home for the- raw value, so only narrow screens keep it inline on the row — except- for a renamed selection, where the label alone doesn't reveal what- the series queries, so the raw key stays inline at every size. */}- {value && (- <span- className={cn(- 'font-mono text-xs text-tertiary/50 leading-tight truncate max-w-full',- !isRenamedSelection && 'md:hidden'- )}- >- {value}- </span>- )}- {showCategory && <MenuLabel className="text-tertiary/50 text-xxs p-0 mt-1">{category}</MenuLabel>}- </div>- <MatchedValueBadge entry={entry} />- {/* Whatever the group supplies for this item, the same node the classic list renders,- so a picker row carries its per-item state in either menu. */}- {itemTag && <span className="shrink-0 empty:hidden">{itemTag}</span>}- {recency && (- <Badge variant="default" className="gap-1 shrink-0">- {recency === 'recent' ? <IconClock className="size-3" /> : <IconPinFilled className="size-3" />}- {recency === 'recent' ? 'Recent' : 'Pinned'}- </Badge>- )}- <VerificationBadge entry={entry} />- {isSelected && <IconCheck className="size-3.5 text-foreground shrink-0" />}- {opensSubmenu && <IconChevronRight className="size-3.5 text-tertiary shrink-0" />}- </Autocomplete.Item>- )-}--/**- * Zero-DOM fetcher: runs `useGroupList` for one group and reports items- * up via callback. Mounting one per visible group keeps the parent memo- * cheap (no nested hook arrays).- */-function Fetcher({- group,- excludeStale,- onItems,- onLoadingChange,- onFetchingChange,- onErrorChange,-}: {- group: TaxonomicFilterGroup- /** Hide stale event definitions (event / custom-event groups only). */- excludeStale: boolean- onItems: (type: string, items: TaxonomicDefinitionTypes[]) => void- /** 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, query?: string) => void- /** Reports whether this group's request failed with nothing to fall back on, plus a- * retry function the parent can call from the error state's "Try again" button, and- * the query the report belongs to (so the parent can ignore a stale report). */- onErrorChange: (type: string, hasError: boolean, retry: () => Promise<unknown>, query?: string) => void-}): null {- const { getGroupListInput } = useTaxonomicFilterContext()- const input = getGroupListInput(group)- const list = useGroupList({ ...input, excludeStale })- useEffect(() => {- onItems(group.type, list.items)- }, [group.type, list.items, onItems])- useEffect(() => {- onLoadingChange(group.type, list.showLoadingState)- }, [group.type, list.showLoadingState, onLoadingChange])- useEffect(() => {- onFetchingChange(group.type, list.isFetching, input.searchQuery)- }, [group.type, list.isFetching, input.searchQuery, onFetchingChange])- // `refetch`'s identity changes every render — read it through a ref so the effect only- // reruns when `showErrorState` itself changes, not on every unrelated re-render.- const refetchRef = useRef(list.refetch)- refetchRef.current = list.refetch- useEffect(() => {- onErrorChange(group.type, list.showErrorState, () => refetchRef.current(), input.searchQuery)- // oxlint-disable-next-line react-hooks/exhaustive-deps -- refetchRef always holds the latest fn- }, [group.type, list.showErrorState, input.searchQuery, onErrorChange])- // Make sure we flip back to "not loading"/"not fetching"/"not errored" when this group- // unmounts — otherwise a stale `true` from a previously-active chip would keep the- // skeleton (or the reveal barrier, or the error state) stuck after we switch scope.- useEffect(() => {- return () => {- onLoadingChange(group.type, false)- onFetchingChange(group.type, false)- onErrorChange(group.type, false, () => Promise.resolve())- }- }, [group.type, onLoadingChange, onFetchingChange, onErrorChange])- return null-}--/** Skeleton placeholder shown in place of the result list while a remote- * fetch is in flight and we have nothing to show yet. Matches the- * single-line row layout so the popover height doesn't jump when results- * arrive. */-function LoadingRows(): JSX.Element {- return (- <div className="flex flex-col gap-1 p-2" data-attr="menu-filter-loading">- {[0, 1, 2, 3, 4].map((i) => (- <div key={i} className="px-2 py-1">- <Skeleton className="h-3.5 w-2/3 rounded" />- </div>- ))}- </div>- )-}--/**- * Parse a URL-shaped string into its path tail (path + search + hash) for- * row rendering. Returns `null` for anything that isn't a `http(s)://` URL- * or fails to parse — caller falls back to default rendering.- */-function parseUrlPathTail(s: string): string | null {- if (typeof s !== 'string' || !/^https?:\/\//i.test(s)) {- return null- }- try {- const u = new URL(s)- return (u.pathname || '/') + u.search + u.hash- } catch {- return null- }-}--function getRawName(item: TaxonomicDefinitionTypes, group: TaxonomicFilterGroup): string {- // Prefer the underlying `name` field — it's the raw identifier on- // most definitions (`$timestamp`, `event`, `properties.$browser`).- // Some groups override `getName` to return a humanized label (Event- // metadata maps `id` → `coreFilterDefinition.label`, returning- // "Timestamp" for `timestamp`); falling back to `getName` only when- // the item has no `name` keeps the raw → friendly → display chain- // working so the preview's "Sent as" surfaces the underlying key.- const itemName = (item as unknown as { name?: unknown }).name- if (typeof itemName === 'string' && itemName.length > 0) {- return itemName- }- return group.getName?.(item) ?? ''-}--function getFriendlyLabel(item: TaxonomicDefinitionTypes, group: TaxonomicFilterGroup): string | undefined {- const raw = getRawName(item, group)- if (!raw) {- return undefined- }- return getCoreFilterDefinition(raw, group.type)?.label-}--function buildMenuFilterEntry(item: TaxonomicDefinitionTypes, group: TaxonomicFilterGroup): MenuFilterEntry {- return {- item,- group,- name: getRawName(item, group),- friendlyLabel: getFriendlyLabel(item, group),- }-}--// Mirrors the legacy `taxonomicFilterLogic` classifier (kept in sync until the legacy picker is retired).-function classifyInputMode(pastedChars: number, totalLength: number): 'typed' | 'mixed' | 'pasted' {- return pastedChars >= totalLength && pastedChars > 0 ? 'pasted' : pastedChars > 0 ? 'mixed' : 'typed'-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/DwhFlow.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/DwhFlow.tsxdeleted file mode 100644index 00f112300b85..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/DwhFlow.tsx+++ /dev/null@@ -1,591 +0,0 @@-/**- * Data warehouse config form, rendered as a Quill Dialog (modal) on top- * of the popover so the form gets full breathing room instead of being- * squeezed inside the 720px popover.- *- * Flow:- * - User picks a DWH table from the combobox (`drillTo='dwh-pick'`- * in `TaxonomicFilterMenu`).- * - Clicking a row transitions to `dwh-config` and opens this Dialog- * while the popover stays underneath at the table list.- * - "Cancel" (or X / overlay / Esc) calls `onBack` → state returns- * to `dwh-pick` so the user can pick a different table.- * - "Select" calls `onCommit` → `closeAll` which dismisses both the- * dialog and the parent popover.- *- * Mirrors the legacy `FunnelDataWarehouseStepDefinitionPopover` flow:- * - DatabaseTablePreview at the top so the user can sanity-check the- * data they're configuring against.- * - One tab per `dataWarehousePopoverFields` entry (Aggregation- * target / Timestamp / Unique ID by default).- * - Per-field description + a column dropdown filtered to the- * allowed Postgres types for that field.- * - HogQL fallback (lazy Monaco) when the active field has- * `allowHogQL: true` and the chosen value isn't a real column.- * - When `insightProps` is supplied, the aggregation-target tab- * reads `funnelDataLogic.querySource` to render the- * "Current aggregation target is set to person/group" message- * that mirrors the legacy popover.- */-import { useValues } from 'kea'-import { useMemo, useRef, useState } from 'react'--import {- Badge,- Button,- Combobox,- ComboboxContent,- ComboboxEmpty,- ComboboxInput,- ComboboxItem,- ComboboxList,- Dialog,- DialogBody,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,- Field,- FieldContent,- FieldDescription,- FieldLabel,- ItemContent,- ItemDescription,- ItemTitle,- Tabs,- TabsList,- TabsTrigger,-} from '@posthog/quill'--import { HogQLEditor } from 'lib/components/HogQLEditor/HogQLEditor'-import { DatabaseTablePreview } from 'lib/components/TablePreview/DatabaseTablePreview'-import type { TablePreviewExpressionColumn } from 'lib/components/TablePreview/types'-import { Link } from 'lib/lemon-ui/Link'-import { urls } from 'scenes/urls'--import type { DatabaseSerializedFieldType } from '~/queries/schema/schema-general'-import { NodeKind } from '~/queries/schema/schema-general'-import { InsightLogicProps } from '~/types'--import { funnelDataLogic } from 'products/product_analytics/frontend/insights/funnels/funnelDataLogic'--import { HIDDEN_FIELD_TYPES } from '../dataWarehouseColumns'-import { defaultDataWarehousePopoverFields } from '../taxonomicFilterLogic'-import { DataWarehousePopoverField, TaxonomicDefinitionTypes } from '../types'-import { CommitFn, MenuFilterEntry, TaxonomicFilterGroup } from './types'--/** Allowed column types per field key — copied from the legacy logic so- * the dropdowns surface the same options as the funnel popover. */-const ALLOWED_COLUMN_TYPES_BY_FIELD_KEY: Record<string, DatabaseSerializedFieldType[]> = {- aggregation_target_field: ['string'],- timestamp_field: ['datetime', 'date', 'string'],- id_field: ['string', 'integer', 'decimal', 'float'],- distinct_id_field: ['string'],-}--/** Default descriptions per known field key — used when the consumer- * doesn't pass a `description` on the field. Keeps the form- * self-explanatory even when the caller hands us the bare default- * `defaultDataWarehousePopoverFields` array. Mirrors the legacy- * `EDITABLE_FIELD_EXPLANATIONS` table. */-const DEFAULT_FIELD_DESCRIPTIONS: Record<string, string> = {- aggregation_target_field: 'Used to match people or groups across funnel steps.',- timestamp_field: 'Used to order step timing and apply the funnel date range.',- id_field: 'Used as the unique row ID to detect duplicate records.',- distinct_id_field: 'Used to associate this row with a person via distinct_id.',-}--const LINKED_TABLE_TYPES: DatabaseSerializedFieldType[] = ['lazy_table', 'virtual_table']--interface ColumnOption {- name: string- type: DatabaseSerializedFieldType-}--export interface MenuFilterDwhConfigProps {- table: TaxonomicDefinitionTypes- group: TaxonomicFilterGroup- onCommit: CommitFn- onBack: () => void- /** Field keys + labels to expose as tabs. Defaults to the standard `id_field` / `timestamp_field` / `distinct_id_field` bundle. */- dataWarehousePopoverFields?: DataWarehousePopoverField[]- /** When supplied, the aggregation-target tab reads `funnelDataLogic` for context (group vs person, HogQL aggregation). */- insightProps?: InsightLogicProps-}--export function MenuFilterDwhConfig({- table,- group,- onCommit,- onBack,- dataWarehousePopoverFields = defaultDataWarehousePopoverFields,- insightProps,-}: MenuFilterDwhConfigProps): JSX.Element {- const tableName = group.getName?.(table) ?? (table as { name?: string }).name ?? 'table'-- // ---- columns ---------------------------------------------------------- const columns: ColumnOption[] = useMemo(() => {- const fields =- (table as { fields?: Record<string, { name?: string; type?: DatabaseSerializedFieldType }> }).fields ?? {}- return Object.values(fields)- .filter((f) => !!f?.name && !!f?.type)- .map((f) => ({ name: f.name as string, type: f.type as DatabaseSerializedFieldType }))- }, [table])-- const linkedTables = useMemo(- () => columns.filter((c) => LINKED_TABLE_TYPES.includes(c.type)).map((c) => c.name),- [columns]- )-- // ---- local definition (per-field current value) ---------------------- type FieldValues = Record<string, string | undefined>- const initialValues: FieldValues = useMemo(() => {- const out: FieldValues = {}- for (const f of dataWarehousePopoverFields) {- const existing = (table as unknown as Record<string, unknown>)[f.key]- if (typeof existing === 'string' && existing.length > 0) {- out[f.key] = existing- continue- }- // Cheap heuristic so the user lands on a likely-correct column- // when the table hasn't been configured before.- const guess =- f.key === 'id_field'- ? columns.find((c) => c.name === 'id' || c.name.endsWith('_id'))- : f.key === 'timestamp_field'- ? columns.find(- (c) =>- c.name === 'timestamp' ||- c.name.includes('time') ||- c.name.includes('created') ||- c.name.includes('date')- )- : f.key === 'distinct_id_field'- ? columns.find((c) => c.name.includes('distinct'))- : columns[0]- out[f.key] = guess?.name- }- return out- }, [table, columns, dataWarehousePopoverFields])-- const [values, setValues] = useState<FieldValues>(initialValues)-- // ---- active tab ------------------------------------------------------ const [activeFieldKey, setActiveFieldKey] = useState<string>(() => dataWarehousePopoverFields[0]?.key ?? 'id_field')- const activeField = useMemo(- () => dataWarehousePopoverFields.find((f) => f.key === activeFieldKey),- [activeFieldKey, dataWarehousePopoverFields]- )-- // ---- column options for the active field ---------------------------- const activeFieldOptions = useMemo<ColumnOption[]>(() => {- const allowed = ALLOWED_COLUMN_TYPES_BY_FIELD_KEY[activeFieldKey] ?? []- const filtered = allowed.length > 0 ? columns.filter((c) => allowed.includes(c.type)) : columns- return filtered- }, [activeFieldKey, columns])-- const activeFieldValue = values[activeFieldKey] ?? ''- // HogQL mode — true whenever the active value isn't one of the field's- // *selectable* options (including `''`, the sentinel for "user picked- // SQL expression but hasn't typed anything yet"). Checked against- // `activeFieldOptions` — the same type-filtered set `ColumnSelect` uses- // — so the editor and the dropdown agree: when the dropdown shows "SQL- // expression", the editor renders. A value that's a real column but of- // a disallowed type for this field counts as HogQL, matching the- // dropdown.- const activeFieldIsHogQL = useMemo(- () => !!activeField?.allowHogQL && !activeFieldOptions.some((c) => c.name === activeFieldValue),- [activeField, activeFieldValue, activeFieldOptions]- )-- // ---- preview -------------------------------------------------------- const previewTable = useMemo(() => {- const fields = (table as { fields?: Record<string, { type?: DatabaseSerializedFieldType }> }).fields ?? {}- return {- ...(table as object),- fields: Object.fromEntries(- Object.entries(fields).filter(- ([, f]) => !HIDDEN_FIELD_TYPES.includes(f?.type as DatabaseSerializedFieldType)- )- ),- } as typeof table- }, [table])-- const previewExpressionColumns: TablePreviewExpressionColumn[] = useMemo(() => {- const tableFieldNames = new Set(columns.map((c) => c.name))- const usedKeys = new Set(tableFieldNames)- const out: TablePreviewExpressionColumn[] = []- for (const f of dataWarehousePopoverFields) {- const v = values[f.key]- if (typeof v !== 'string') {- continue- }- const expression = v.trim()- if (!expression || tableFieldNames.has(expression)) {- continue- }- const keyBase = `__${f.key}_hogql_expression`- let key = keyBase- let suffix = 2- while (usedKeys.has(key)) {- key = `${keyBase}_${suffix}`- suffix += 1- }- usedKeys.add(key)- out.push({ key, expression, label: `${f.label} (SQL expression)`, type: 'SQL expression' })- }- return out- }, [columns, dataWarehousePopoverFields, values])-- const previewSelectedKey = useMemo(() => {- const expr = previewExpressionColumns.find((c) => c.key.startsWith(`__${activeFieldKey}_hogql_expression`))- return expr?.key ?? activeFieldValue- }, [previewExpressionColumns, activeFieldKey, activeFieldValue])-- const canSubmit = useMemo(- () =>- dataWarehousePopoverFields.every((f) => {- if (f.optional) {- return true- }- const v = values[f.key]- return typeof v === 'string' && v.length > 0- }),- [dataWarehousePopoverFields, values]- )-- const entry: MenuFilterEntry = useMemo(- () => ({- item: table,- group,- name: tableName,- }),- [table, group, tableName]- )-- return (- <Dialog- open- // Open is bound to render — when this component unmounts the- // dialog disappears. `onOpenChange(false)` fires for X /- // overlay / Esc; route those to `onBack` so the parent state- // machine returns to `dwh-pick` (popover keeps showing the- // table list).- onOpenChange={(open) => {- if (!open) {- onBack()- }- }}- >- <DialogContent- // `nested` because a popover with focus management is- // already open underneath; tells base-ui to stack focus- // traps + handle overlay clicks correctly.- nested- // `size="wide"` clamps to ~72rem so the embedded- // LemonTable preview gets horizontal breathing room.- // Vertical behaviour (viewport-bounded `max-height`,- // three-row grid, body scroll) comes from Quill's- // base dialog styling regardless of size.- size="wide"- className="gap-0 p-0"- >- <DialogHeader className="flex-row items-center gap-2 px-4 py-3 border-b">- <Button- type="button"- variant="outline"- size="sm"- aria-label="Go back"- onClick={onBack}- className="shrink-0 gap-1"- data-attr="dwh-config-back"- >- Go back- </Button>- <DialogTitle className="flex-1 truncate">Configure data warehouse table</DialogTitle>- </DialogHeader>- {/* `DialogBody` defaults to a `ScrollArea` (per Quill)- so we get scroll shadows and edge-overflow data- attrs for free. The viewport already gets- `padding-block: 1rem` from Quill's body styling, so- the inner stack just needs a row gap. Fills the full- `size="wide"` dialog width — no max-width clamp. */}- <DialogBody className="w-full overflow-auto">- <div className="flex flex-col gap-4 min-w-0">- <FieldDescription className="!mt-0">- Table: <Badge variant="info">{tableName}</Badge>- </FieldDescription>-- {/* `data-not-quill` resets the colour-token rebinds- that `[data-quill]` applies on the popover root,- so the legacy DatabaseTablePreview keeps its- PostHog colours instead of inheriting Quill's. */}- <div data-not-quill className="flex min-w-0 overflow-x-auto">- <DatabaseTablePreview- table={previewTable as never}- selectedKey={previewSelectedKey || undefined}- limit={25}- expressionColumns={previewExpressionColumns}- emptyMessage="No table selected"- bordered- />- </div>-- <Tabs value={activeFieldKey} onValueChange={(v) => setActiveFieldKey(v)}>- <TabsList className="bg-muted">- {dataWarehousePopoverFields.map((f) => (- <TabsTrigger key={f.key} value={f.key}>- {f.label}- </TabsTrigger>- ))}- </TabsList>- </Tabs>-- {activeField && (- <ActiveFieldEditor- field={activeField}- value={activeFieldValue}- isHogQL={activeFieldIsHogQL}- options={activeFieldOptions}- tableName={tableName}- linkedTables={linkedTables}- onChange={(v) => setValues((prev) => ({ ...prev, [activeField.key]: v }))}- insightProps={insightProps}- />- )}- </div>- </DialogBody>- <DialogFooter className="px-4 py-3 border-t">- <Button variant="outline" onClick={onBack}>- Cancel- </Button>- <Button- variant="primary"- disabled={!canSubmit}- onClick={() =>- // `handleCommit` upstream calls `closeAll`,- // which collapses the popover too — so Select- // dismisses both the dialog and the menu in- // one click.- onCommit(entry, {- ...values,- } as Record<string, unknown>)- }- >- Select- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}--interface ActiveFieldEditorProps {- field: DataWarehousePopoverField- value: string- isHogQL: boolean- options: ColumnOption[]- tableName: string- linkedTables: string[]- onChange: (v: string) => void- insightProps?: InsightLogicProps-}--/**- * Active-field editor: column dropdown + optional HogQL fallback. Split- * out so it can mount the funnel logic conditionally (only when- * `insightProps` is supplied) without that cost on every render.- */-function ActiveFieldEditor({- field,- value,- isHogQL,- options,- tableName,- linkedTables,- onChange,- insightProps,-}: ActiveFieldEditorProps): JSX.Element {- const description = field.description ?? DEFAULT_FIELD_DESCRIPTIONS[field.key]- return (- <Field>- <FieldLabel className="text-sm font-semibold">{field.label}</FieldLabel>- <FieldContent className="gap-3">- {description && <FieldDescription className="!mt-0">{description}</FieldDescription>}-- {field.key === 'aggregation_target_field' && (- <AggregationTargetContext insightProps={insightProps} isHogQL={isHogQL} />- )}-- <ColumnSelect options={options} value={value} onChange={onChange} allowHogQL={!!field.allowHogQL} />-- {field.allowHogQL &&- isHogQL && (- // Render the rich `HogQLEditor` inline (full width) —- // skipping the legacy `HogQLDropdown` button-trigger- // wrapper — so users see the editor + placeholder- // examples + "Update SQL expression" button + "Learn- // more about SQL" link without an extra click.- <HogQLEditor- value={value}- onChange={(v) => onChange(v)}- metadataSource={{- kind: NodeKind.HogQLQuery,- query: `SELECT * FROM ${field.tableName ?? tableName}`,- }}- placeholder={- linkedTables.length- ? `Enter an SQL Expression, for example:\n- json_column.my_person_id\n- person_distinct_ids.person_id\n\nYou can also reference these linked tables: ${linkedTables.join(', ')}`- : `Enter an SQL Expression, for example:\n- json_column.my_person_id\n- person_distinct_ids.person_id`- }- disableAutoFocus- />- )}- </FieldContent>- </Field>- )-}--interface AggregationTargetContextProps {- /** Optional — when set, drives the "set to person/group/custom" copy. */- insightProps?: InsightLogicProps- isHogQL: boolean-}--function AggregationTargetContext({ insightProps, isHogQL }: AggregationTargetContextProps): JSX.Element {- return (- <FieldDescription className="!mt-0 flex flex-col gap-1">- {insightProps ? (- <FunnelAggregationDescription insightProps={insightProps} />- ) : (- <span>- Selected field needs to match the <b>Person ID</b> (or <b>Group ID</b> when aggregating by group).- </span>- )}- <span>- If this field is not directly available on the table, add it by joining in{' '}- <Link to={urls.sqlEditor()} target="_blank" className="underline text-primary">- SQL editor- </Link>{' '}- using fields like <code>distinct_id</code> or <code>email</code>.{' '}- <Link- to="https://posthog.com/docs/data-warehouse/join#table-joins"- target="_blank"- className="underline text-primary"- >- For more help- </Link>- . {isHogQL ? '(currently using SQL expression)' : ''}- </span>- </FieldDescription>- )-}--/**- * Splits the funnel-context-aware copy into its own component so we only- * mount `funnelDataLogic` when an `insightProps` is supplied. The- * surrounding joining-hint paragraph still renders regardless.- */-function FunnelAggregationDescription({ insightProps }: { insightProps: InsightLogicProps }): JSX.Element {- const { querySource } = useValues(funnelDataLogic(insightProps))- const isAggregatingByGroup = querySource?.aggregation_group_type_index != null- const isAggregatingByHogQL = !!querySource?.funnelsFilter?.funnelAggregateByHogQL && !isAggregatingByGroup- if (isAggregatingByHogQL) {- return (- <span>- Current aggregation target is custom. The selected field needs to match the custom aggregation value.- </span>- )- }- return (- <span>- Current aggregation target is set to <b>{isAggregatingByGroup ? 'group' : 'person'}</b>, so the selected- field needs to match the <b>{isAggregatingByGroup ? 'Group ID' : 'Person ID'}</b>.- </span>- )-}--interface ColumnSelectProps {- options: ColumnOption[]- value: string- onChange: (v: string) => void- allowHogQL: boolean-}--const HOGQL_SENTINEL = '__hogql__'--/** Flat entry shape backing the combobox — `title`/`description` map to the- * column name + type (or the SQL-expression sentinel row). */-interface ColumnSelectEntry {- value: string- title: string- description?: string-}--function ColumnSelect({ options, value, onChange, allowHogQL }: ColumnSelectProps): JSX.Element {- const [open, setOpen] = useState(false)- const triggerRef = useRef<HTMLButtonElement>(null)-- // HogQL mode whenever the value isn't a real column name AND the field- // allows it. Drop the `!!value` guard so the empty string (set by- // picking "SQL expression" from the dropdown before typing anything)- // still surfaces the SQL-expression label in the trigger instead of- // rendering as blank.- const isHogQL = allowHogQL && !options.some((o) => o.name === value)- const displayValue = isHogQL ? HOGQL_SENTINEL : value-- const items: ColumnSelectEntry[] = useMemo(- () => [- ...options.map((o) => ({ value: o.name, title: o.name, description: o.type as string })),- ...(allowHogQL- ? [{ value: HOGQL_SENTINEL, title: 'SQL expression', description: 'Use a HogQL expression' }]- : []),- ],- [options, allowHogQL]- )-- const selectedItem = items.find((item) => item.value === displayValue) ?? null-- return (- <Combobox- items={items}- itemToStringLabel={(item: ColumnSelectEntry) => item.title}- itemToStringValue={(item: ColumnSelectEntry) => item.value}- open={open}- onOpenChange={setOpen}- value={selectedItem}- onValueChange={(item: ColumnSelectEntry | null) =>- onChange(item ? (item.value === HOGQL_SENTINEL ? '' : item.value) : '')- }- >- <Button ref={triggerRef} variant="outline" className="h-min" onClick={() => setOpen((prev) => !prev)}>- {selectedItem ? (- <ItemContent variant="menuItem">- <ItemTitle>{selectedItem.title}</ItemTitle>- {selectedItem.description && (- <ItemDescription className="leading-none">{selectedItem.description}</ItemDescription>- )}- </ItemContent>- ) : (- <span className="text-muted-foreground">Select a value</span>- )}- </Button>- <ComboboxContent anchor={triggerRef} className="min-w-(--anchor-width)" align="start" sideOffset={8}>- <ComboboxInput placeholder="Search columns" showTrigger={false} />- <ComboboxEmpty>No columns found</ComboboxEmpty>- <ComboboxList>- {(item: ColumnSelectEntry) => (- <ComboboxItem key={item.value} value={item} className="py-0">- <ItemContent variant="menuItem">- <ItemTitle>{item.title}</ItemTitle>- {item.description && (- <ItemDescription className="leading-none">{item.description}</ItemDescription>- )}- </ItemContent>- </ComboboxItem>- )}- </ComboboxList>- </ComboboxContent>- </Combobox>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Header.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Header.tsxdeleted file mode 100644index 2649d8f40bd4..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/Header.tsx+++ /dev/null@@ -1,53 +0,0 @@-/**- * Shared header for popover sub-pages. Renders a back button (← chevron)- * + title. The back button calls `onBack` — the parent state machine- * decides what "back" means for the current page (typically: re-open the- * dropdown menu).- */--import { Button, cn, Kbd } from '@posthog/quill'--export interface MenuFilterHeaderProps {- title: string- onBack: () => void- className?: string- /**- * Whether the Tab keyboard hint should render. Drilled views (single- * category, Recent, Pinned) have no chip row to cycle through, so- * the hint is misleading there — pass `false` to suppress it.- * Defaults to `true` so the All / mixed-group view keeps the hint.- */- showTabHint?: boolean-}--export function MenuFilterHeader({ title, onBack, className, showTabHint = true }: MenuFilterHeaderProps): JSX.Element {- return (- <div- className={cn('flex items-center gap-2 px-3 py-2 border-b text-sm font-semibold shrink-0', className)}- data-slot="menu-filter-header"- >- <Button- type="button"- variant="outline"- size="sm"- aria-label="Go back"- onClick={onBack}- className="-ml-1 shrink-0 gap-1"- data-attr="menu-filter-back"- >- Go back- </Button>- <span className="flex-1 truncate">{title}</span>-- <div className="items-center gap-2 text-xs hidden @[720px]/main-content-container:flex">- {showTabHint && (- <>- <Kbd>Tab</Kbd>{' '}- <span className="text-muted-foreground font-normal">Cycle through categories</span>- </>- )}- <Kbd>Esc</Kbd> <span className="text-muted-foreground font-normal">Go back one level</span>- </div>- </div>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/HogQLEditor.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/HogQLEditor.tsxdeleted file mode 100644index cbbf388befe8..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/HogQLEditor.tsx+++ /dev/null@@ -1,138 +0,0 @@-/**- * HogQL expression editor — opens directly from the dropdown menu, no- * combobox stop-over. Save commits `{ name, value }` derived from the- * expression.- *- * The Monaco editor (`CodeEditorInline`) is loaded lazily so the- * Monaco bundle isn't pulled into the main chunk just to keep the- * filter menu warm. While the chunk loads, a Skeleton fills the- * editor slot. Esc and ⌘+Enter are wired through Monaco's command- * registry — Esc only fires `onBack` when no suggestion / find- * widget is open so it still closes those first like users expect.- */-import { Suspense, useEffect, useRef, useState } from 'react'--import { Button, DialogFooter, Field, FieldContent, FieldDescription, FieldLabel, Skeleton } from '@posthog/quill'--import { Link } from 'lib/lemon-ui/Link'-import { lazyWithRetry } from 'lib/utils/retryImport'--import { useTaxonomicFilterContext } from '../headless/context'-import { TaxonomicFilterGroupType } from '../types'-import { MenuFilterHeader } from './Header'-import { CommitFn, MenuFilterEntry } from './types'--const CodeEditorInline = lazyWithRetry(() =>- import('lib/monaco/CodeEditorInline').then((m) => ({ default: m.CodeEditorInline }))-)--const EXAMPLE_HINTS = `Enter SQL expression, such as:-- properties.$current_url-- person.properties.email-- toInt(properties.\`Long Field Name\`) * 10-- concat(event, ' ', distinct_id)`--export interface MenuFilterHogQLEditorProps {- onCommit: CommitFn- onBack: () => void- /** Pre-fill the editor (e.g. when re-editing an existing expression). */- initialExpression?: string-}--export function MenuFilterHogQLEditor({- onCommit,- onBack,- initialExpression = '',-}: MenuFilterHogQLEditorProps): JSX.Element {- const { groups } = useTaxonomicFilterContext()- const [expression, setExpression] = useState(initialExpression)- // Monaco's `addAction` registers handlers at editor-mount time and- // captures whatever `onPressCmdEnter` referenced then. Without a ref- // we'd permanently call the first render's `commit` (with the- // initial empty expression), which is why ⌘+Enter looked broken.- const expressionRef = useRef(expression)- useEffect(() => {- expressionRef.current = expression- }, [expression])-- const group = groups.find((g) => g.type === TaxonomicFilterGroupType.HogQLExpression)-- const commit = (raw: string): void => {- // When Cmd+Enter fires without a selection, Monaco passes an- // empty string as `highlightedText`. Fall back to the live- // editor value via the ref so the save still goes through.- const value = raw.length > 0 ? raw : expressionRef.current- const trimmed = value.trim()- if (!trimmed || !group) {- return- }- const entry: MenuFilterEntry = {- item: { name: trimmed, value: trimmed } as never,- group,- name: trimmed,- }- onCommit(entry, { name: trimmed, value: trimmed })- }-- return (- <div className="flex flex-col flex-1 min-h-0">- <MenuFilterHeader title="Write SQL expression" onBack={onBack} />- <div className="flex flex-col flex-1 min-h-0">- <div className="flex flex-col gap-4 p-4 flex-1 min-h-0 overflow-y-auto">- <Field>- <FieldLabel>Expression</FieldLabel>- <FieldContent className="gap-4">- <Suspense fallback={<Skeleton className="h-[120px] w-full rounded-md" />}>- <CodeEditorInline- value={expression}- onChange={(v) => setExpression(v ?? '')}- language="hogQLExpr"- minHeight="120px"- autoFocus- onPressCmdEnter={(value) => commit(value)}- onMount={(editor, monaco) => {- // Esc → onBack, but only when Monaco- // isn't in a state where Esc has its- // own meaning (suggestions, find,- // snippet) — otherwise we'd swallow- // intellisense dismissal.- editor.addCommand(- monaco.KeyCode.Escape,- () => onBack(),- '!suggestWidgetVisible && !findWidgetVisible && !inSnippetMode'- )- }}- />- </Suspense>- <FieldDescription>- <pre className="text-xs text-secondary whitespace-pre-wrap font-mono leading-snug m-0">- {EXAMPLE_HINTS}- </pre>- <div className="mt-2 text-xs">- <Link- to="https://posthog.com/docs/sql"- target="_blank"- className="underline text-primary"- >- Learn more about SQL- </Link>- </div>- <div className="mt-2 text-xs text-tertiary">- Esc goes back without saving. ⌘+Enter saves.- </div>- </FieldDescription>- </FieldContent>- </Field>- </div>- <DialogFooter>- <Button variant="outline" onClick={onBack}>- Cancel- </Button>- <Button variant="primary" disabled={!expression.trim()} onClick={() => commit(expression)}>- Add SQL expression- </Button>- </DialogFooter>- </div>- </div>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/InputTrigger.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/InputTrigger.tsxdeleted file mode 100644index aedf2ed900e1..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/InputTrigger.tsx+++ /dev/null@@ -1,62 +0,0 @@-import { ReactElement } from 'react'--/**- * Replay-style trigger for the rebuilt taxonomic menu: a LemonInput search box- * with a leading filter-icon button. Focusing/typing in the box opens the- * combobox; clicking the icon opens the dropdown menu.- *- * LemonInput (not quill) so the trigger matches the surrounding scene's UI. The- * combobox internals stay quill; when it opens, the popover panel renders its- * own live search field (header above, list below) positioned over this row, so- * here we render an invisible same-height spacer to hold the anchor in place- * and avoid a layout shift behind the panel.- */-import { LemonInput } from 'lib/lemon-ui/LemonInput'--export interface MenuInputTriggerProps {- iconButton: ReactElement- placeholder?: string- value?: string- onChange?: (value: string) => void- onFocus?: () => void- fullWidth?: boolean- /** While the combobox panel is open it owns the visible field; the row- * holds an invisible spacer so the trigger anchor and layout don't shift. */- spacerOnly?: boolean-}--export function MenuInputTrigger({- iconButton,- placeholder,- value,- onChange,- onFocus,- fullWidth = true,- spacerOnly = false,-}: MenuInputTriggerProps): JSX.Element {- if (spacerOnly) {- return (- <div aria-hidden="true">- <LemonInput- fullWidth={fullWidth}- size="small"- disabled- placeholder={placeholder}- className="invisible"- />- </div>- )- }- return (- <LemonInput- fullWidth={fullWidth}- size="small"- prefix={iconButton}- data-attr="taxonomic-filter-menu-input"- placeholder={placeholder}- value={value}- onChange={onChange}- onFocus={onFocus}- />- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/MatchedValueBadge.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/MatchedValueBadge.test.tsxdeleted file mode 100644index 3124ab70ab21..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/MatchedValueBadge.test.tsx+++ /dev/null@@ -1,40 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, screen } from '@testing-library/react'--import { getMatchedValue, MatchedValueBadge } from './MatchedValueBadge'-import { MenuFilterEntry } from './types'--function makeEntry(item: Record<string, any>): MenuFilterEntry {- return {- item,- group: { type: 'log_attributes', name: 'Log attributes' },- name: item.name ?? 'attr',- } as unknown as MenuFilterEntry-}--describe('MatchedValueBadge', () => {- afterEach(cleanup)-- it('renders the matched value when the item matched on value', () => {- render(<MatchedValueBadge entry={makeEntry({ name: 'level', matchedOn: 'value', matchedValue: 'error' })} />)- expect(screen.getByLabelText('Matched on value')).toHaveTextContent('error')- })-- it('truncates long matched values', () => {- const long = 'a'.repeat(40)- render(<MatchedValueBadge entry={makeEntry({ name: 'level', matchedOn: 'value', matchedValue: long })} />)- expect(screen.getByLabelText('Matched on value')).toHaveTextContent('…')- })-- it.each([- ['matched on name', { name: 'level', matchedOn: 'name', matchedValue: 'error' }],- ['no matchedValue', { name: 'level', matchedOn: 'value' }],- ['empty matchedValue', { name: 'level', matchedOn: 'value', matchedValue: '' }],- ['plain attribute', { name: 'level' }],- ])('renders nothing for %s', (_label, item) => {- const { container } = render(<MatchedValueBadge entry={makeEntry(item)} />)- expect(container).toBeEmptyDOMElement()- expect(getMatchedValue(makeEntry(item))).toBeNull()- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/MatchedValueBadge.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/MatchedValueBadge.tsxdeleted file mode 100644index 1c943ced045d..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/MatchedValueBadge.tsx+++ /dev/null@@ -1,61 +0,0 @@-/**- * "Matched on value" badge for taxonomic filter rows + preview pane.- *- * Some groups (log / resource attributes) search attribute *values* as well- * as names via `search_values=true`. When a row surfaces because the query- * matched one of its values — not the attribute name — the endpoint tags the- * item with `matchedOn: 'value'` and the `matchedValue`. Surfacing it tells- * the user why an attribute appears for a query that isn't in its name.- */-import { Badge, cn, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'--import { MenuFilterEntry } from './types'--const VALUE_MATCH_MAX_LENGTH = 30--export function getMatchedValue(entry: MenuFilterEntry): string | null {- const item = entry.item as { matchedOn?: string; matchedValue?: string } | null- if (item && item.matchedOn === 'value' && typeof item.matchedValue === 'string' && item.matchedValue.length > 0) {- return item.matchedValue- }- return null-}--export function MatchedValueBadge({- entry,- className,-}: {- entry: MenuFilterEntry- className?: string-}): JSX.Element | null {- const matchedValue = getMatchedValue(entry)- if (!matchedValue) {- return null- }- const truncated =- matchedValue.length > VALUE_MATCH_MAX_LENGTH- ? matchedValue.slice(0, VALUE_MATCH_MAX_LENGTH) + '…'- : matchedValue- return (- <Tooltip>- {/* Trigger must render a host element so base-ui's hover ref attaches —- `Badge` is a plain component (not forwardRef). See VerificationBadge. */}- <TooltipTrigger- delay={300}- render={(triggerProps) => (- <span {...triggerProps} className={cn('inline-flex min-w-0', className)}>- <Badge- variant="default"- aria-label="Matched on value"- data-attr="taxonomic-value-match-indicator"- className="max-w-48 shrink-0 truncate font-mono"- >- {truncated}- </Badge>- </span>- )}- />- <TooltipContent className="max-w-64">Matched on value: "{matchedValue}"</TooltipContent>- </Tooltip>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/PreviewPane.test.ts b/frontend/src/lib/components/TaxonomicFilter/menu/PreviewPane.test.tsdeleted file mode 100644index 2eba1a649644..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/PreviewPane.test.ts+++ /dev/null@@ -1,37 +0,0 @@-import { urls } from 'scenes/urls'--import type { propertyDefinitionsModelType } from '~/models/propertyDefinitionsModel'-import { PropertyDefinition } from '~/types'--import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'-import { resolveViewUrl } from './PreviewPane'-import { MenuFilterEntry } from './types'--// resolveViewUrl is the rebuild's separate implementation of the legacy-// definitionPopoverLogic.viewFullDetailUrl selector — no test enforces parity-// between the two. Per-type id recovery lives in (and is tested via)-// resolvePropertyDefinitionId; these cases only guard that the rebuild delegates-// to it and hides the link when nothing resolves (the /properties/undefined regression).-describe('resolveViewUrl', () => {- const entry = (type: TaxonomicFilterGroupType, item: Partial<PropertyDefinition>): MenuFilterEntry =>- ({ item, group: { type } as TaxonomicFilterGroup, name: String(item.name ?? '') }) as MenuFilterEntry-- it('builds the property URL from the recovered id for a name-only item', () => {- const getPropertyDefinition = ((name) =>- name === '$current_url'- ? ({ name, id: 'event-url-id' } as PropertyDefinition)- : null) as propertyDefinitionsModelType['values']['getPropertyDefinition']-- const url = resolveViewUrl(- entry(TaxonomicFilterGroupType.EventProperties, { name: '$current_url' }),- getPropertyDefinition- )-- expect(url).toBe(urls.propertyDefinition('event-url-id'))- })-- it('stays undefined when a name-only property cannot be resolved', () => {- const url = resolveViewUrl(entry(TaxonomicFilterGroupType.EventProperties, { name: 'never-saved' }), () => null)- expect(url).toBeUndefined()- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/PreviewPane.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/PreviewPane.tsxdeleted file mode 100644index 9bc35a5f4e14..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/PreviewPane.tsx+++ /dev/null@@ -1,211 +0,0 @@-/**- * Preview pane — right column of the combobox panel. Shows metadata for- * the currently highlighted row (description, property type, sent-as,- * pin / view, action match groups). Hidden on narrow viewports- * (`md:flex`); list takes the full popover on mobile.- *- * Quill-native re-render of the legacy- * `lib/components/DefinitionPopover/DefinitionPopoverContents.tsx`.- * Properties / events / actions render specific extras; everything else- * falls back to the shared header + description.- */-import { useValues } from 'kea'-import posthog from 'posthog-js'--import { IconPin } from '@posthog/icons'-import { Button, cn, ScrollArea, Separator } from '@posthog/quill'--import { FlagCalledMoveNotice } from 'lib/components/FlagCalledMoveNotice/FlagCalledMoveNotice'-import { resolvePropertyDefinitionId } from 'lib/components/PropertyFilters/utils'-import { Link } from 'lib/lemon-ui/Link'-import { urls } from 'scenes/urls'--import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'-import { ActionType, CohortType, EventDefinition, PropertyDefinition } from '~/types'--import { useTaxonomicAutocompleteItemDetails } from '../headless'-import { TaxonomicFilterGroupType } from '../types'-import { getMatchedValue } from './MatchedValueBadge'-import { ActionMatchGroups } from './preview/ActionMatchGroups'-import { MenuFilterEntry } from './types'-import { VerificationBadge } from './VerificationBadge'--export interface PreviewPaneProps {- /** Highlighted entry, or `null` when nothing is highlighted. */- entry: MenuFilterEntry | null- className?: string-}--export function PreviewPane({ entry, className }: PreviewPaneProps): JSX.Element {- return (- <div className={cn('min-w-0 min-h-0', className)} data-slot="menu-filter-preview" aria-live="polite">- {entry ? <PreviewBody entry={entry} /> : <PreviewEmpty />}- </div>- )-}--function PreviewEmpty(): JSX.Element {- return (- <div className="flex flex-1 items-center justify-center p-4 text-xs text-secondary text-center">- Highlight an item to see details.- </div>- )-}--function PreviewBody({ entry }: { entry: MenuFilterEntry }): JSX.Element | null {- const details = useTaxonomicAutocompleteItemDetails(entry)- const { getPropertyDefinition } = useValues(propertyDefinitionsModel)- if (!details) {- return null- }-- // Action-specific match groups (`steps`) live on the entry's item, not- // in the shared hook — the hook only models scalar metadata. Same- // for event first/last seen (handled later if needed).- const isAction = entry.group.type === TaxonomicFilterGroupType.Actions- const viewUrl = resolveViewUrl(entry, getPropertyDefinition)- const matchedValue = getMatchedValue(entry)-- return (- <ScrollArea className="flex-1 min-h-0">- <div className="flex flex-col gap-3 p-3 text-sm">- <PreviewHeader details={details} viewUrl={viewUrl} entry={entry} />-- {details.description ? (- <p className="text-xs leading-relaxed text-secondary">{details.description}</p>- ) : (- <p className="text-xs italic text-tertiary">No description.</p>- )}-- <FlagCalledMoveNotice- name={entry.name}- groupType={entry.group.type}- className="text-xs leading-relaxed"- />-- {details.example && <p className="text-xs italic text-secondary">Example: {details.example}</p>}-- {details.propertyType && (- <div className="flex flex-col gap-0.5 border-t pt-2">- <div className="text-xxs uppercase tracking-wide text-secondary">Property type</div>- <div className="text-xs">{details.propertyType}</div>- </div>- )}-- {matchedValue && (- <div className="flex flex-col gap-0.5 border-t pt-2">- <div className="text-xxs uppercase tracking-wide text-secondary">Matched on value</div>- <code className="break-all font-mono text-xs text-tertiary">{matchedValue}</code>- </div>- )}-- {isAction && <ActionMatchGroups item={entry.item} />}- </div>- </ScrollArea>- )-}--interface PreviewHeaderProps {- details: ReturnType<typeof useTaxonomicAutocompleteItemDetails>- /** Data management URL for the definition, or `undefined` to hide. */- viewUrl: string | undefined- /** Highlighted entry — drives the verification badge. */- entry: MenuFilterEntry-}--function PreviewHeader({ details, viewUrl, entry }: PreviewHeaderProps): JSX.Element | null {- if (!details) {- return null- }- return (- <div className="flex flex-col gap-4 " data-quill="true">- <div className="flex items-center justify-between gap-2">- <Button- type="button"- variant="outline"- size="sm"- disabled={!details.isPinnable}- aria-pressed={details.isPinned}- onClick={() => {- posthog.capture('taxonomic filter menu pin toggled', {- groupType: entry.group.type,- // Intended next state — `isPinned` still reads- // the pre-toggle value here.- pinned: !details.isPinned,- })- details.togglePin()- }}- >- <IconPin className="size-3.5" />- {details.isPinned ? 'Pinned' : 'Pin'}- </Button>- {viewUrl && (- <Button- variant="link"- className="text-primary"- size="sm"- // The render prop swaps the native <button> for a Link (<a>),- // so tell Base UI not to expect native button semantics.- nativeButton={false}- render={<Link to={viewUrl} target="_blank" className="text-xs underline" />}- >- View- </Button>- )}- </div>- <div className="flex flex-col gap-1">- <div className="text-xxs uppercase tracking-wide text-secondary">{details.groupLabel}</div>- <div className="text-base font-semibold leading-tight break-words">{details.title}</div>- {details.rawName && details.rawName !== details.title && (- <div className="flex items-baseline gap-1 text-xs text-secondary">- <span>Sent as</span>- <code className="break-all font-mono text-tertiary">{details.rawName}</code>- </div>- )}- <VerificationBadge entry={entry} className="mt-1 self-start" />- </div>- <Separator />- </div>- )-}--/**- * Resolve the data-management URL for an entry. Mirrors the legacy- * `definitionPopoverLogic.viewFullDetailUrl` selector — Action / Event /- * Property / Cohort each have their own page; everything else returns- * `undefined` so the link is hidden. Pinned/default property items are- * stored as `{ name }` only, so recover the saved definition id from- * `propertyDefinitionsModel` rather than pointing at `/properties/undefined`.- */-export function resolveViewUrl(- entry: MenuFilterEntry,- getPropertyDefinition: typeof propertyDefinitionsModel.values.getPropertyDefinition-): string | undefined {- const { group, item } = entry- switch (group.type) {- case TaxonomicFilterGroupType.Actions: {- const id = (item as ActionType).id- return id != null ? urls.action(id) : undefined- }- case TaxonomicFilterGroupType.Events:- case TaxonomicFilterGroupType.CustomEvents: {- const id = (item as EventDefinition).id- return id ? urls.eventDefinition(id) : undefined- }- case TaxonomicFilterGroupType.EventProperties:- case TaxonomicFilterGroupType.PersonProperties:- case TaxonomicFilterGroupType.SessionProperties:- case TaxonomicFilterGroupType.EventMetadata:- case TaxonomicFilterGroupType.EventFeatureFlags: {- const id = resolvePropertyDefinitionId(item as PropertyDefinition, group.type, getPropertyDefinition)- return id ? urls.propertyDefinition(id) : undefined- }- case TaxonomicFilterGroupType.Cohorts:- case TaxonomicFilterGroupType.CohortsWithAllUsers: {- const id = (item as CohortType).id- return id != null ? urls.cohort(id) : undefined- }- default:- return undefined- }-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.inputTrigger.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.inputTrigger.test.tsxdeleted file mode 100644index f442c81f0768..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.inputTrigger.test.tsx+++ /dev/null@@ -1,117 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { Provider } from 'kea'--import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { groupsModel } from '~/models/groupsModel'-import { performQuery } from '~/queries/query'-import { initKeaTests } from '~/test/init'-import { emptyPaginated } from '~/test/mocks/taxonomicFilterApiMock'--import { TaxonomicFilterHeadless } from '../headless'-import { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'-import { TaxonomicFilterGroupType } from '../types'-import { TaxonomicFilterMenu } from './TaxonomicFilterMenu'--jest.mock('~/queries/query', () => ({- performQuery: jest.fn(),-}))--jest.mock('posthog-js', () => ({- __esModule: true,- default: { capture: jest.fn() },-}))--jest.mock('lib/api', () => require('~/test/mocks/taxonomicFilterApiMock').buildTaxonomicFilterApiMock())--const apiGet = jest.requireMock('lib/api').default.get as jest.MockedFunction<any>--const GROUP_TYPES = [- TaxonomicFilterGroupType.EventProperties,- TaxonomicFilterGroupType.PersonProperties,- TaxonomicFilterGroupType.HogQLExpression,-]--function renderInputTriggerMenu(): ReturnType<typeof render> {- return render(- <Provider>- <TaxonomicFilterHeadless.Root taxonomicGroupTypes={GROUP_TYPES} onChange={jest.fn()}>- <TaxonomicFilterMenu triggerVariant="input" />- </TaxonomicFilterHeadless.Root>- </Provider>- )-}--describe('TaxonomicFilterMenu input trigger', () => {- beforeEach(() => {- __clearTaxonomicResourceCache()- apiGet.mockReset()- apiGet.mockImplementation(emptyPaginated)- ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })- useMocks({})- initKeaTests()- actionsModel.mount()- groupsModel.mount()- })-- afterEach(() => cleanup())-- it('renders a text input and a filter-icon menu button instead of a single button', () => {- renderInputTriggerMenu()-- expect(screen.getByTestId('taxonomic-filter-menu-input')).toBeInTheDocument()- expect(screen.getByRole('textbox')).toBeInTheDocument()- expect(screen.getByLabelText('Open filter menu')).toBeInTheDocument()- })-- it('opens the dropdown menu (without a redundant "New filter…" item) when the filter icon is clicked', async () => {- renderInputTriggerMenu()-- await userEvent.click(screen.getByLabelText('Open filter menu'))-- // The menu opens — its always-present "HogQL expression" entry confirms it.- await waitFor(() => {- expect(screen.getByTestId('taxonomic-filter-menu-hogql')).toBeInTheDocument()- })- // Typing in the box replaces "New filter…", so it must not be offered.- expect(screen.queryByTestId('taxonomic-filter-menu-new')).not.toBeInTheDocument()- expect(screen.queryByText('New filter…')).not.toBeInTheDocument()- // The icon opens the menu, NOT the combobox — guards the `stopPropagation`- // that keeps the click from bubbling to the input's focus handler.- expect(screen.queryByTestId('menu-filter-search')).not.toBeInTheDocument()- })-- it('opens the combobox search panel when the input is focused', async () => {- renderInputTriggerMenu()-- await userEvent.click(screen.getByTestId('taxonomic-filter-menu-input'))-- await waitFor(() => {- expect(screen.getByTestId('menu-filter-search')).toBeInTheDocument()- })- // The dropdown menu must not also be open — focusing the input is the- // combobox path, not the menu path.- expect(screen.queryByTestId('taxonomic-filter-menu-hogql')).not.toBeInTheDocument()- })-- it('keeps a single search input — the combobox chrome opens around the trigger box, not a second mirrored input', async () => {- renderInputTriggerMenu()-- await userEvent.click(screen.getByTestId('taxonomic-filter-menu-input'))-- await waitFor(() => {- expect(screen.getByTestId('menu-filter-search')).toBeInTheDocument()- })- // The placeholder trigger input is replaced by the search field, not- // mirrored alongside it — so there's a single live input, not two.- expect(screen.queryByTestId('taxonomic-filter-menu-input')).not.toBeInTheDocument()- // The search field renders in the trigger row beside the filter-icon- // button (chrome opens around it), not adrift in the popover.- const iconButton = screen.getByLabelText('Open filter menu')- const searchInput = screen.getByTestId('menu-filter-search')- expect(iconButton.closest('.LemonInput')).toContainElement(searchInput)- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.pinned.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.pinned.test.tsxdeleted file mode 100644index 1532f24f37bf..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.pinned.test.tsx+++ /dev/null@@ -1,109 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { Provider } from 'kea'--import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { groupsModel } from '~/models/groupsModel'-import { performQuery } from '~/queries/query'-import { initKeaTests } from '~/test/init'-import { emptyPaginated } from '~/test/mocks/taxonomicFilterApiMock'--import { TaxonomicFilterHeadless } from '../headless'-import { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'-import { taxonomicFilterPinnedPropertiesLogic } from '../taxonomicFilterPinnedPropertiesLogic'-import { TaxonomicFilterGroupType } from '../types'-import { TaxonomicFilterMenu } from './TaxonomicFilterMenu'--jest.mock('~/queries/query', () => ({- performQuery: jest.fn(),-}))--jest.mock('posthog-js', () => ({- __esModule: true,- default: { capture: jest.fn() },-}))--jest.mock('lib/api', () => require('~/test/mocks/taxonomicFilterApiMock').buildTaxonomicFilterApiMock())--const apiGet = jest.requireMock('lib/api').default.get as jest.MockedFunction<any>--// Two content groups, so the picker does not take the sole-group path that-// promotes pinned items into the single list.-const GROUP_TYPES = [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.EventProperties]--function renderMenu(): ReturnType<typeof render> {- return render(- <Provider>- <TaxonomicFilterHeadless.Root taxonomicGroupTypes={GROUP_TYPES} onChange={jest.fn()}>- <TaxonomicFilterMenu />- </TaxonomicFilterHeadless.Root>- </Provider>- )-}--function pinnedRowTexts(): string[] {- return Array.from(document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]')).map(- (el) => el.textContent ?? ''- )-}--describe('TaxonomicFilterMenu pinned rows', () => {- beforeEach(() => {- __clearTaxonomicResourceCache()- apiGet.mockReset()- apiGet.mockImplementation(emptyPaginated)- ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })- useMocks({})- localStorage.clear()- initKeaTests()- actionsModel.mount()- groupsModel.mount()- })-- afterEach(() => cleanup())-- // Pins are stored globally, so a pin can outlive the picker it was made in.- // Without the context filter the cohort still renders: resolveShortcutGroup- // falls back to the first non-meta group, so it appears as an Events row and- // commits a cohort id under the Events group.- it('leaves out a pin whose source group this picker does not offer', async () => {- const pinnedLogic = taxonomicFilterPinnedPropertiesLogic.build()- pinnedLogic.mount()- pinnedLogic.actions.setPinnedFilters([- {- groupType: TaxonomicFilterGroupType.Events,- groupName: 'Events',- value: 'signed up',- item: { name: 'signed up' },- timestamp: 0,- },- {- groupType: TaxonomicFilterGroupType.Cohorts,- groupName: 'Cohorts',- value: 1,- item: { name: 'Power users' },- timestamp: 0,- },- ])-- renderMenu()-- await userEvent.click(screen.getByTestId('taxonomic-filter-menu-trigger'))- await waitFor(() => {- expect(screen.getByTestId('taxonomic-filter-menu-new')).toBeInTheDocument()- })- expect(screen.queryByText('Recent')).not.toBeInTheDocument()- expect(screen.queryByText('Pinned')).not.toBeInTheDocument()- await userEvent.click(screen.getByTestId('taxonomic-filter-menu-new'))-- await waitFor(() => {- expect(pinnedRowTexts().length).toBeGreaterThan(0)- })- const rows = pinnedRowTexts()- expect(rows.some((text) => text.includes('signed up'))).toBe(true)- expect(rows.some((text) => text.includes('Power users'))).toBe(false)- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsxdeleted file mode 100644index a15f6658addc..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx+++ /dev/null@@ -1,550 +0,0 @@-import { Meta, StoryObj } from '@storybook/react'-import { useMountedLogic } from 'kea'-import { useState } from 'react'--import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'-import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__mocks__/taxonomicFilterMocksDecorator'-import { FEATURE_FLAGS } from 'lib/constants'--import { mswDecorator } from '~/mocks/browser'-import { toPaginatedResponse } from '~/mocks/handlers'-import { actionsModel } from '~/models/actionsModel'-import { getCoreFilterDefinition } from '~/taxonomy/helpers'-import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'--import { TaxonomicFilterHeadless } from '../headless'-import { DataWarehousePopoverField, TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'-import { MenuFilterCombobox } from './Combobox'-import { MenuFilterDwhConfig } from './DwhFlow'-import { TaxonomicFilterMenu } from './TaxonomicFilterMenu'-import { MenuFilterEntry } from './types'--const meta: Meta = {- title: 'Filters/Taxonomic Filter (Menu rebuild)',- decorators: [taxonomicFilterMocksDecorator],- parameters: {- docs: {- description: {- component:- 'Popover-fronted TaxonomicFilter — dropdown menu for shortcuts, combobox with chips + preview pane for browsing, and dedicated panels for DataWarehouse config and HogQL expression editing. Gated in production by the `taxonomic-filter-menu-rebuild` flag.',- },- },- },- tags: ['autodocs'],-}--export default meta--type Story = StoryObj--interface ContainerProps {- taxonomicGroupTypes: TaxonomicFilterGroupType[]- eventNames?: string[]- suggestedFiltersLabel?: string- /** Pre-seeded selection — the trigger label uses it and the menu routes- * the initial open straight into the panel that owns it. */- initialSelected?: MenuFilterEntry | null- triggerLabel?: string-}--function Container({- taxonomicGroupTypes,- eventNames,- suggestedFiltersLabel,- initialSelected = null,- triggerLabel = 'Filter',-}: ContainerProps): JSX.Element {- useMountedLogic(actionsModel)- const [selected, setSelected] = useState<MenuFilterEntry | null>(initialSelected)-- return (- <div className="flex flex-col gap-3 max-w-2xl">- <TaxonomicFilterHeadless.Root- bindRootProps={false}- taxonomicGroupTypes={taxonomicGroupTypes}- eventNames={eventNames}- suggestedFiltersLabel={suggestedFiltersLabel}- >- <TaxonomicFilterMenu- triggerLabel={triggerLabel}- selected={selected}- onCommit={(entry) => setSelected(entry)}- />- </TaxonomicFilterHeadless.Root>- {selected && (- <div className="text-xs text-secondary">- Selected: <code>{selected.group.type}</code>- {' / '}- <code>{selected.friendlyLabel ?? selected.name}</code>- </div>- )}- </div>- )-}--export const EventsAndActions: Story = {- render: () => (- <Container- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]}- triggerLabel="Pick event or action"- />- ),- parameters: {- docs: {- description: {- story: 'Two-tab combobox. Click the trigger → dropdown menu → "New filter…" → combobox with All / Events / Actions chips.',- },- },- },-}--export const Properties: Story = {- render: () => (- <Container- taxonomicGroupTypes={[- TaxonomicFilterGroupType.EventProperties,- TaxonomicFilterGroupType.PersonProperties,- TaxonomicFilterGroupType.SessionProperties,- TaxonomicFilterGroupType.EventMetadata,- ]}- triggerLabel="Pick property"- />- ),- parameters: {- docs: {- description: {- story: 'Property picker — chips for each property family. The preview pane on the right shows description, type, sent-as, and pin/view actions for the highlighted row.',- },- },- },-}--export const SeriesPlusDataWarehouse: Story = {- render: () => (- <Container- taxonomicGroupTypes={[- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.DataWarehouse,- TaxonomicFilterGroupType.HogQLExpression,- TaxonomicFilterGroupType.EventProperties,- ]}- triggerLabel="Pick series source"- />- ),- parameters: {- docs: {- description: {- story: 'Mirrors the ActionFilterRow series picker — Data warehouse tables and HogQL expression appear as separate dropdown-menu entries (with chevrons) so they bypass the chip row and route directly to their dedicated panels.',- },- },- },-}--export const HogQLOnly: Story = {- render: () => (- <Container- taxonomicGroupTypes={[TaxonomicFilterGroupType.HogQLExpression]}- triggerLabel="Write SQL expression"- />- ),- parameters: {- docs: {- description: {- story: 'Dropdown only shows the HogQL entry — clicking it opens the lazy-loaded Monaco editor. ⌘+Enter saves; Esc returns to the menu (and falls through to suggestions / find widgets first).',- },- },- },-}--export const PreSelectedEvent: Story = {- render: () => (- <Container- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]}- initialSelected={- {- item: { name: '$pageview', id: '$pageview' },- group: { type: TaxonomicFilterGroupType.Events },- name: '$pageview',- friendlyLabel: 'Pageview',- } as unknown as MenuFilterEntry- }- triggerLabel="Pick event"- />- ),- parameters: {- docs: {- description: {- story: 'Trigger pre-seeded with a selection — clicking the trigger jumps straight into the combobox with the matching chip active and the row highlighted + checkmarked + scrolled into view.',- },- },- },-}--export const PreSelectedHogQL: Story = {- render: () => (- <Container- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.HogQLExpression]}- initialSelected={- {- item: { name: "properties.$browser = 'Chrome'" },- group: { type: TaxonomicFilterGroupType.HogQLExpression },- name: "properties.$browser = 'Chrome'",- } as unknown as MenuFilterEntry- }- triggerLabel="Pick filter"- />- ),- parameters: {- docs: {- description: {- story: 'Pre-existing HogQL expression — re-opening lands directly on the Monaco editor pre-filled with the saved expression for editing.',- },- },- },-}--// ---- DataWarehouse config story ---------------------------------------// Renders `<MenuFilterDwhConfig>` directly so the DWH interface is the-// initial visible surface — no need to click through the trigger /-// dropdown menu first. Useful as a focused debug surface for layout +-// the DatabaseTablePreview / Tabs / Select / HogQL fallback chrome.--const COMPLEX_DWH_TABLE = {- name: 'chargebee.customers',- type: 'data_warehouse',- fields: {- id: { name: 'id', type: 'string' },- mrr: { name: 'mrr', type: 'integer' },- email: { name: 'email', type: 'string' },- phone: { name: 'phone', type: 'string' },- object: { name: 'object', type: 'string' },- channel: { name: 'channel', type: 'string' },- first_invoiced_at: { name: 'first_invoiced_at', type: 'datetime' },- created_at: { name: 'created_at', type: 'datetime' },- updated_at: { name: 'updated_at', type: 'datetime' },- ltv: { name: 'ltv', type: 'decimal' },- is_active: { name: 'is_active', type: 'boolean' },- metadata: { name: 'metadata', type: 'string' },- // Linked tables to demo the linked-tables hint in HogQL fallback.- person_distinct_ids: { name: 'person_distinct_ids', type: 'lazy_table' },- events: { name: 'events', type: 'view' },- },-}--const DWH_GROUP: TaxonomicFilterGroup = {- name: 'Data warehouse tables',- searchPlaceholder: 'data warehouse tables',- type: TaxonomicFilterGroupType.DataWarehouse,- getName: (t: any) => t.name,- getValue: (t: any) => t.name,- getPopoverHeader: () => 'Data warehouse table',-} as unknown as TaxonomicFilterGroup--const COMPLEX_DWH_FIELDS: DataWarehousePopoverField[] = [- {- key: 'aggregation_target_field',- label: 'Aggregation target',- description: 'Used to match people or groups across funnel steps.',- allowHogQL: true,- },- {- key: 'timestamp_field',- label: 'Timestamp',- description: 'Used to order step timing and apply the funnel date range.',- allowHogQL: true,- },- {- key: 'id_field',- label: 'Unique ID',- description: 'Used as the unique row ID to detect duplicate records.',- },-]--function DwhConfigContainer(): JSX.Element {- useMountedLogic(actionsModel)- const [committed, setCommitted] = useState<{ name: string; extras?: Record<string, unknown> } | null>(null)- return (- <div className="flex flex-col gap-3 max-w-3xl">- <TaxonomicFilterHeadless.Root- bindRootProps={false}- taxonomicGroupTypes={[- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.DataWarehouse,- ]}- >- {/* Fixed-size frame so the DwhFlow lays out as it would- inside the popover (h-[400px], w-[720px]) and we can- spot-check the chrome / scroll behaviour. */}- <div className="border rounded overflow-hidden flex flex-col w-[720px] h-[480px] bg-surface-primary">- <MenuFilterDwhConfig- table={COMPLEX_DWH_TABLE as never}- group={DWH_GROUP}- dataWarehousePopoverFields={COMPLEX_DWH_FIELDS}- onCommit={(entry, extras) => setCommitted({ name: entry.name, extras })}- onBack={() => setCommitted(null)}- />- </div>- </TaxonomicFilterHeadless.Root>- {committed && (- <pre className="text-xs text-secondary border rounded p-2 max-w-3xl overflow-auto">- {JSON.stringify(committed, null, 2)}- </pre>- )}- </div>- )-}--export const DataWarehouseConfig: Story = {- render: () => <DwhConfigContainer />,- parameters: {- featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]: true },- testOptions: {- waitForSelector: '[data-attr="dwh-config-back"]',- snapshotTargetSelector: '[data-slot="dialog-content"]',- },- docs: {- description: {- story: 'DataWarehouse config form rendered standalone so it lands on the DWH interface immediately. Wide table with mixed types (string / integer / decimal / datetime / boolean / lazy_table / view) exercises every column-type filter in the dropdowns plus the linked-tables hint in the HogQL fallback. Tabs are configured to mirror the funnel popover (Aggregation target / Timestamp / Unique ID).',- },- },- },-}--// ---- Default "All" surface with recents/pinned ---------------------------// Renders the combobox directly on the `all` scope so the recents-first-// default surface is the initial snapshot (no click-through the dropdown-// menu first). Recents/pinned are synthesized so the order is deterministic.--function recentPinnedEntry(groupType: TaxonomicFilterGroupType, name: string, groupName: string): MenuFilterEntry {- return {- item: { name } as never,- group: {- type: groupType,- name: groupName,- getName: (t: any) => t?.name,- getValue: (t: any) => t?.name,- } as unknown as TaxonomicFilterGroup,- name,- }-}--function DefaultSurfaceContainer(): JSX.Element {- useMountedLogic(actionsModel)- const recentEntries = [- recentPinnedEntry(TaxonomicFilterGroupType.Events, 'signed up', 'Events'),- recentPinnedEntry(TaxonomicFilterGroupType.EventProperties, 'plan', 'Event properties'),- ]- const pinnedEntries = [recentPinnedEntry(TaxonomicFilterGroupType.EventProperties, 'industry', 'Event properties')]- return (- <div className="flex flex-col gap-3 max-w-2xl">- <TaxonomicFilterHeadless.Root- bindRootProps={false}- taxonomicGroupTypes={[- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.EventProperties,- ]}- >- <div className="border rounded overflow-hidden flex flex-col w-[720px] h-[480px] bg-surface-primary">- <MenuFilterCombobox- drillTo="all"- recentEntries={recentEntries}- pinnedEntries={pinnedEntries}- onCommit={() => {}}- onBack={() => {}}- />- </div>- </TaxonomicFilterHeadless.Root>- </div>- )-}--export const DefaultSurfaceWithRecents: Story = {- // Excluded from the snapshot/flake gate: the combobox autofocuses, fetches- // content lists, and the preview pane loads definition metadata async, so- // the render isn't pixel-stable across runs. Kept for the Storybook demo;- // the recents-first behaviour is covered by RTL in Combobox.test.tsx.- tags: ['test-skip'],- render: () => <DefaultSurfaceContainer />,- parameters: {- docs: {- description: {- story: 'The default "All" surface staff land on, brought in line with the pill variant: recents lead, then pinned, then the cross-tab content in fixed (learnable) order. Recent/pinned rows are tagged with their source (e.g. "Events - recent"), and saved items stay in All without separate Recent and Pinned category options.',- },- },- },-}--// ---- Renamed series selection --------------------------------------------// Renders the combobox directly on the `all` scope with a committed selection-// whose series carries a rename: the promoted first row is labelled with the-// rename ("Completed sign-up") and keeps the raw event key visible beneath it.--function RenamedSeriesSelectionContainer(): JSX.Element {- useMountedLogic(actionsModel)- const selectedEntry: MenuFilterEntry = {- item: { name: 'signed up', id: 'signed up' } as never,- group: {- type: TaxonomicFilterGroupType.Events,- name: 'Events',- getName: (t: any) => t?.name,- getValue: (t: any) => t?.name ?? t?.id,- } as unknown as TaxonomicFilterGroup,- name: 'signed up',- }- return (- <TaxonomicFilterHeadless.Root- bindRootProps={false}- taxonomicGroupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]}- >- <div className="border rounded overflow-hidden flex flex-col w-[720px] h-[420px] bg-surface-primary">- <MenuFilterCombobox- drillTo="all"- selectedEntry={selectedEntry}- selectedRename={{ label: 'Completed sign-up', raw: 'signed up' }}- onCommit={() => {}}- onBack={() => {}}- />- </div>- </TaxonomicFilterHeadless.Root>- )-}--export const RenamedSeriesSelection: Story = {- // Excluded from the snapshot/flake gate for the same reason as- // DefaultSurfaceWithRecents: the `all` scope fetches content lists and the- // preview pane loads async, so the render isn't pixel-stable. Kept for the- // Storybook demo; the rename labelling is covered by RTL in Combobox.test.tsx.- tags: ['test-skip'],- render: () => <RenamedSeriesSelectionContainer />,- parameters: {- docs: {- description: {- story: 'Reopening the rebuilt menu on a renamed series: the committed selection is promoted to the first row, labelled with the series\' rename ("Completed sign-up") while the raw `signed up` event key stays inline beneath it, with the checkmark and preview pane tracking the same row.',- },- },- },-}--function bareKeyRecentEntries(): MenuFilterEntry[] {- const group = {- type: TaxonomicFilterGroupType.EventProperties,- name: 'Event properties',- getName: (item: { name?: string }) => item?.name,- getValue: (item: { name?: string }) => item?.name,- } as unknown as TaxonomicFilterGroup- const friendlyLabel = getCoreFilterDefinition('$browser', TaxonomicFilterGroupType.EventProperties)?.label- const propertyFilter: AnyPropertyFilter = {- type: PropertyFilterType.Event,- key: '$browser',- operator: PropertyOperator.Exact,- value: 'Chrome',- }- const bareKey = { item: { name: '$browser' }, group, name: '$browser', friendlyLabel } as MenuFilterEntry- const full = {- item: { name: '$browser' },- group,- name: '$browser',- friendlyLabel,- recentPropertyFilter: propertyFilter,- recentLabel: formatPropertyLabel(propertyFilter, {}),- } as MenuFilterEntry- return [bareKey, full]-}--function BareKeyRecentsContainer(): JSX.Element {- useMountedLogic(actionsModel)- return (- <TaxonomicFilterHeadless.Root- bindRootProps={false}- taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}- >- <div className="border rounded overflow-hidden flex flex-col w-[720px] h-[420px] bg-surface-primary">- <MenuFilterCombobox- drillTo="recent"- drillItems={bareKeyRecentEntries()}- title="Recent"- onCommit={() => {}}- onBack={() => {}}- />- </div>- </TaxonomicFilterHeadless.Root>- )-}--export const RecentsBareKeyExpansion: Story = {- render: () => <BareKeyRecentsContainer />,- parameters: {- testOptions: { waitForSelector: '[data-slot="menu-filter-preview"]' },- docs: {- description: {- story: "The menu combobox's Recent drill after a complete recent (`Browser = Chrome`) was used. The bare key (`Browser`) leads so a user can jump to the key and pick a fresh value, and the full recent (`Browser = Chrome`) follows.",- },- },- },-}--function CohortRowsContainer(): JSX.Element {- useMountedLogic(actionsModel)- return (- <TaxonomicFilterHeadless.Root- bindRootProps={false}- taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]}- // The opt-in a feature flag's release conditions set; no other picker tags cohorts.- showCohortFlagTargeting- >- <div className="border rounded overflow-hidden flex flex-col w-[720px] h-[420px] bg-surface-primary">- <MenuFilterCombobox- drillTo={TaxonomicFilterGroupType.Cohorts}- title="Cohorts"- onCommit={() => {}}- onBack={() => {}}- />- </div>- </TaxonomicFilterHeadless.Root>- )-}--export const CohortsWithRealtimeStates: Story = {- render: () => <CohortRowsContainer />,- decorators: [- mswDecorator({- get: {- '/api/projects/:team_id/cohorts/': toPaginatedResponse([- {- id: 1,- name: 'Viewed pricing this week',- count: 4321,- is_static: false,- realtime: { state: 'ready', ready_at: '2023-07-03T09:40:00Z', build: null },- },- {- id: 2,- name: 'Completed onboarding',- count: 210,- is_static: false,- realtime: {- state: 'building',- ready_at: null,- build: { phase: 'scanning', percent_complete: 45, updated_at: '2023-07-03T23:58:00Z' },- },- },- { id: 3, name: 'Signed up last month', count: 1200, is_static: false, realtime: null },- ]),- },- }),- ],- parameters: {- featureFlags: [FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING],- // The preparing cohort's tag holds a spinner while its build runs, so the runner cannot- // wait for every loader to disappear here.- testOptions: { waitForLoadersToDisappear: false, waitForSelector: '[data-attr="cohort-realtime-tag"]' },- docs: {- description: {- story: 'Cohort rows carry the same realtime tag the classic list shows, so someone picking a cohort for a feature flag sees which ones flags can already target.',- },- },- },-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.test.ts b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.test.tsdeleted file mode 100644index 9e76895a26c4..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { TaxonomicFilterGroupType } from '../types'-import { eventSelectionWasStale, resolveInitialMenuState, resolveSelectedOpenState } from './TaxonomicFilterMenu'-import { MenuFilterEntry, MenuFilterState } from './types'--const entryFor = (type: TaxonomicFilterGroupType): MenuFilterEntry =>- ({ item: { id: 'a', name: 'a' }, group: { type }, name: 'a' }) as unknown as MenuFilterEntry--describe('eventSelectionWasStale', () => {- const staleEvent = { name: 'old', last_seen_at: '2000-01-01T00:00:00Z' } as any- const freshEvent = { name: 'new', last_seen_at: new Date().toISOString() } as any-- it.each([- ['stale event definition', TaxonomicFilterGroupType.Events, staleEvent, true],- ['fresh event definition', TaxonomicFilterGroupType.Events, freshEvent, false],- ['stale custom-event definition', TaxonomicFilterGroupType.CustomEvents, staleEvent, true],- ['non-event group', TaxonomicFilterGroupType.EventProperties, staleEvent, undefined],- ['event row without last_seen_at', TaxonomicFilterGroupType.Events, { name: 'x' }, undefined],- ])('%s -> %s', (_label, groupType, item, expected) => {- expect(eventSelectionWasStale(groupType as TaxonomicFilterGroupType, item)).toBe(expected)- })-})--describe('resolveSelectedOpenState', () => {- const hogqlEntry = entryFor(TaxonomicFilterGroupType.HogQLExpression)- const dwhEntry = entryFor(TaxonomicFilterGroupType.DataWarehouse)- const eventEntry = entryFor(TaxonomicFilterGroupType.Events)-- it.each<[string, MenuFilterEntry | null, MenuFilterState]>([- ['no selection -> menu', null, { kind: 'menu' }],- ['hogql selection -> hogql editor', hogqlEntry, { kind: 'hogql-edit' }],- [- 'data warehouse selection -> dwh config (origin menu)',- dwhEntry,- { kind: 'dwh-config', table: dwhEntry.item, group: dwhEntry.group, origin: 'menu' },- ],- ['other selection -> combobox all', eventEntry, { kind: 'combobox', drillTo: 'all' }],- ])('%s', (_label, selected, expected) => {- expect(resolveSelectedOpenState(selected)).toEqual(expected)- })-})--describe('resolveInitialMenuState', () => {- const hogqlEntry = entryFor(TaxonomicFilterGroupType.HogQLExpression)-- it.each<[string, boolean, 'menu' | 'combobox' | undefined, MenuFilterEntry | null, MenuFilterState]>([- ['closed when not defaultOpen', false, undefined, null, { kind: 'closed' }],- ['not defaultOpen ignores defaultOpenState and selection', false, 'combobox', hogqlEntry, { kind: 'closed' }],- ['defaultOpenState combobox -> combobox all', true, 'combobox', null, { kind: 'combobox', drillTo: 'all' }],- ['defaultOpenState menu -> menu', true, 'menu', null, { kind: 'menu' }],- ['no defaultOpenState falls back to selection (none -> menu)', true, undefined, null, { kind: 'menu' }],- ['no defaultOpenState falls back to selection (hogql)', true, undefined, hogqlEntry, { kind: 'hogql-edit' }],- ])('%s', (_label, defaultOpen, defaultOpenState, selected, expected) => {- expect(resolveInitialMenuState(defaultOpen, defaultOpenState, selected)).toEqual(expected)- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsxdeleted file mode 100644index 53fc7023659c..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx+++ /dev/null@@ -1,928 +0,0 @@-/**- * Dropdown-menu-fronted taxonomic filter.- *- * See `../headless/UX_SPEC.md` for the design.- *- * Architecture:- * - One state machine at the top (`MenuFilterState`).- * - Trigger button is anchor for both the dropdown menu (small list- * options) and the popover (data panels). The DropdownMenuTrigger- * is the visible button; PopoverTrigger is a transparent overlay- * used solely as a Floating UI anchor.- * - Popover dismiss treats clicks on the underlying trigger button as- * "outside" since the PopoverTrigger overlay isn't the click target.- * We cancel that specific outsidePress in `onOpenChange` so the- * popover doesn't immediately re-close when we route a `selected`- * user straight into a panel.- * - Each panel (Combobox / DwhConfig / HogQL) is a pure component; it- * receives data + callbacks.- *- * Consumer wraps it in `<TaxonomicFilterHeadless.Root>` so we can read- * `groups` + `selectItem` via context (same orchestrator the legacy /- * old headless components use).- */-import { useValues } from 'kea'-import posthog from 'posthog-js'-import { ReactElement, useCallback, useEffect, useMemo, useRef, useState } from 'react'--import { IconChevronRight, IconFilter } from '@posthog/icons'-import {- Button,- cn,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,- Popover,- PopoverContent,- PopoverTrigger,-} from '@posthog/quill'--import type { SeriesRename } from 'lib/components/EntityFilterInfo'-import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'-import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { isDefinitionStale } from 'lib/utils/definitions'--import { getCoreFilterDefinition } from '~/taxonomy/helpers'-import { AnyPropertyFilter, EventDefinition } from '~/types'--import { useTaxonomicFilterContext } from '../headless/context'-import { recentTaxonomicFiltersLogic } from '../recentTaxonomicFiltersLogic'-import { taxonomicFilterPinnedPropertiesLogic } from '../taxonomicFilterPinnedPropertiesLogic'-import {- isQuickFilterItem,- META_GROUP_TYPES,- TaxonomicDefinitionTypes,- TaxonomicFilterGroupType,- TaxonomicFilterValue,-} from '../types'-import { filterPinnedForContext, filterRecentsForContext } from '../utils/suggestedContextFilters'-import { MenuFilterCombobox } from './Combobox'-import { MenuFilterDwhConfig } from './DwhFlow'-import { MenuFilterHogQLEditor } from './HogQLEditor'-import { MenuInputTrigger } from './InputTrigger'-import { taxonomicTriggerWrapperClassName } from './triggerLayout'-import {- CommitFn,- DrillCategory,- MenuFilterEntry,- MenuFilterState,- TAXONOMIC_FILTER_SURFACE,- TaxonomicFilterGroup,-} from './types'--export interface TaxonomicFilterMenuProps {- /** Default trigger label when nothing is selected. */- triggerLabel?: string- /** Currently-selected entry — drives the trigger label. Optional. */- selected?: MenuFilterEntry | null- /** Rename (custom name) carried by the series being edited — applied to the selected row in the combobox. */- selectedRename?: SeriesRename | null- /**- * Trigger override. Static element or render function receiving- * trigger state.- */- trigger?: ReactElement | ((state: TriggerState) => ReactElement)- /** Called whenever the user commits a selection. */- onCommit?: CommitFn- /** Search input placeholder in the combobox. */- placeholder?: string- /**- * Heading shown above the combobox panel. Defaults to "Choose filter".- * Consumers like the series picker override this to read e.g.- * "Choose series filter" so the panel matches its surrounding context.- */- comboboxTitle?: string- /** Field tabs the DWH config form should expose (id_field, timestamp_field, …). Defaults to the standard bundle. */- dataWarehousePopoverFields?: import('../types').DataWarehousePopoverField[]- /** Insight context for the DWH config — when set, the aggregation-target tab reads `funnelDataLogic` for funnel-aware copy. */- insightProps?: import('~/types').InsightLogicProps- /**- * Stretch the trigger to its parent's full width. When false (default)- * the trigger sizes to its content and caps at the parent — matching a- * plain inline button so it truncates instead of overflowing a shared- * flex row. Set true for dedicated full-width trigger columns.- */- fullWidthTrigger?: boolean- /**- * Open the menu immediately on mount. Used by consumers that lazily- * mount this component on the user's first trigger click — without it- * the click that mounts the component wouldn't also open it.- */- defaultOpen?: boolean- /**- * Extra node rendered inside the trigger wrapper (which is `relative`),- * e.g. an absolutely-positioned corner badge. Kept inside the wrapper so- * callers don't need to add another positioned ancestor of their own.- */- triggerAccessory?: import('react').ReactNode- /**- * Trigger presentation. `'button'` (default) is the single dropdown- * button. `'input'` renders a replay-style search box with a leading- * filter-icon button: focusing/typing in the box opens the combobox,- * clicking the icon opens the dropdown menu. Only takes effect while- * nothing is `selected` (the add-filter case) — an existing selection- * still renders the button so its label is visible.- */- triggerVariant?: 'button' | 'input'- /**- * Where `defaultOpen` lands. Defaults to `resolveOpenState()` (menu when- * nothing is selected). The input trigger uses this so an open driven by- * the search box arrives directly on the combobox while one driven by the- * filter icon arrives on the dropdown menu.- */- defaultOpenState?: 'menu' | 'combobox'- /**- * Consumer rows appended to the dropdown menu, under a separator. Each row- * is a `DropdownMenu*` item, so a click closes the menu like a built-in row.- */- menuItems?: import('react').ReactNode-}--export interface TriggerState {- label: string- selected: MenuFilterEntry | null- open: boolean-}--/** Dropdown-menu options users can pick, for the option-click event. */-type MenuOption = 'new' | 'recent' | 'pinned' | 'dwh' | 'hogql'--// Module-level so a quick close→reopen is detectable even though the-// component unmounts between opens (consumers lazily mount it on the-// first trigger click). Heuristic only — shared across all triggers.-let lastMenuClosedAtMs: number | null = null-const QUICK_REOPEN_MS = 3000--// The input-trigger panel is shifted up + left so its search field lands over-// the trigger row (the input appears to stay put and only widen). The shift-// equals the field's offset from the panel's top-left, summed from the pieces-// that produce it — kept as named parts so a change to `MenuFilterHeader`'s-// spacing or the input row's padding is visibly the thing to keep in sync here.-const MENU_HEADER_PADDING_Y_PX = 16 // MenuFilterHeader `py-2` (top + bottom)-const MENU_HEADER_BUTTON_HEIGHT_PX = 24 // "Go back" Button `size="sm"` (h-6)-const MENU_HEADER_BORDER_PX = 1 // MenuFilterHeader `border-b`-const SEARCH_ROW_PADDING_PX = 8 // search-field row `p-2` (one side)-const PANEL_BORDER_PX = 1 // PopoverContent border--/** Panel-top to search-field-top: the header (padding + button + border) plus the- * search row's top padding. */-const INPUT_TRIGGER_PANEL_HEADER_OFFSET =- MENU_HEADER_PADDING_Y_PX + MENU_HEADER_BUTTON_HEIGHT_PX + MENU_HEADER_BORDER_PX + SEARCH_ROW_PADDING_PX--/** Panel-left to search-field-left: the panel border plus the search row's left- * padding. */-const INPUT_TRIGGER_PANEL_LEFT_INSET = PANEL_BORDER_PX + SEARCH_ROW_PADDING_PX--/** Mirrors legacy `taxonomicFilterLogic`: staleness only applies to event /- * custom-event definitions that carry `last_seen_at`; `undefined` for every- * other selection so the field reads identically across the A/B arms. */-export function eventSelectionWasStale(- sourceGroupType: TaxonomicFilterGroupType,- item: TaxonomicDefinitionTypes-): boolean | undefined {- const isEventSelection =- sourceGroupType === TaxonomicFilterGroupType.Events || sourceGroupType === TaxonomicFilterGroupType.CustomEvents- if (!isEventSelection || !item || typeof item !== 'object' || !('last_seen_at' in item)) {- return undefined- }- return isDefinitionStale(item as unknown as EventDefinition)-}--/** The default combobox landing — the "All" scope, where recents/pinned lead and- * the user can search across every category. The one home for this state so the- * initial-mount and runtime open paths can't drift. */-const comboboxAllState = (): MenuFilterState => ({ kind: 'combobox', drillTo: 'all' })--/**- * Resolve the panel a trigger open should land on from the current selection.- * If `selected` is set, jump straight into the panel that matches its group so- * the user lands on something editable (e.g. the HogQL editor pre-filled with- * the existing expression) instead of having to re-traverse the dropdown menu.- * With no selection we fall back to the menu.- */-export function resolveSelectedOpenState(selected: MenuFilterEntry | null): MenuFilterState {- if (!selected) {- return { kind: 'menu' }- }- if (selected.group.type === TaxonomicFilterGroupType.HogQLExpression) {- return { kind: 'hogql-edit' }- }- if (selected.group.type === TaxonomicFilterGroupType.DataWarehouse) {- // origin='menu' so X / Esc / Cancel return to the dropdown menu rather- // than dropping the user into the (unscrolled) dwh-pick list they never- // visited.- return { kind: 'dwh-config', table: selected.item, group: selected.group, origin: 'menu' }- }- // The committed selection floats to the first row (and stays highlighted) so- // the user can verify it at a glance.- return comboboxAllState()-}--/**- * Initial menu state at mount. `defaultOpen` consumers lazily mount this- * component on the user's first trigger interaction, so opening is a one-shot- * mount concern — it belongs in the initial state, not a post-paint effect, so- * the picker opens in the same commit it mounts (no intermediate closed frame).- * `defaultOpenState` routes the open to the panel matching the interaction (the- * input trigger's search box -> combobox, its filter icon -> menu).- */-export function resolveInitialMenuState(- defaultOpen: boolean,- defaultOpenState: 'menu' | 'combobox' | undefined,- selected: MenuFilterEntry | null-): MenuFilterState {- if (!defaultOpen) {- return { kind: 'closed' }- }- if (defaultOpenState === 'combobox') {- return comboboxAllState()- }- if (defaultOpenState === 'menu') {- return { kind: 'menu' }- }- return resolveSelectedOpenState(selected)-}--export function TaxonomicFilterMenu({- triggerLabel,- selected,- selectedRename,- trigger,- onCommit,- placeholder,- comboboxTitle,- dataWarehousePopoverFields,- insightProps,- fullWidthTrigger = false,- defaultOpen = false,- triggerAccessory,- triggerVariant = 'button',- defaultOpenState,- menuItems,-}: TaxonomicFilterMenuProps): JSX.Element {- const {- groups,- selectItem,- inputProps,- searchQuery,- setSearchQuery,- selectingKeyOnly,- excludedOperators,- excludedProperties,- } = useTaxonomicFilterContext()- const [state, setState] = useState<MenuFilterState>(() =>- resolveInitialMenuState(defaultOpen, defaultOpenState, selected ?? null)- )-- // Telemetry — track open dwell + commit funnel so we can compare- // against legacy `taxonomic filter *` events. Stored in refs so the- // close handler reads the actual session start, not a stale closure.- const openedAtRef = useRef<number | null>(null)- const hadCommitRef = useRef(false)- const lastStateKindRef = useRef<MenuFilterState['kind']>('closed')- useEffect(() => {- const previous = lastStateKindRef.current- const next = state.kind- if (previous === 'closed' && next !== 'closed') {- const now = Date.now()- const msSinceLastClose = lastMenuClosedAtMs != null ? now - lastMenuClosedAtMs : null- openedAtRef.current = now- hadCommitRef.current = false- posthog.capture('taxonomic filter menu opened', {- openedTo: next,- hadSelection: !!selected,- triggerLabel,- // Reopen funnel — `null` on the first open of the session;- // a small value means the user bounced and came right back.- msSinceLastClose,- reopenedQuickly: msSinceLastClose != null && msSinceLastClose < QUICK_REOPEN_MS,- })- } else if (previous !== 'closed' && next !== 'closed' && previous !== next) {- posthog.capture('taxonomic filter menu drilled', {- fromState: previous,- toState: next,- })- } else if (previous !== 'closed' && next === 'closed') {- const closedAt = Date.now()- const dwellMs = openedAtRef.current ? closedAt - openedAtRef.current : null- posthog.capture('taxonomic filter menu closed', {- dwellMs,- hadCommit: hadCommitRef.current,- lastState: previous,- })- // Legacy's `groupType: activeTab` is omitted because the menu has no single active tab at close time.- posthog.capture('taxonomic filter closed', {- surface: TAXONOMIC_FILTER_SURFACE,- dwellMs,- hadSelection: hadCommitRef.current,- categoryRailDocked: false,- })- lastMenuClosedAtMs = closedAt- openedAtRef.current = null- }- lastStateKindRef.current = next- // We deliberately don't track `selected` / `triggerLabel` — they- // shouldn't fire fresh `opened` events on identity churn.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [state.kind])-- // -- Transitions -- single source of truth for state changes. Each- // transition is a single setState call so React batches and there's- // no intermediate flicker.- const closeAll = useCallback(() => setState({ kind: 'closed' }), [])- const openMenu = useCallback(() => setState({ kind: 'menu' }), [])- const openCombobox = useCallback((drillTo: DrillCategory) => setState({ kind: 'combobox', drillTo }), [])- const openDwhPick = useCallback(() => setState({ kind: 'dwh-pick' }), [])- const openDwhConfig = useCallback(- (table: TaxonomicDefinitionTypes, group: TaxonomicFilterGroup, origin: 'menu' | 'dwh-pick') =>- setState({ kind: 'dwh-config', table, group, origin }),- []- )- const openHogql = useCallback(() => setState({ kind: 'hogql-edit' }), [])-- // Capture which dropdown-menu option the user picked, then run its- // transition. Lets us see the relative pull of New / Recent / Pinned /- // DWH / HogQL rather than just a generic menu→panel `drilled` event.- const selectMenuOption = useCallback((option: MenuOption, action: () => void): void => {- posthog.capture('taxonomic filter menu option clicked', { option })- action()- }, [])-- const resolveOpenState = useCallback((): MenuFilterState => resolveSelectedOpenState(selected ?? null), [selected])-- // -- Recent / Pinned shortcuts -- read from kea so menu items reflect- // the live counts. Mapped back to entries via source group.- const { recentFilterItems } = useValues(recentTaxonomicFiltersLogic)- const { pinnedFilterItems } = useValues(taxonomicFilterPinnedPropertiesLogic)-- // Only recents/pinned whose source group is one of this picker's groups —- // a global recent from a different picker (e.g. a cohort in an events-only- // picker) would otherwise be remapped onto a fallback group and shown under- // the wrong category.- const taxonomicGroupTypes = useMemo(() => groups.map((g) => g.type), [groups])- const recentEntries = useMemo<MenuFilterEntry[]>(- () =>- mapShortcutItems(- filterRecentsForContext(- recentFilterItems as TaxonomicDefinitionTypes[],- taxonomicGroupTypes,- excludedOperators,- selectingKeyOnly,- excludedProperties- ) as ShortcutItem[],- groups- ),- [recentFilterItems, taxonomicGroupTypes, groups, excludedOperators, selectingKeyOnly, excludedProperties]- )- const pinnedEntries = useMemo<MenuFilterEntry[]>(- () =>- mapShortcutItems(- filterPinnedForContext(- pinnedFilterItems as TaxonomicDefinitionTypes[],- taxonomicGroupTypes,- excludedProperties- ) as ShortcutItem[],- groups- ),- [pinnedFilterItems, taxonomicGroupTypes, groups, excludedProperties]- )-- const hasDwh = groups.some((g) => g.type === TaxonomicFilterGroupType.DataWarehouse)- const hasHogql = groups.some((g) => g.type === TaxonomicFilterGroupType.HogQLExpression)-- // -- Commit -- routes through orchestrator's `selectItem` AND the- // consumer's `onCommit` callback. Closes everything.- const handleCommit = useCallback<CommitFn>(- (entry, extra, selection) => {- const mergedItem = extra- ? ({ ...(entry.item as unknown as object), ...extra } as unknown as TaxonomicDefinitionTypes)- : entry.item- const itemValue = entry.group.getValue?.(mergedItem) ?? entry.canonicalValue ?? null- hadCommitRef.current = true- posthog.capture('taxonomic filter menu item selected', {- groupType: entry.group.type,- hadSearchInput: !!searchQuery,- query: searchQuery || undefined,- hadExtras: !!extra,- fromState: lastStateKindRef.current,- // Time-to-select — how long from opening the menu to- // committing this item.- msSinceOpen: openedAtRef.current ? Date.now() - openedAtRef.current : null,- })- // Legacy contract, fired from this final-commit funnel rather than on- // row click so it counts only committed selections — a DWH table pick- // that opens (and is then cancelled from) the config form never reaches- // here, while a config-form or HogQL commit does. `groupType` is the- // active scope (mirrors legacy `activeTab`); `sourceGroupType` is the- // row's origin group — they differ for a recent/pinned row on the All- // surface. `selection` is absent for non-row commits (DWH form, HogQL).- // `wasStale` mirrors legacy for event/custom-event selections; `wasQuickFilter`- // uses the same predicate as legacy, though the menu surfaces no quick-filter- // items so it is false in practice and the legacy quick-filter field spread- // never applies here.- // `position` is the rendered row index (same coordinate as legacy's- // `meta.position`): directly comparable on single-group scopes, and- // surface-relative on the merged "All" scope, which leads with the- // recents/pinned prefix and has no single-tab legacy equivalent.- posthog.capture('taxonomic filter item selected', {- surface: TAXONOMIC_FILTER_SURFACE,- groupType: selection?.groupType,- sourceGroupType: entry.group.type,- wasFromRecents: selection?.wasFromRecents ?? false,- wasFromPinnedList: selection?.wasFromPinnedList ?? false,- wasQuickFilter: isQuickFilterItem(entry.item),- hadSearchInput: !!searchQuery,- 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)- closeAll()- },- [selectItem, onCommit, closeAll, searchQuery]- )-- // -- Trigger render --- const label =- (selected?.friendlyLabel && selected.friendlyLabel.length > 0 ? selected.friendlyLabel : selected?.name) ||- triggerLabel ||- inputProps.placeholder ||- 'Filter'- const triggerState: TriggerState = { label, selected: selected ?? null, open: state.kind !== 'closed' }- const triggerEl: ReactElement =- typeof trigger === 'function' ? trigger(triggerState) : (trigger ?? <Button variant="outline">{label}</Button>)-- // Replay-style input trigger — only while nothing is selected, so an- // existing selection keeps showing its label in the button. The icon is- // the dropdown-menu anchor; the input opens (and seeds) the combobox.- const useInputTrigger = triggerVariant === 'input' && !selected- const inputTriggerPlaceholder = triggerLabel || inputProps.placeholder || 'Add filter'-- // When the input-trigger combobox is open, the popover panel renders the- // live search field (header above it, results below) and is shifted up so- // that field lands over the trigger row — the chrome wraps the input. The- // shared ref lets the popover focus that field on open.- const comboboxInputRef = useRef<HTMLInputElement | null>(null)-- // -- Popover open derives from state. The dropdown menu is a separate- // overlay (DropdownMenu); the popover is open for any non-menu,- // non-closed kind.- //- // `dwh-config` deliberately excluded — when the user opens the DWH- // config dialog we close the popover (not just stack on top of it),- // so PostHog's stock z-order (`--z-popover` > `--z-modal`) keeps- // Selects inside the dialog above the modal as expected. Cancelling- // the dialog returns to `dwh-pick` and the popover re-opens at the- // table list.- const popoverOpen = state.kind === 'combobox' || state.kind === 'dwh-pick' || state.kind === 'hogql-edit'-- // `combobox` and `dwh-pick` render a search-field row, so in input-trigger- // mode the panel is shifted to overlay that field on the trigger box (and the- // trigger yields to an invisible spacer). `hogql-edit` is intentionally- // excluded: the code editor has no search-field row to align to, so it opens- // as a normal dropdown below the trigger.- const comboboxOverlaysTrigger = useInputTrigger && (state.kind === 'combobox' || state.kind === 'dwh-pick')-- // Filter-icon menu anchor, styled to match the scene (LemonButton). Lives- // as the field's prefix — in the resting trigger box, and in the combobox's- // portaled field while open — so it stays put as the menu opens around it.- const inputTriggerIcon = (- <DropdownMenuTrigger- render={- <LemonButton- size="small"- icon={<IconFilter />}- aria-label="Open filter menu"- data-attr="taxonomic-filter-menu-trigger"- // Stop the click bubbling to the LemonInput wrapper, whose- // onClick focuses the input — that would open the combobox- // instead of the icon's dropdown menu.- onClick={(e) => e.stopPropagation()}- />- }- />- )-- // Manual outside-click handling. base-ui Popover's automatic dismiss- // can't reliably distinguish a click on the visible trigger (the- // DropdownMenuTrigger button) from a click outside, because its own- // PopoverTrigger is a transparent overlay sibling. We cancel its- // outsidePress / focusOut firings (see `onOpenChange` below) and- // close manually here.- //- // The popover content lives in a portal and Quill's `PopoverContent`- // doesn't forward refs, so we walk the click target's ancestors- // looking for `[data-slot="popover-content"]` instead.- const triggerWrapRef = useRef<HTMLSpanElement | null>(null)-- /*- * Mount the popover inside the global `main-content-container`- * layout host (defined in `Navigation.tsx`) instead of the default- * `document.body` portal. CSS container queries- * (`@container/main-content-container`) walk DOM ancestors only —- * a portal to body breaks that chain, so chip-row hints and panel- * widths that key off `@[720px]/main-content-container` fail to- * resolve. Mounting inside the container restores ancestry and- * the same Tailwind classes work inside the popover content.- *- * Resolved synchronously via a lazy `useState` initializer so the- * value is available on the first render — base-ui's Portal reads- * `container` once at mount time, and a `useEffect`-set ref- * arrives one render too late, leaving the popover at `<body>`.- */- const [popoverContainer, setPopoverContainer] = useState<HTMLElement | null>(() =>- typeof document !== 'undefined'- ? (document.querySelector('.main-content-container') as HTMLElement | null)- : null- )- useEffect(() => {- // Tab-aware scenes can mount before the container element- // exists (the layout shell renders top-down). Re-poll once on- // mount so we still catch it after a brief delay.- if (popoverContainer) {- return undefined- }- const id = window.setTimeout(() => {- const found = document.querySelector('.main-content-container') as HTMLElement | null- if (found) {- setPopoverContainer(found)- }- }, 0)- return () => window.clearTimeout(id)- }, [popoverContainer])-- useEffect(() => {- if (!popoverOpen) {- return undefined- }- let attached = false- const handler = (event: PointerEvent): void => {- const target = event.target as Element | null- if (!target) {- return- }- // Treat clicks inside our own popover content as inside…- if (target.closest?.('[data-slot="popover-content"]')) {- return- }- // …and clicks inside ANY quill portal (Select dropdown, nested- // DropdownMenu, ContextMenu, Combobox suggestions) as inside- // too — those mount in their own portals at body level so a- // raw `target.closest(popover-content)` misses them. Without- // this, choosing a column from the field Select inside the- // DWH config form was closing the whole popover.- if (target.closest?.('[data-quill-portal]')) {- return- }- // Monaco portals suggestion widgets to a shared body-level div; treat clicks there as- // inside so picking a SQL autocomplete value doesn't close the filter.- if (target.closest?.('[data-attr="monaco-overflow-root"]')) {- return- }- if (triggerWrapRef.current?.contains(target)) {- return- }- closeAll()- }- // Defer attach by one task — avoids catching the same click that- // just transitioned us into a popover state.- const timer = window.setTimeout(() => {- attached = true- document.addEventListener('pointerdown', handler, true)- }, 0)- return () => {- window.clearTimeout(timer)- if (attached) {- document.removeEventListener('pointerdown', handler, true)- }- }- }, [popoverOpen, closeAll])-- return (- <DropdownMenu- open={state.kind === 'menu'}- onOpenChange={(open) => {- if (open) {- // Trigger click is the only way DropdownMenu's- // onOpenChange(true) fires. Interpret it based on- // current state: closed → resolve to a panel; in a- // popover state → toggle the popover closed.- setState((current) => {- if (- current.kind === 'combobox' ||- current.kind === 'dwh-pick' ||- current.kind === 'dwh-config' ||- current.kind === 'hogql-edit'- ) {- return { kind: 'closed' }- }- return resolveOpenState()- })- return- }- // Functional setState — when a menu item's onClick already- // advanced state (e.g. to 'combobox'), the subsequent menu- // auto-close shouldn't yank us back to 'closed'. Use the- // latest staged state, not the value from the render closure.- setState((current) => (current.kind === 'menu' ? { kind: 'closed' } : current))- }}- >- <Popover- open={popoverOpen}- onOpenChange={(open, eventDetails) => {- if (open) {- return- }- // Esc still closes via base-ui; everything else- // (outsidePress, focusOut, triggerHover, etc.) is- // unreliable when the trigger button isn't the- // PopoverTrigger element, so we cancel and let the- // document pointerdown effect handle it.- if (eventDetails.reason === 'escape-key') {- closeAll()- return- }- eventDetails.cancel()- }}- >- <span ref={triggerWrapRef} className={taxonomicTriggerWrapperClassName(fullWidthTrigger)}>- {useInputTrigger ? (- <MenuInputTrigger- iconButton={inputTriggerIcon}- fullWidth={fullWidthTrigger}- placeholder={inputTriggerPlaceholder}- value={searchQuery}- spacerOnly={comboboxOverlaysTrigger}- onChange={(next) => {- setSearchQuery(next)- if (state.kind !== 'combobox') {- openCombobox('all')- }- }}- onFocus={() => {- if (state.kind === 'closed') {- openCombobox('all')- }- }}- />- ) : (- <DropdownMenuTrigger render={triggerEl} data-attr="taxonomic-filter-menu-trigger" />- )}- <PopoverTrigger- nativeButton={false}- render={<span aria-hidden tabIndex={-1} className="absolute inset-0 pointer-events-none" />}- />- {triggerAccessory}- </span>- <PopoverContent- align="start"- side="bottom"- // Input trigger: shift the panel up by (trigger height +- // header + input-row padding) so the panel's search field- // lands over the trigger row — header pops above, results- // below, the input appears to stay put and just widen. Keep- // the side fixed so it can't flip away from that alignment.- // Button trigger: a normal dropdown below the button.- sideOffset={- comboboxOverlaysTrigger- ? ({ anchor }) => -(anchor.height + INPUT_TRIGGER_PANEL_HEADER_OFFSET)- : 4- }- // Pull the panel left so its inset search field aligns with- // the trigger box horizontally (input appears not to move).- alignOffset={comboboxOverlaysTrigger ? -INPUT_TRIGGER_PANEL_LEFT_INSET : 0}- // Input trigger: pin the vertical axis so the field stays over- // the trigger row, but allow horizontal `shift` so the wide- // panel slides left to stay on-screen when the trigger sits near- // the right edge (e.g. web-analytics filters) — losing a few px- // of horizontal alignment there beats clipping off-screen.- // Button trigger: keep it on the vertical axis, never beside.- collisionAvoidance={- comboboxOverlaysTrigger- ? { side: 'none', align: 'shift' }- : { side: 'flip', align: 'shift', fallbackAxisSide: 'none' }- }- container={popoverContainer ?? undefined}- // Focus the panel's search field on open (it's outside the- // popover's default focusable flow until rendered).- initialFocus={comboboxOverlaysTrigger ? comboboxInputRef : undefined}- className={cn(- 'p-0 gap-0 overflow-hidden flex flex-col w-[calc(100%_-_2rem)] @[720px]/main-content-container:w-[720px] h-[400px]'- )}- >- {state.kind === 'combobox' && (- <MenuFilterCombobox- drillTo={state.drillTo}- drillItems={- state.drillTo === 'recent'- ? recentEntries- : state.drillTo === 'pinned'- ? pinnedEntries- : undefined- }- // Recents/pinned lead the default "All" surface- // (fixed order: recents, then pinned).- recentEntries={recentEntries}- pinnedEntries={pinnedEntries}- placeholder={placeholder ?? inputProps.placeholder}- // Only override the default "Choose filter"- // header when on the All chip — drilled views- // already title themselves with the group name.- title={state.drillTo === 'all' ? comboboxTitle : undefined}- selectedEntry={selected ?? null}- selectedRename={selectedRename}- onCommit={handleCommit}- onBack={openMenu}- inputRef={comboboxInputRef}- iconButton={useInputTrigger ? inputTriggerIcon : undefined}- />- )}- {(state.kind === 'dwh-pick' || state.kind === 'dwh-config') && (- // Popover stays at the table list while the- // dwh-config Dialog (rendered below) is open on- // top — that way Cancel returns the user to the- // same list scroll/highlight position they were- // browsing before clicking a table.- <MenuFilterCombobox- drillTo={TaxonomicFilterGroupType.DataWarehouse}- title="Data warehouse tables"- placeholder="Search tables…"- selectedEntry={- selected?.group.type === TaxonomicFilterGroupType.DataWarehouse ? selected : null- }- onCommit={(entry) => openDwhConfig(entry.item, entry.group, 'dwh-pick')}- onBack={openMenu}- inputRef={comboboxInputRef}- iconButton={useInputTrigger ? inputTriggerIcon : undefined}- />- )}- {state.kind === 'hogql-edit' && (- <MenuFilterHogQLEditor- initialExpression={- selected?.group.type === TaxonomicFilterGroupType.HogQLExpression- ? selected.name- : undefined- }- onCommit={handleCommit}- onBack={openMenu}- />- )}- </PopoverContent>- </Popover>- {/* DWH config dialog — sibling of the popover so it portals- above it. Mounting only while in `dwh-config` state means- the dialog auto-opens on transition and unmounts on- close (Cancel / X / Esc → `onBack` returns to dwh-pick;- Select calls `handleCommit` which triggers `closeAll`- and dismisses both the dialog and the popover). */}- {state.kind === 'dwh-config' && (- <MenuFilterDwhConfig- // The selected entry receives schema loaded after opening; state.table is only the opening snapshot.- table={state.origin === 'menu' ? (selected?.item ?? state.table) : state.table}- group={state.group}- dataWarehousePopoverFields={dataWarehousePopoverFields}- insightProps={insightProps}- onCommit={handleCommit}- // Restore the origin surface — menu (when the dialog- // was opened straight from the trigger because a DWH- // selection already existed) or the table picker- // (when the user drilled down through dwh-pick).- onBack={state.origin === 'menu' ? openMenu : openDwhPick}- />- )}- <DropdownMenuContent align="start" className="min-w-[240px]">- {/* The input-trigger box already does "type to make a new filter",- so the explicit "New filter…" row would be redundant there. */}- {!useInputTrigger && (- <DropdownMenuItem- onClick={() => selectMenuOption('new', () => openCombobox('all'))}- data-attr="taxonomic-filter-menu-new"- >- New filter…- <IconChevronRight className="ml-auto size-3.5 text-tertiary" />- </DropdownMenuItem>- )}- {(hasDwh || hasHogql) && <DropdownMenuSeparator />}- {hasDwh && (- <DropdownMenuItem- onClick={() => selectMenuOption('dwh', openDwhPick)}- data-attr="taxonomic-filter-menu-dwh"- >- Data warehouse tables- <IconChevronRight className="ml-auto size-3.5 text-tertiary" />- </DropdownMenuItem>- )}- {hasHogql && (- <DropdownMenuItem- onClick={() => selectMenuOption('hogql', openHogql)}- data-attr="taxonomic-filter-menu-hogql"- >- HogQL expression- <IconChevronRight className="ml-auto size-3.5 text-tertiary" />- </DropdownMenuItem>- )}- {menuItems && (- <>- <DropdownMenuSeparator />- {menuItems}- </>- )}- </DropdownMenuContent>- </DropdownMenu>- )-}--interface ShortcutItem {- name?: string- id?: unknown- value?: unknown- // `_pinnedContext.value` and `_recentContext.sourceValue` mean the- // same thing — the source-group field name diverged in master while- // this branch was in flight; consumers (this menu) read whichever- // shape exists. See `taxonomicFilterPinnedPropertiesLogic` /- // `recentTaxonomicFiltersLogic`.- _pinnedContext?: { sourceGroupType?: TaxonomicFilterGroupType; value?: TaxonomicFilterValue }- _recentContext?: {- sourceGroupType?: TaxonomicFilterGroupType- sourceValue?: TaxonomicFilterValue- propertyFilter?: AnyPropertyFilter- }-}--/**- * Resolve the most appropriate `TaxonomicFilterGroup` for a shortcut- * item.- *- * 1. Recorded `sourceGroupType` if it points at a real content group- * that's available right now.- * 2. If the recorded source is a META group (Suggested / Recent /- * Pinned), find a non-meta group in `groups` whose `getValue(item)`- * matches the saved value — that's the underlying definition the- * item really belongs to (e.g. SuggestedFilters → Events).- * 3. Fall back to the first non-meta group so the row at least has a- * sensible category subtitle instead of "Suggested filters".- */-function resolveShortcutGroup(- item: ShortcutItem,- sourceType: TaxonomicFilterGroupType | undefined,- sourceValue: unknown,- groups: TaxonomicFilterGroup[]-): TaxonomicFilterGroup | null {- if (sourceType && !META_GROUP_TYPES.has(sourceType)) {- const direct = groups.find((g) => g.type === sourceType)- if (direct) {- return direct- }- }- const matchByValue = groups.find((g) => {- if (META_GROUP_TYPES.has(g.type)) {- return false- }- try {- const candidate = g.getValue?.(item as TaxonomicDefinitionTypes)- return candidate != null && candidate === sourceValue- } catch {- return false- }- })- if (matchByValue) {- return matchByValue- }- return groups.find((g) => !META_GROUP_TYPES.has(g.type)) ?? null-}--function mapShortcutItems(items: ShortcutItem[], groups: TaxonomicFilterGroup[]): MenuFilterEntry[] {- return items- .map((item) => {- const ctx = item._recentContext ?? item._pinnedContext- const sourceType = ctx?.sourceGroupType- // Recent stores the value under `sourceValue`, pinned under- // `value`. Read whichever side exists.- const sourceValue =- (ctx as { sourceValue?: TaxonomicFilterValue } | undefined)?.sourceValue ??- (ctx as { value?: TaxonomicFilterValue } | undefined)?.value- const group = resolveShortcutGroup(item, sourceType, sourceValue, groups)- if (!group) {- return null- }- const name = (item.name as string) ?? group.getName?.(item as TaxonomicDefinitionTypes) ?? ''- const recentPropertyFilter = item._recentContext?.propertyFilter- return {- item: item as TaxonomicDefinitionTypes,- group,- name,- ...(sourceValue != null ? { canonicalValue: sourceValue } : {}),- friendlyLabel: getCoreFilterDefinition(name, group.type)?.label,- ...(recentPropertyFilter- ? { recentPropertyFilter, recentLabel: formatPropertyLabel(recentPropertyFilter, {}) }- : {}),- } as MenuFilterEntry- })- .filter((e): e is MenuFilterEntry => e != null)-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/VerificationBadge.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/VerificationBadge.tsxdeleted file mode 100644index d4518ed0044f..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/VerificationBadge.tsx+++ /dev/null@@ -1,79 +0,0 @@-/**- * Verification badge for taxonomic filter rows + preview pane.- *- * Two mutually-exclusive states (core defs can't be team-verified — see- * `DefinitionPopoverContents`'s `allowVerification`):- * - `core` — a built-in PostHog definition (`isCoreFilter`). Badge- * reads "By PostHog" with the logomark.- * - `verified` — a custom definition a team explicitly marked verified- * (`item.verified`). Badge reads "Verified".- */-import { IconBadge, IconLogomark } from '@posthog/icons'-import { Badge, cn, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'--import { isCoreFilter } from '~/taxonomy/helpers'--import { MenuFilterEntry } from './types'--type Verification = { kind: 'core' } | { kind: 'verified' }--export function getVerification(entry: MenuFilterEntry): Verification | null {- // Core PostHog definitions ($pageview, $browser, …) are inherently- // verified — surfaced as "By PostHog" rather than a team flag.- if (isCoreFilter(entry.name)) {- return { kind: 'core' }- }- if ((entry.item as { verified?: boolean })?.verified) {- return { kind: 'verified' }- }- return null-}--export function VerificationBadge({- entry,- className,-}: {- entry: MenuFilterEntry- className?: string-}): JSX.Element | null {- const verification = getVerification(entry)- if (!verification) {- return null- }- const isCore = verification.kind === 'core'- return (- <Tooltip>- {/* The trigger must render a host element (a `<span>`) so- base-ui's ref + hover handlers actually attach — `Badge` is- a plain function component (not `forwardRef`), so spreading- the trigger's `ref` onto it gets dropped and the tooltip- never anchors/opens. The Badge is plain visual content- inside the trigger span. */}- <TooltipTrigger- delay={300}- render={(triggerProps) => (- <span {...triggerProps} className={cn('inline-flex', className)}>- <Badge variant={isCore ? 'default' : 'success'} className="gap-1 shrink-0">- {isCore ? <IconLogomark className="size-3" /> : <IconBadge className="size-3" />}- {isCore ? 'PostHog' : 'Verified'}- </Badge>- </span>- )}- />- <TooltipContent className="max-w-64 flex-col items-start">- {isCore ? (- <>- <strong>Built into PostHog.</strong> A core definition PostHog ships, maintains, and documents.- Its name, type, and description are managed for you, so you don't need to verify it.- </>- ) : (- <>- <strong>Verified by your team.</strong> Someone marked this definition as the right one to use.- Verified items are prioritized in filters so collaborators reach for them over similar,- unverified ones.- </>- )}- </TooltipContent>- </Tooltip>- )-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/index.ts b/frontend/src/lib/components/TaxonomicFilter/menu/index.tsdeleted file mode 100644index bba8d411d609..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/index.ts+++ /dev/null@@ -1,34 +0,0 @@-/**- * Dropdown-menu-fronted taxonomic filter — fresh rebuild.- *- * See `../headless/UX_SPEC.md` for the design reference.- *- * <TaxonomicFilterHeadless.Root taxonomicGroupTypes={...} onChange={...}>- * <TaxonomicFilterMenu />- * </TaxonomicFilterHeadless.Root>- */-export { TaxonomicFilterMenu } from './TaxonomicFilterMenu'-export type { TaxonomicFilterMenuProps, TriggerState as MenuFilterTriggerState } from './TaxonomicFilterMenu'--export { MenuFilterCombobox } from './Combobox'-export type { MenuFilterComboboxProps } from './Combobox'--export { MenuFilterDwhConfig } from './DwhFlow'-export type { MenuFilterDwhConfigProps } from './DwhFlow'--export { MenuFilterHogQLEditor } from './HogQLEditor'-export type { MenuFilterHogQLEditorProps } from './HogQLEditor'--export { MenuFilterHeader } from './Header'-export type { MenuFilterHeaderProps } from './Header'--export { PreviewPane as MenuFilterPreviewPane } from './PreviewPane'-export type { PreviewPaneProps as MenuFilterPreviewPaneProps } from './PreviewPane'--export type {- CommitFn as MenuFilterCommitFn,- DrillCategory as MenuFilterDrillCategory,- MenuFilterEntry,- MenuFilterState,- PageHeader as MenuFilterPageHeader,-} from './types'diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/preview/ActionMatchGroups.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/preview/ActionMatchGroups.test.tsxdeleted file mode 100644index c5d2578cce43..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/preview/ActionMatchGroups.test.tsx+++ /dev/null@@ -1,61 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, screen, waitFor } from '@testing-library/react'-import { Provider } from 'kea'--import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { initKeaTests } from '~/test/init'--import { ActionMatchGroups } from './ActionMatchGroups'--const TEST_ACTION = {- id: 282580,- name: 'Test action',- steps: [- {- event: '$pageview',- properties: [{ key: '$os_version', value: '14.4.1', operator: 'semver_gte' }],- },- ],-}--function renderItem(item: any): ReturnType<typeof render> {- return render(- <Provider>- <ActionMatchGroups item={item} />- </Provider>- )-}--describe('ActionMatchGroups', () => {- beforeEach(async () => {- useMocks({ get: { '/api/projects/:team_id/actions/': { results: [TEST_ACTION], count: 1 } } })- initKeaTests()- actionsModel.mount()- await waitFor(() => {- if (actionsModel.values.actions.length !== 1) {- throw new Error('actions not loaded yet')- }- })- })-- afterEach(() => cleanup())-- // Both an item that already carries `steps` and a lightweight `{ id, name }` shim (the- // committed selection on the "All" surface) must render the match groups — the bug was- // that the shim, lacking `steps`, produced a blank preview.- it.each([- ['an item that already carries steps', TEST_ACTION],- ['a step-less {id,name} shim hydrated from actionsModel', { id: TEST_ACTION.id, name: TEST_ACTION.name }],- ])('renders match groups for %s', (_label, item) => {- renderItem(item)- expect(screen.getByText('$os_version')).toBeInTheDocument()- expect(screen.getByText('greater than or equal (semver)')).toBeInTheDocument()- })-- it('renders nothing for a step-less item with no matching action', () => {- const { container } = renderItem({ id: 999999, name: 'unknown' })- expect(container).toBeEmptyDOMElement()- })-})diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/preview/ActionMatchGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/preview/ActionMatchGroups.tsxdeleted file mode 100644index cebab49c907d..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/preview/ActionMatchGroups.tsx+++ /dev/null@@ -1,120 +0,0 @@-/**- * Action match-groups list for the preview pane. Renders- * `MATCH GROUP N: <event>` cards joined by "OR" separators. Direct- * Quill-styled port of the legacy `ActionPopoverInfo` so we don't pull- * in the kea-coupled `DefinitionPopover` primitives.- */-import { useValues } from 'kea'--import { Separator } from '@posthog/quill'--import { genericOperatorToHumanName, propertyValueToHumanName } from 'lib/components/DefinitionPopover/utils'--import { actionsModel } from '~/models/actionsModel'-import { ActionStepType, ActionType } from '~/types'--import { TaxonomicDefinitionTypes } from '../../types'--export function ActionMatchGroups({ item }: { item: TaxonomicDefinitionTypes }): JSX.Element | null {- const { actionsById } = useValues(actionsModel)- // The highlighted entry can be a lightweight `{ id, name }` shim — e.g. the- // committed selection on the "All" surface, when the full action isn't among- // the rows currently shown — which carries no `steps`. Hydrate it from- // actionsModel so the match groups render instead of silently nothing.- const partial = item as Partial<ActionType>- const action: ActionType | undefined = Array.isArray(partial.steps)- ? (partial as ActionType)- : partial.id != null- ? actionsById[partial.id]- : undefined- if (!action || !Array.isArray(action.steps) || action.steps.length === 0) {- return null- }- return (- <div className="flex flex-col gap-3 border-t pt-2">- {action.steps.map((step, idx) => (- <div key={idx} className="flex flex-col gap-2">- <MatchGroup index={idx + 1} step={step} />- {idx < action.steps!.length - 1 && (- <div className="flex items-center gap-2 text-xxs uppercase tracking-wide text-secondary">- <Separator className="flex-1" />- <span>OR</span>- <Separator className="flex-1" />- </div>- )}- </div>- ))}- </div>- )-}--function MatchGroup({ index, step }: { index: number; step: ActionStepType }): JSX.Element {- const conditions: JSX.Element[] = []- if (step.selector) {- conditions.push(- <li key="sel">- Element matches CSS selector <Mono>{step.selector}</Mono>- </li>- )- }- if (step.text) {- conditions.push(- <li key="text">- Text{' '}- {step.text_matching === 'regex'- ? 'matches regex'- : step.text_matching === 'exact'- ? 'equals'- : 'contains'}{' '}- <Mono>{step.text}</Mono>- </li>- )- }- if (step.href) {- conditions.push(- <li key="href">- Href{' '}- {step.href_matching === 'regex'- ? 'matches regex'- : step.href_matching === 'exact'- ? 'equals'- : 'contains'}{' '}- <Mono>{step.href}</Mono>- </li>- )- }- if (step.url) {- conditions.push(- <li key="url">- URL{' '}- {step.url_matching === 'regex'- ? 'matches regex'- : step.url_matching === 'exact'- ? 'equals'- : 'contains'}{' '}- <Mono>{step.url}</Mono>- </li>- )- }- step.properties?.forEach((p, pi) => {- conditions.push(- <li key={`p-${pi}`}>- <Mono>{p.key}</Mono> {genericOperatorToHumanName(p)} <Mono>{propertyValueToHumanName(p.value)}</Mono>- </li>- )- })- return (- <div className="flex flex-col gap-1">- <div className="text-xxs uppercase tracking-wide text-secondary">- Match group {index}: <span className="font-mono normal-case text-foreground">{step.event ?? '—'}</span>- </div>- {conditions.length > 0 && (- <ul className="text-xs text-secondary list-disc pl-4 space-y-0.5">{conditions}</ul>- )}- </div>- )-}--function Mono({ children }: { children: React.ReactNode }): JSX.Element {- return <span className="font-mono text-foreground">{children}</span>-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/triggerLayout.ts b/frontend/src/lib/components/TaxonomicFilter/menu/triggerLayout.tsdeleted file mode 100644index c48e5bb5ea0d..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/triggerLayout.ts+++ /dev/null@@ -1,18 +0,0 @@-import { cn } from '@posthog/quill'--/**- * Single source of truth for the layout of any taxonomic-filter trigger- * wrapper — the legacy `TaxonomicPopover` fallback, the lazy placeholder- * before the rebuilt menu mounts, and the rebuilt `TaxonomicFilterMenu`- * itself. Keeping them identical means swapping between the legacy and- * rebuilt triggers (or the placeholder → armed transition) never shifts the- * trigger's box.- *- * `relative` anchors the floating `<TaxonomicMenuToggle>`; `flex min-w-0`- * (not `inline-flex`) lets the trigger fill its parent column and truncate- * instead of sizing to its intrinsic width; width tracks the call site's- * `fullWidth` so a full-width column stays full width in every variant.- */-export function taxonomicTriggerWrapperClassName(fullWidth?: boolean): string {- return cn('relative flex min-w-0', fullWidth ? 'w-full' : 'max-w-full')-}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/types.ts b/frontend/src/lib/components/TaxonomicFilter/menu/types.tsdeleted file mode 100644index caf776f5c1fc..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/menu/types.ts+++ /dev/null@@ -1,77 +0,0 @@-/**- * Shared types for the dropdown-menu-fronted taxonomic filter.- *- * See `../headless/UX_SPEC.md` for the full design.- */-import { AnyPropertyFilter } from '~/types'--import {- TaxonomicDefinitionTypes,- TaxonomicFilterGroup,- TaxonomicFilterGroupType,- TaxonomicFilterValue,-} from '../types'--export const TAXONOMIC_FILTER_SURFACE = 'rebuild-menu'--/** A single selectable entry — what the picker commits when chosen. */-export interface MenuFilterEntry {- item: TaxonomicDefinitionTypes- group: TaxonomicFilterGroup- name: string- canonicalValue?: TaxonomicFilterValue- friendlyLabel?: string- recentPropertyFilter?: AnyPropertyFilter- recentLabel?: string-}--/** Synthetic categories the combobox panel can be drilled into. */-export type DrillCategory = 'all' | 'recent' | 'pinned' | TaxonomicFilterGroupType--/** Top-level state machine. One union type, one transition per action. */-export type MenuFilterState =- | { kind: 'closed' }- | { kind: 'menu' }- | { kind: 'combobox'; drillTo: DrillCategory }- | { kind: 'dwh-pick' }- | {- kind: 'dwh-config'- table: TaxonomicDefinitionTypes- group: TaxonomicFilterGroup- /** Where the dialog was opened from — restored when X / Esc /- * overlay / Cancel fire so back navigation lands on the right- * surface ('menu' = jumped here from the trigger because a- * selection already existed; 'dwh-pick' = drilled down via the- * table picker). */- origin: 'menu' | 'dwh-pick'- }- | { kind: 'hogql-edit' }--/** Common header info every popover sub-page shares. */-export interface PageHeader {- title: string- /** Called when the back button (or Esc) fires. */- onBack: () => void-}--/** Row context the combobox forwards on commit so the legacy `taxonomic filter- * item selected` event (emitted from the final-commit funnel, not on row click)- * can still carry the row's position and origin. Absent for commits that don't- * originate from a combobox row (DWH config form, HogQL editor). */-export interface CommitSelectionContext {- /** Active scope chip the row sat under (legacy `activeTab`); undefined on the All/Recent/Pinned meta scopes. */- groupType: TaxonomicFilterGroupType | undefined- /** Zero-based row position in the rendered list; undefined if the committed- * entry isn't in the rendered list (kept absent rather than a sentinel). */- position: number | undefined- wasFromRecents: boolean- wasFromPinnedList: boolean-}--export type CommitFn = (- entry: MenuFilterEntry,- extra?: Record<string, unknown>,- selection?: CommitSelectionContext-) => void--export type { TaxonomicFilterGroup, TaxonomicFilterGroupType, TaxonomicFilterValue, TaxonomicDefinitionTypes }diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.tsindex e08ea1e29080..094f060dd600 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts@@ -943,8 +943,6 @@ describe('taxonomicFilterLogic', () => {})describe('MCP properties group by event scope', () => {- // Mirrors the rebuild-side assertions in utils/mcpProperties.test.ts — the two- // variants define the group independently, so both sides guard against drift.it.each([{ eventNames: ['$mcp_tool_call'], expectPresent: true },{ eventNames: ['$pageview'], expectPresent: false },@@ -1740,7 +1738,7 @@ describe('taxonomicFilterLogic', () => {(g) => g.type === TaxonomicFilterGroupType.HogQLExpression)!const item = { name: 'properties.$current_url', value: 'properties.$current_url' }- // Mirror TaxonomicFilterMenu's handleCommit: the value is derived via group.getValue.+ // The value is derived via group.getValue.const value = group.getValue?.(item as any) ?? nullawait expectLogic(hogqlLogic, () => {diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsxindex 124f795d3e04..7d341f94c75c 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx@@ -1927,7 +1927,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([getName: (option: SimpleOption | QuickFilterItem) => option.name,// The collapsed "URL contains <query>" row is a QuickFilterItem whose// selection value is the typed query, so generic consumers reading the- // committed value get the query (matching the rebuild menu), not the label.+ // committed value get the query, not the label.getValue: (option: SimpleOption | QuickFilterItem) =>isQuickFilterItem(option) ? option.filterValue : option.name,getPopoverHeader: () => `Pageview URL`,@@ -2073,7 +2073,6 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([),// Recently-used entries are stored stripped of `active`, so treat only an explicit// `false` as disabled — otherwise recent flags are wrongly disabled and unselectable.- // Keep in sync with the Feature Flags group in utils/buildTaxonomicGroups.tsx.getIsDisabled: (featureFlag: FeatureFlagType) => featureFlag.active === false,localItemsSearch: (items, query) => {if (!query) {@@ -2731,8 +2730,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([filterValue: item.filterValue,propertyFilterType: item.propertyFilterType,eventName: item.eventName,- // Mirrors the rebuild menu's `wasUrlContainsShortcut` so contains-shortcut- // adoption is comparable across arms, not muddied with keyword shortcuts.+ // Keeps contains-shortcut adoption separate from keyword shortcuts.wasUrlContainsShortcut: item.isContainsShortcut === true,}),})diff --git a/frontend/src/lib/components/TaxonomicFilter/types.ts b/frontend/src/lib/components/TaxonomicFilter/types.tsindex b52ac8e13220..151e5072b077 100644--- a/frontend/src/lib/components/TaxonomicFilter/types.ts+++ b/frontend/src/lib/components/TaxonomicFilter/types.ts@@ -43,8 +43,7 @@ export interface QuickFilterItem {eventName?: stringextraProperties?: (EventPropertyFilter | PersonPropertyFilter)[]/** Set on the collapsed `URL contains "<query>"` row so commit telemetry can- * measure contains-shortcut adoption, matching the rebuild menu's- * `wasUrlContainsShortcut`. */+ * measure contains-shortcut adoption (`wasUrlContainsShortcut`). */isContainsShortcut?: boolean}@@ -203,7 +202,7 @@ export interface TaxonomicFilterProps {* See `SelectingKeyOnly` for the boolean-or-per-group-dict shape. */selectingKeyOnly?: SelectingKeyOnly/** Collapse URL-shaped groups (Pageview URLs) to a single `URL contains "<query>"`- * shortcut row instead of listing every matching URL — mirrors the rebuild menu.+ * shortcut row instead of listing every matching URL.* Selecting the row commits `$current_url IContains <query>` via a `QuickFilterItem`,* so a host must handle `isQuickFilterItem(item)` in onChange to honor the contains* operator. Only `TaxonomicPropertyFilter` (and the property/universal-filter hosts@@ -417,8 +416,8 @@ export const META_GROUP_TYPES = new Set<TaxonomicFilterGroupType>([/** Selection types that reopen on their own tab/panel rather than the default "All" surface,* because they're config/edit flows (an expression editor, a data-warehouse table/column- * picker) with no simple category value to verify at a glance. Honored by the legacy- * `activeTab` selector and the rebuild menu's `activeChip` initializer alike. */+ * picker) with no simple category value to verify at a glance. Honored by the+ * `activeTab` selector. */export const OPEN_AS_SELF_ON_REOPEN = new Set<TaxonomicFilterGroupType>([TaxonomicFilterGroupType.HogQLExpression,TaxonomicFilterGroupType.DataWarehouse,diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts b/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.tsdeleted file mode 100644index 59bf60af2e51..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts+++ /dev/null@@ -1,66 +0,0 @@-import { combineUrl } from 'kea-router'--import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { capitalizeFirstLetter } from 'lib/utils/strings'-import { toParams } from 'lib/utils/url'-import { getPropertyDefinitionIcon } from 'scenes/data-management/events/DefinitionHeader'--import { Group, GroupType } from '~/types'--import { groupDisplayId } from 'products/persons/frontend/components/GroupActorDisplay'--export type AggregationLabel = (groupTypeIndex: number) => { singular: string; plural: string }--/**- * Pure builder for the dynamic "Group Names" tabs (one per group_type_index).- * Mirrors the `groupAnalyticsTaxonomicGroupNames` selector in taxonomicFilterLogic.- */-export function buildGroupAnalyticsTaxonomicGroupNames(- groupTypes: Map<unknown, GroupType>,- teamId: number,- aggregationLabel: AggregationLabel-): TaxonomicFilterGroup[] {- return Array.from(groupTypes.values()).map((type) => ({- name: capitalizeFirstLetter(aggregationLabel(type.group_type_index).plural),- searchPlaceholder: aggregationLabel(type.group_type_index).plural,- type: `${TaxonomicFilterGroupType.GroupNamesPrefix}_${type.group_type_index}` as unknown as TaxonomicFilterGroupType,- endpoint: combineUrl(`api/projects/${teamId}/groups/`, {- group_type_index: type.group_type_index,- }).url,- getPopoverHeader: () => 'Group Names',- getName: (group: Group) => groupDisplayId(group.group_key, group.group_properties),- getValue: (group: Group) => group.group_key,- groupTypeIndex: type.group_type_index,- }))-}--/**- * Pure builder for the dynamic "Group properties" tabs (one per group_type_index).- * Mirrors the `groupAnalyticsTaxonomicGroups` selector in taxonomicFilterLogic.- */-export function buildGroupAnalyticsTaxonomicGroups(- groupTypes: Map<unknown, GroupType>,- projectId: number | null,- aggregationLabel: AggregationLabel-): TaxonomicFilterGroup[] {- return Array.from(groupTypes.values()).map((type) => ({- name: `${capitalizeFirstLetter(aggregationLabel(type.group_type_index).singular)} properties`,- searchPlaceholder: `${aggregationLabel(type.group_type_index).singular} properties`,- type: `${TaxonomicFilterGroupType.GroupsPrefix}_${type.group_type_index}` as unknown as TaxonomicFilterGroupType,- endpoint: combineUrl(`api/projects/${projectId}/property_definitions`, {- type: 'group',- group_type_index: type.group_type_index,- exclude_hidden: true,- }).url,- valuesEndpoint: (key) =>- `api/projects/${projectId}/groups/property_values?${toParams({- key,- group_type_index: type.group_type_index,- })}`,- getName: (group) => group.name,- getValue: (group) => group.name,- getPopoverHeader: () => 'Property',- getIcon: getPropertyDefinitionIcon,- groupTypeIndex: type.group_type_index,- }))-}diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsxdeleted file mode 100644index 2f3b464446fa..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx+++ /dev/null@@ -1,1214 +0,0 @@-import clsx from 'clsx'-import { combineUrl } from 'kea-router'--import { IconFlag, IconServer } from '@posthog/icons'--import {- buildAutocaptureSeriesShortcuts,- buildEventTypeFilterShortcuts,-} from 'lib/components/TaxonomicFilter/eventTypeShortcuts'-import { RECENT_PINNED_TAB_DEFINITIONS } from 'lib/components/TaxonomicFilter/recentPinnedTabDefinitions'-import {- DataWarehousePopoverField,- SimpleOption,- TaxonomicDefinitionTypes,- TaxonomicFilterGroup,- TaxonomicFilterGroupType,- TaxonomicFilterValue,-} from 'lib/components/TaxonomicFilter/types'-import { fuzzyEventSearchEnabled } from 'lib/components/TaxonomicFilter/utils/fuzzyEventSearch'-import { hiddenEventNames } from 'lib/components/TaxonomicFilter/utils/hiddenEvents'-import { withKeywordShortcuts } from 'lib/components/TaxonomicFilter/utils/keywordShortcuts'-import {- MCP_TOOL_CALL_EVENT,- MCP_TOOL_CALL_SUGGESTED_PROPERTIES,- getMCPExcludedEventProperties,- getMCPPropertyFilterOptions,- includesMCPAnalyticsEvents,-} from 'lib/components/TaxonomicFilter/utils/mcpProperties'-import { isEmailLikeSearch, isUrlLikeSearch } from 'lib/components/TaxonomicFilter/utils/valueSearchQuery'-import { FEATURE_FLAGS } from 'lib/constants'-import { IconCohort } from 'lib/lemon-ui/icons'-import { Link } from 'lib/lemon-ui/Link'-import { isString } from 'lib/utils/guards'-import { pluralize } from 'lib/utils/strings'-import {- getAccountCustomPropertyDefinitionIcon,- getAccountFieldDefinitionIcon,- getEventDefinitionIcon,- getEventMetadataDefinitionIcon,- getPersonPropertyDefinitionIcon,- getPropertyDefinitionIcon,- getRevenueAnalyticsDefinitionIcon,-} from 'scenes/data-management/events/DefinitionHeader'-import { dataWarehouseSettingsSceneLogic } from 'scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic'-import { COHORT_BEHAVIORAL_LIMITATIONS_URL } from 'scenes/feature-flags/constants'-import {- getProductEventFilterOptions,- getProductEventPropertyFilterOptions,-} from 'scenes/hog-functions/filters/productEventFilterOptions'-import { MaxContextTaxonomicFilterOption } from 'scenes/max/maxTypes'-import { NotebookType } from 'scenes/notebooks/types'-import { SavedFiltersTaxonomicGroup } from 'scenes/session-recordings/filters/SavedFiltersTaxonomicGroup'--import { actionsModel } from '~/models/actionsModel'-import { dashboardsModel } from '~/models/dashboardsModel'-import { AnyDataNode, DatabaseSchemaField, DatabaseSchemaTable } from '~/queries/schema/schema-general'-import { getCoreFilterDefinition, getFilterLabel } from '~/taxonomy/helpers'-import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'-import {- ActionType,- CohortType,- CoreFilterDefinition,- DashboardType,- EventDefinition,- EventDefinitionType,- Experiment,- FeatureFlagType,- PersonProperty,- PersonType,- PropertyDefinition,- PropertyDefinitionType,- PropertyFilterType,- InsightModel,- SessionRecordingPlaylistType,- TeamType,-} from '~/types'--import { CohortRealtimeTag } from 'products/cohorts/frontend/realtime/CohortRealtimeTag'-import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'-import { experimentsLogic } from 'products/experiments/frontend/scenes/experimentsLogic'-import { PersonSearchMatchTags } from 'products/persons/frontend/components/PersonSearchMatchTags'-import type { PersonListRecordApi } from 'products/persons/frontend/generated/api.schemas'-import { LazyHogFlowTaxonomicFilters } from 'products/workflows/frontend/Workflows/hogflows/filters/LazyHogFlowTaxonomicFilters'--import { InlineHogQLEditor } from '../InlineHogQLEditor'--const TRAFFIC_TYPE_VIRTUAL_PROPERTIES = [- '$virt_is_bot',- '$virt_traffic_type',- '$virt_traffic_category',- '$virt_bot_name',-]--// Stable reference for CohortsWithAllUsers options to prevent cascading re-renders.-// taxonomicGroups has 14 dependencies that change during initial mount. Each change creates-// new group objects with inline options arrays, causing rawLocalItems → fuse → localItems →-// items → selectedItem reference changes. With CohortsWithAllUsers, selectedItemHasPopover-// returns true (getValue returns 'all'), so ControlledDefinitionPopover renders and its-// useEffect dispatches setDefinition on every selectedItem change, triggering kea store updates-// that combined with react-window's layout effect setState exceed React's 50-update limit.-const COHORTS_WITH_ALL_USERS_OPTIONS: CohortType[] = [{ id: 'all', name: 'All Users*' } as unknown as CohortType]--export const eventTaxonomicGroupProps: Pick<TaxonomicFilterGroup, 'getPopoverHeader' | 'getIcon'> = {- getPopoverHeader: (eventDefinition: EventDefinition): string => {- if (CORE_FILTER_DEFINITIONS_BY_GROUP.events[eventDefinition.name]) {- return 'PostHog event'- }- return `${eventDefinition.verified ? 'Verified' : 'Unverified'} event`- },- getIcon: getEventDefinitionIcon,-}--export const propertyTaxonomicGroupProps = (- coreDefinitionsGroup?: Record<string, CoreFilterDefinition>-): Pick<TaxonomicFilterGroup, 'getPopoverHeader' | 'getIcon'> => ({- getPopoverHeader: (propertyDefinition: PropertyDefinition): string => {- const coreGroup = coreDefinitionsGroup ?? CORE_FILTER_DEFINITIONS_BY_GROUP.event_properties- if (coreGroup[propertyDefinition.name]) {- return 'PostHog property'- }- return 'Property'- },- getIcon: getPropertyDefinitionIcon,-})--export const defaultDataWarehousePopoverFields: DataWarehousePopoverField[] = [- {- key: 'id_field',- label: 'ID Field',- },- {- key: 'timestamp_field',- label: 'Timestamp Field',- allowHogQL: true,- },- {- key: 'distinct_id_field',- label: 'Distinct ID Field',- allowHogQL: true,- },-]--/**- * Pure inputs for buildTaxonomicGroups. Mirrors the dependency list of the- * `taxonomicGroups` selector in taxonomicFilterLogic.tsx — keep in sync.- */-export interface BuildTaxonomicGroupsContext {- currentTeam: TeamType- projectId: number | null- groupAnalyticsTaxonomicGroups: TaxonomicFilterGroup[]- groupAnalyticsTaxonomicGroupNames: TaxonomicFilterGroup[]- eventNames: string[]- /**- * The picker's requested group types — read by group definitions that adapt to which- * tabs are present (e.g. Event properties excludes the known MCP schema only when the- * MCP properties tab is there to host it).- */- taxonomicGroupTypes?: TaxonomicFilterGroupType[]- /**- * Distinct promoted properties for events currently in context. Surfaced first in the- * SuggestedFilters tab so the team's chosen "summary" property is one click away.- */- promotedPropertiesForContextEvents?: string[]- schemaColumns: DatabaseSchemaField[]- schemaColumnsLoading: boolean | undefined- metadataSource: AnyDataNode- suggestedFiltersLabel: string | undefined- propertyFilters: {- excludedProperties: Partial<Record<TaxonomicFilterGroupType, (string | number | null)[]>>- propertyAllowList?: Partial<Record<TaxonomicFilterGroupType, (string | number | null)[]>>- showNumericalPropsOnly?: boolean- }- eventMetadataPropertyDefinitions: PropertyDefinition[]- personMetadataPropertyDefinitions: PropertyDefinition[]- maxContextOptions: MaxContextTaxonomicFilterOption[]- hideBehavioralCohorts: boolean- /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */- showCohortFlagTargeting: boolean- endpointFilters: Record<string, any> | undefined- hogQLExpressionComponentProps: {- globals?: Record<string, any>- showBreakdownLabelHint: boolean- }- featureFlags: Record<string, boolean | string | undefined>- /** Keep offering events whose data is moving out of the `events` table. See `TaxonomicFilterProps`. */- includeHiddenEvents?: boolean- /** The picker offers "Use event name" for a search with no matches. See `TaxonomicFilterProps`. */- allowNonCapturedEvents?: boolean-}--export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): TaxonomicFilterGroup[] {- const {- currentTeam,- projectId,- groupAnalyticsTaxonomicGroups,- groupAnalyticsTaxonomicGroupNames,- eventNames,- promotedPropertiesForContextEvents = [],- schemaColumns,- schemaColumnsLoading,- metadataSource,- suggestedFiltersLabel,- propertyFilters,- eventMetadataPropertyDefinitions,- personMetadataPropertyDefinitions,- maxContextOptions,- hideBehavioralCohorts,- showCohortFlagTargeting,- endpointFilters,- hogQLExpressionComponentProps,- featureFlags,- includeHiddenEvents,- allowNonCapturedEvents,- } = ctx- const { id: teamId } = currentTeam- const fuzzyEventSearch = fuzzyEventSearchEnabled(featureFlags, allowNonCapturedEvents)- const { excludedProperties, propertyAllowList, showNumericalPropsOnly } = propertyFilters- // Opt the cohort picker into the trimmed `?basic=true` payload (drops the- // query/groups/last_error_message/experiment_set fields the picker never reads;- // `filters` is kept). Gated by a flag so the smaller response shape can be rolled- // out and rolled back independently.- const cohortsEndpointParams = featureFlags[FEATURE_FLAGS.COHORTS_TAXONOMIC_BASIC_LIST] ? { basic: true } : undefined- const groups: TaxonomicFilterGroup[] = [- {- name: 'Events',- searchPlaceholder: 'events',- type: TaxonomicFilterGroupType.Events,- options: [{ name: 'All events', value: null }].filter(- (o) => !excludedProperties[TaxonomicFilterGroupType.Events]?.includes(o.value)- ),- endpoint: combineUrl(`api/projects/${projectId}/event_definitions`, {- event_type: EventDefinitionType.Event,- exclude_hidden: true,- fuzzy_search: fuzzyEventSearch,- }).url,- // The caller's record already carries the hidden names. Appending them again keeps the- // group hiding them even if some future caller passes a record that skipped the fold,- // and the set drops the repeat so it stays out of `useGroupList`'s cache key.- excludedProperties: [- ...new Set([- ...(excludedProperties?.[TaxonomicFilterGroupType.Events]?.filter(isString) ?? []),- ...hiddenEventNames(currentTeam?.flag_evaluations_mode, includeHiddenEvents),- ]),- ],- ...withKeywordShortcuts<Record<string, any>>(- {- getName: (eventDefinition) => eventDefinition.name,- getValue: (eventDefinition) =>- 'id' in eventDefinition ? eventDefinition.name : eventDefinition.value,- getIcon: eventTaxonomicGroupProps.getIcon,- getPopoverHeader: eventTaxonomicGroupProps.getPopoverHeader,- },- {- popoverHeader: 'Autocapture shortcut',- buildShortcuts: buildAutocaptureSeriesShortcuts,- }- ),- },- {- name: 'Internal Events',- searchPlaceholder: 'internal events',- type: TaxonomicFilterGroupType.InternalEvents,- options: [- { name: 'All internal events', value: null },- ...getProductEventFilterOptions('activity-log').map((item) => ({- name: item.label,- value: item.value,- })),- ],- getName: (eventDefinition: Record<string, any>) => eventDefinition.name,- getValue: (eventDefinition: Record<string, any>) =>- 'id' in eventDefinition ? eventDefinition.name : eventDefinition.value,- ...eventTaxonomicGroupProps,- },- {- name: 'Activity log properties',- searchPlaceholder: 'activity log properties',- type: TaxonomicFilterGroupType.ActivityLogProperties,- options: getProductEventPropertyFilterOptions('activity-log').map((value) => ({- name: value,- value,- group: TaxonomicFilterGroupType.EventProperties,- })),- getIcon: getPropertyDefinitionIcon,- getPopoverHeader: () => 'Activity log properties',- },- {- name: 'Workflow variables',- searchPlaceholder: 'variable key',- type: TaxonomicFilterGroupType.WorkflowVariables,- categoryLabel: () => 'Workflow variables',- render: LazyHogFlowTaxonomicFilters,- getPopoverHeader: () => 'Workflow variables',- },- {- name: 'Actions',- searchPlaceholder: 'actions',- type: TaxonomicFilterGroupType.Actions,- logic: actionsModel,- value: 'actionsSorted',- getName: (action: ActionType) => action.name || '',- getValue: (action: ActionType) => action.id,- getPopoverHeader: () => 'Action',- getIcon: getEventDefinitionIcon,- },- {- name: 'Data warehouse tables',- searchPlaceholder: 'data warehouse tables',- type: TaxonomicFilterGroupType.DataWarehouse,- logic: dataWarehouseSettingsSceneLogic,- value: 'dataWarehouseTablesAndViews',- valueLoading: 'databaseLoading',- getName: (table: DatabaseSchemaTable) => table.name,- getValue: (table: DatabaseSchemaTable) => table.name,- getPopoverHeader: () => 'Data Warehouse Table',- getIcon: () => <IconServer />,- },- ...(schemaColumns.length > 0 || schemaColumnsLoading- ? [- {- name: 'Data warehouse properties',- searchPlaceholder: 'data warehouse properties',- type: TaxonomicFilterGroupType.DataWarehouseProperties,- options: schemaColumns,- getName: (col: DatabaseSchemaField) => col.name,- getValue: (col: DatabaseSchemaField) => col.name,- getPopoverHeader: () => 'Data Warehouse Column',- getIcon: () => <IconServer />,- },- ]- : []),- {- name: 'Extended person properties',- searchPlaceholder: 'extended person properties',- type: TaxonomicFilterGroupType.DataWarehousePersonProperties,- logic: joinsLogic,- value: 'columnsJoinedToPersons',- getName: (personProperty: PersonProperty) => personProperty.name,- getValue: (personProperty: PersonProperty) => personProperty.id,- getPopoverHeader: () => 'Extended Person Property',- },- {- name: 'Autocapture elements',- searchPlaceholder: 'autocapture elements',- type: TaxonomicFilterGroupType.Elements,- options: (['tag_name', 'text', 'href', 'selector'] as const)- .filter((option) => !excludedProperties[TaxonomicFilterGroupType.Elements]?.includes(option))- .map((option) => ({- name: option,- })) as SimpleOption[],- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => 'Autocapture Element',- },- {- name: 'Metadata',- searchPlaceholder: 'metadata',- type: TaxonomicFilterGroupType.Metadata,- // populate options using `optionsFromProp` depending on context in which- // this taxonomic group type is used- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- ...propertyTaxonomicGroupProps(CORE_FILTER_DEFINITIONS_BY_GROUP.metadata),- },- {- name: 'Event properties',- searchPlaceholder: 'event properties',- type: TaxonomicFilterGroupType.EventProperties,- endpoint: combineUrl(`api/projects/${projectId}/property_definitions`, {- is_feature_flag: false,- ...(eventNames.length > 0 ? { event_names: eventNames } : {}),- properties: propertyAllowList?.[TaxonomicFilterGroupType.EventProperties]- ? propertyAllowList[TaxonomicFilterGroupType.EventProperties].join(',')- : undefined,- exclude_hidden: true,- }).url,- scopedEndpoint:- eventNames.length > 0- ? combineUrl(`api/projects/${projectId}/property_definitions`, {- event_names: eventNames,- is_feature_flag: false,- filter_by_event_names: true,- properties: propertyAllowList?.[TaxonomicFilterGroupType.EventProperties]- ? propertyAllowList[TaxonomicFilterGroupType.EventProperties].join(',')- : undefined,- exclude_hidden: true,- }).url- : undefined,- expandLabel: ({ count, expandedCount }: { count: number; expandedCount: number }) =>- `Show ${pluralize(expandedCount - count, 'property', 'properties')} that ${pluralize(- expandedCount - count,- 'has',- 'have',- false- )}n't been seen with ${pluralize(eventNames.length, 'this event', 'these events', false)}`,- excludedProperties: [- ...(excludedProperties?.[TaxonomicFilterGroupType.EventProperties]?.filter(isString) ?? []),- ...(!featureFlags[FEATURE_FLAGS.TRAFFIC_TYPE_VIRTUAL_PROPERTIES]- ? TRAFFIC_TYPE_VIRTUAL_PROPERTIES- : []),- // The known MCP schema lives only in its own group when that tab is- // present — excluded via the same mechanism as TRAFFIC_TYPE_VIRTUAL_PROPERTIES- // above; the exclusivity intent is documented on getMCPExcludedEventProperties.- ...getMCPExcludedEventProperties(eventNames, ctx.taxonomicGroupTypes),- ],- propertyAllowList: propertyAllowList?.[TaxonomicFilterGroupType.EventProperties]?.filter(isString),- ...withKeywordShortcuts<PropertyDefinition>(- {- getName: (propertyDefinition) => propertyDefinition.name,- getValue: (propertyDefinition) => propertyDefinition.name,- ...propertyTaxonomicGroupProps(),- },- {- popoverHeader: 'Event type shortcut',- buildShortcuts: buildEventTypeFilterShortcuts,- }- ),- },- {- name: 'Internal event properties',- searchPlaceholder: 'internal event properties',- type: TaxonomicFilterGroupType.InternalEventProperties,- options: getProductEventPropertyFilterOptions('activity-log').map((value) => ({- name: value,- value,- group: TaxonomicFilterGroupType.EventProperties,- })),- getIcon: getPropertyDefinitionIcon,- getPopoverHeader: () => 'Internal event properties',- },- // Only offered when the picker is scoped to canonical MCP events, so the- // known @posthog/mcp schema is separated out without adding a tab anywhere else.- ...(includesMCPAnalyticsEvents(eventNames)- ? [- {- name: 'MCP properties',- searchPlaceholder: 'MCP properties',- type: TaxonomicFilterGroupType.MCPProperties,- options: getMCPPropertyFilterOptions().map((value) => ({- name: value,- value,- group: TaxonomicFilterGroupType.EventProperties,- })),- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getIcon: getPropertyDefinitionIcon,- getPopoverHeader: () => 'MCP property',- },- ]- : []),- {- name: 'Event metadata',- searchPlaceholder: 'event metadata',- type: TaxonomicFilterGroupType.EventMetadata,- options: eventMetadataPropertyDefinitions,- getIcon: (option: PropertyDefinition) => getEventMetadataDefinitionIcon(option),- getName: (option: PropertyDefinition) => {- const coreDefinition = getCoreFilterDefinition(option.id, TaxonomicFilterGroupType.EventMetadata)- return coreDefinition ? coreDefinition.label : option.name- },- getValue: (option: PropertyDefinition) => option.id,- valuesEndpoint: (key) => {- return `api/event/values/?key=${encodeURIComponent(key)}&is_column=true`- },- getPopoverHeader: () => 'Event metadata',- },- {- name: 'Feature flags',- searchPlaceholder: 'feature flags',- type: TaxonomicFilterGroupType.EventFeatureFlags,- endpoint: combineUrl(`api/projects/${projectId}/property_definitions`, {- is_feature_flag: true,- ...(eventNames.length > 0 ? { event_names: eventNames } : {}),- }).url,- scopedEndpoint:- eventNames.length > 0- ? combineUrl(`api/projects/${projectId}/property_definitions`, {- event_names: eventNames,- is_feature_flag: true,- filter_by_event_names: true,- }).url- : undefined,- expandLabel: ({ count, expandedCount }: { count: number; expandedCount: number }) =>- `Show ${pluralize(expandedCount - count, 'property', 'properties')} that ${pluralize(- expandedCount - count,- 'has',- 'have',- false- )}n't been seen with ${pluralize(eventNames.length, 'this event', 'these events', false)}`,- getName: (propertyDefinition: PropertyDefinition) => propertyDefinition.name,- getValue: (propertyDefinition: PropertyDefinition) => propertyDefinition.name,- excludedProperties: excludedProperties?.[TaxonomicFilterGroupType.EventFeatureFlags]?.filter(isString),- ...propertyTaxonomicGroupProps(),- },- {- name: 'Issues',- searchPlaceholder: 'issues',- type: TaxonomicFilterGroupType.ErrorTrackingIssues,- options: Object.entries(CORE_FILTER_DEFINITIONS_BY_GROUP[TaxonomicFilterGroupType.ErrorTrackingIssues])- .map(([key, { label }]) => ({- value: key,- name: label,- }))- .filter((o) => !excludedProperties[TaxonomicFilterGroupType.ErrorTrackingIssues]?.includes(o.value)),- getName: (option) => option.name,- getValue: (option) => option.value,- valuesEndpoint: (key) => `api/projects/${projectId}/error_tracking/issues/values?key=` + key,- getPopoverHeader: () => 'Issues',- },- {- name: 'Exception properties',- searchPlaceholder: 'exceptions',- type: TaxonomicFilterGroupType.ErrorTrackingProperties,- options: [- ...getProductEventPropertyFilterOptions('error-tracking').map((value) => ({- name: value,- value,- group: TaxonomicFilterGroupType.EventProperties,- propertyFilterType: PropertyFilterType.Event,- })),- ...(currentTeam?.person_display_name_properties- ? currentTeam.person_display_name_properties.map((property) => ({- name: property,- value: property,- group: TaxonomicFilterGroupType.PersonProperties,- propertyFilterType: PropertyFilterType.Person,- }))- : []),- ],- getName: (option) => option.name,- getValue: (option) => option.value,- getIcon: getPropertyDefinitionIcon,- getPopoverHeader: () => 'Exception properties',- },- {- name: 'Revenue analytics properties',- searchPlaceholder: 'revenue analytics properties',- type: TaxonomicFilterGroupType.RevenueAnalyticsProperties,- options: Object.entries(- CORE_FILTER_DEFINITIONS_BY_GROUP[TaxonomicFilterGroupType.RevenueAnalyticsProperties]- )- .map(([key, { type: property_type }]) => ({- id: key,- name: key,- value: key,- property_type,- type: PropertyDefinitionType.RevenueAnalytics,- }))- .filter(- (o) => !excludedProperties[TaxonomicFilterGroupType.RevenueAnalyticsProperties]?.includes(o.value)- ),- getIcon: getRevenueAnalyticsDefinitionIcon,- getName: (option: PropertyDefinition) => {- const coreDefinition = getCoreFilterDefinition(- option.id,- TaxonomicFilterGroupType.RevenueAnalyticsProperties- )-- return coreDefinition ? coreDefinition.label : option.name- },- getValue: (option: PropertyDefinition) => option.id,- valuesEndpoint: (key) => {- return `api/projects/${projectId}/revenue_analytics/taxonomy/values?key=${encodeURIComponent(key)}`- },- getPopoverHeader: () => 'Revenue analytics properties',- },- {- name: 'Account fields',- searchPlaceholder: 'account fields',- type: TaxonomicFilterGroupType.AccountFields,- getIcon: getAccountFieldDefinitionIcon,- getName: (option: PropertyDefinition) => option.name,- getValue: (option: PropertyDefinition) => option.id,- getPopoverHeader: () => 'Account field',- },- {- name: 'Account relationships',- searchPlaceholder: 'account relationships',- type: TaxonomicFilterGroupType.AccountRelationships,- getIcon: getAccountFieldDefinitionIcon,- getName: (option: PropertyDefinition) => option.name,- getValue: (option: PropertyDefinition) => option.id,- getPopoverHeader: () => 'Account relationship',- },- {- name: 'Account custom properties',- searchPlaceholder: 'account custom properties',- type: TaxonomicFilterGroupType.AccountCustomProperties,- // Mirrors the legacy taxonomicFilterLogic group: account custom property definitions- // are per-team API data, so the options come from the consumer via `optionsFromProp` —- // items carry `{ id, name, description, is_canonical, property_type }` with the- // definition id as the value.- getIcon: getAccountCustomPropertyDefinitionIcon,- getName: (option: PropertyDefinition) => option.name,- getValue: (option: PropertyDefinition) => option.id,- valuesEndpoint: (key) =>- `api/projects/${projectId}/custom_property_definitions/values/?key=${encodeURIComponent(key)}`,- getPopoverHeader: () => 'Custom property',- },- {- name: 'Logs',- searchPlaceholder: 'logs',- type: TaxonomicFilterGroupType.Logs,- options: [- { key: 'message', name: 'message', propertyFilterType: 'log' },- { key: 'severity_level', name: 'severity_level', propertyFilterType: 'log' },- { key: 'trace_id', name: 'trace_id', propertyFilterType: 'log' },- { key: 'span_id', name: 'span_id', propertyFilterType: 'log' },- ].filter((o) => !excludedProperties[TaxonomicFilterGroupType.Logs]?.includes(o.key)),- localItemsSearch: (items: any[], q: string): any[] => {- if (!q) {- return items- }- const matches = items.filter((item) => item.name?.toLowerCase().includes(q.toLowerCase()))- // Mirrors the legacy Logs group in taxonomicFilterLogic: the free-text message-search- // item only makes sense where picking `message` does.- if (excludedProperties[TaxonomicFilterGroupType.Logs]?.includes('message')) {- return matches- }- return [- {- key: 'message',- name: 'Search log message for "' + q + '"',- value: q,- propertyFilterType: 'log',- },- ].concat(matches)- },- getName: (option: { key: string; name: string }) => option.name,- getValue: (option: { key: string; name: string }) => option.key,- getPopoverHeader: () => 'Log attributes',- },- {- name: 'Log attributes',- searchPlaceholder: 'attributes',- type: TaxonomicFilterGroupType.LogAttributes,- endpoint: combineUrl(`api/projects/${projectId}/logs/attributes`, {- attribute_type: 'log',- search_values: 'true',- ...endpointFilters,- }).url,- valuesEndpoint: (key) =>- combineUrl(`api/projects/${projectId}/logs/values`, {- attribute_type: 'log',- key: key,- ...endpointFilters,- }).url,- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => 'Log attributes',- },- {- name: 'Resource attributes',- searchPlaceholder: 'resources',- type: TaxonomicFilterGroupType.LogResourceAttributes,- endpoint: combineUrl(`api/projects/${projectId}/logs/attributes`, {- attribute_type: 'resource',- search_values: 'true',- ...endpointFilters,- }).url,- valuesEndpoint: (key) =>- combineUrl(`api/projects/${projectId}/logs/values`, {- attribute_type: 'resource',- key: key,- ...endpointFilters,- }).url,- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => 'Resource attributes',- },- {- name: 'Metric attributes',- searchPlaceholder: 'attributes',- type: TaxonomicFilterGroupType.MetricAttributes,- endpoint: combineUrl(`api/projects/${projectId}/metrics/attributes`, {- ...endpointFilters,- }).url,- valuesEndpoint: (key) =>- combineUrl(`api/projects/${projectId}/metrics/attribute_values`, {- key: key,- ...endpointFilters,- }).url,- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => 'Metric attributes',- },- {- name: 'Spans',- searchPlaceholder: 'spans',- type: TaxonomicFilterGroupType.Spans,- options: [- { key: 'name', name: 'name', propertyFilterType: 'span' },- { key: 'kind', name: 'kind', propertyFilterType: 'span' },- { key: 'duration', name: 'duration (ms)', propertyFilterType: 'span' },- { key: 'trace_id', name: 'trace_id', propertyFilterType: 'span' },- { key: 'span_id', name: 'span_id', propertyFilterType: 'span' },- { key: 'status_code', name: 'status code', propertyFilterType: 'span' },- ],- valuesEndpoint: (key) =>- key === 'name'- ? combineUrl(`api/projects/${projectId}/tracing/spans/values`, {- attribute_type: 'span',- key: key,- ...endpointFilters,- }).url- : undefined,- getName: (option: { key: string; name: string }) => option.name,- getValue: (option: { key: string; name: string }) => option.key,- getPopoverHeader: () => 'Span attributes',- },- {- name: 'Span attributes',- searchPlaceholder: 'span attributes',- type: TaxonomicFilterGroupType.SpanAttributes,- endpoint: combineUrl(`api/projects/${projectId}/tracing/spans/attributes`, {- attribute_type: 'span_attribute',- search_values: 'true',- ...endpointFilters,- }).url,- valuesEndpoint: (key) =>- combineUrl(`api/projects/${projectId}/tracing/spans/values`, {- attribute_type: 'span_attribute',- key: key,- ...endpointFilters,- }).url,- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => 'Span attributes',- },- {- name: 'Span resource attributes',- searchPlaceholder: 'span resources',- type: TaxonomicFilterGroupType.SpanResourceAttributes,- endpoint: combineUrl(`api/projects/${projectId}/tracing/spans/attributes`, {- attribute_type: 'span_resource_attribute',- search_values: 'true',- ...endpointFilters,- }).url,- valuesEndpoint: (key) =>- combineUrl(`api/projects/${projectId}/tracing/spans/values`, {- attribute_type: 'span_resource_attribute',- key: key,- ...endpointFilters,- }).url,- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => 'Span resource attributes',- },- {- name: 'Numerical event properties',- searchPlaceholder: 'numerical event properties',- type: TaxonomicFilterGroupType.NumericalEventProperties,- endpoint: combineUrl(`api/projects/${projectId}/property_definitions`, {- is_numerical: true,- event_names: eventNames,- }).url,- getName: (propertyDefinition: PropertyDefinition) => propertyDefinition.name,- getValue: (propertyDefinition: PropertyDefinition) => propertyDefinition.name,- ...propertyTaxonomicGroupProps(),- },- {- name: 'Person properties',- searchPlaceholder: 'person properties',- type: TaxonomicFilterGroupType.PersonProperties,- endpoint: combineUrl(`api/projects/${projectId}/property_definitions`, {- type: 'person',- properties: propertyAllowList?.[TaxonomicFilterGroupType.PersonProperties]- ? propertyAllowList[TaxonomicFilterGroupType.PersonProperties].join(',')- : undefined,- exclude_hidden: true,- }).url,- getName: (personProperty: PersonProperty) => personProperty.name,- getValue: (personProperty: PersonProperty) => personProperty.name,- propertyAllowList: propertyAllowList?.[TaxonomicFilterGroupType.PersonProperties]?.filter(isString),- ...propertyTaxonomicGroupProps(CORE_FILTER_DEFINITIONS_BY_GROUP.person_properties),- getIcon: getPersonPropertyDefinitionIcon,- },- {- name: 'Person metadata',- searchPlaceholder: 'person metadata',- type: TaxonomicFilterGroupType.PersonMetadata,- options: personMetadataPropertyDefinitions,- getIcon: getPropertyDefinitionIcon,- getName: (option: PropertyDefinition) => {- const coreDefinition = getCoreFilterDefinition(option.id, TaxonomicFilterGroupType.PersonMetadata)- return coreDefinition ? coreDefinition.label : option.name- },- getValue: (option: PropertyDefinition) => option.id,- getPopoverHeader: () => 'Person metadata',- },- {- name: 'Cohorts',- searchPlaceholder: 'cohorts',- type: TaxonomicFilterGroupType.Cohorts,- endpoint: combineUrl(`api/projects/${projectId}/cohorts/`, cohortsEndpointParams).url,- value: 'cohorts',- // See taxonomicFilterLogic — cohort populations comfortably fit- // in one page; cache the first 100 and fuse-filter typed- // queries locally to avoid per-keystroke round-trips.- clientFilterFirstPage: true,- getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,- getValue: (cohort: CohortType) => cohort.id,- getTag: showCohortFlagTargeting- ? (cohort: CohortType) => <CohortRealtimeTag realtime={cohort.realtime} />- : undefined,- getPopoverHeader: (cohort: CohortType) => `${cohort.is_static ? 'Static' : 'Dynamic'} Cohort`,- getIcon: function _getIcon(): JSX.Element {- return <IconCohort className="taxonomy-icon taxonomy-icon-muted" />- },- footerMessage: hideBehavioralCohorts ? (- <>- <Link to={COHORT_BEHAVIORAL_LIMITATIONS_URL} target="_blank">- Some cohorts excluded due to containing behavioral filters.- </Link>- </>- ) : undefined,- },- {- name: 'Cohorts',- searchPlaceholder: 'cohorts',- type: TaxonomicFilterGroupType.CohortsWithAllUsers,- endpoint: combineUrl(`api/projects/${projectId}/cohorts/`, cohortsEndpointParams).url,- clientFilterFirstPage: true,- options: COHORTS_WITH_ALL_USERS_OPTIONS,- getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,- getValue: (cohort: CohortType) => cohort.id,- getTag: showCohortFlagTargeting- ? (cohort: CohortType) => <CohortRealtimeTag realtime={cohort.realtime} />- : undefined,- getPopoverHeader: () => `All Users`,- getIcon: function _getIcon(): JSX.Element {- return <IconCohort className="taxonomy-icon taxonomy-icon-muted" />- },- },- // PageviewUrls returns a URL string value, used in paths and property filters.- // PageviewEvents creates a $pageview event with $current_url property filter,- // used in trends and funnels series pickers.- {- name: 'Pageview URLs',- searchPlaceholder: 'pageview URLs',- type: TaxonomicFilterGroupType.PageviewUrls,- endpoint: `api/projects/${teamId}/events/values/?key=$current_url&event_name=$pageview`,- searchAlias: 'value',- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => `Pageview URL`,- minSearchQueryLength: 3,- shouldSearch: featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_VALUE_SEARCH_GATING]- ? isUrlLikeSearch- : undefined,- searchQueryHint: 'Search for a URL, domain, or path.',- searchDescription: 'URLs seen on pageview events',- },- {- name: 'Pageview events',- searchPlaceholder: 'pageview events',- type: TaxonomicFilterGroupType.PageviewEvents,- endpoint: `api/projects/${teamId}/events/values/?key=$current_url&event_name=$pageview`,- searchAlias: 'value',- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => `Pageview event`,- minSearchQueryLength: 3,- shouldSearch: featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_VALUE_SEARCH_GATING]- ? isUrlLikeSearch- : undefined,- searchQueryHint: 'Search for a URL, domain, or path.',- searchDescription: 'pageview events filtered by URL',- },- // Screens returns a screen name value, used in paths and property filters.- // ScreenEvents creates a $screen event with $screen_name property filter,- // used in trends and funnels series pickers.- {- name: 'Screens',- searchPlaceholder: 'screens',- type: TaxonomicFilterGroupType.Screens,- endpoint: `api/projects/${teamId}/events/values/?key=$screen_name&event_name=$screen`,- searchAlias: 'value',- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => `Screen`,- minSearchQueryLength: 3,- searchDescription: 'screen names seen on screen events',- },- {- name: 'Screen events',- searchPlaceholder: 'screen events',- type: TaxonomicFilterGroupType.ScreenEvents,- endpoint: `api/projects/${teamId}/events/values/?key=$screen_name&event_name=$screen`,- searchAlias: 'value',- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => `Screen event`,- minSearchQueryLength: 3,- searchDescription: 'screen events filtered by screen name',- },- {- name: 'Email addresses',- searchPlaceholder: 'email addresses',- type: TaxonomicFilterGroupType.EmailAddresses,- endpoint: `api/projects/${teamId}/persons/values/?key=email`,- searchAlias: 'value',- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => `Email address`,- minSearchQueryLength: 5,- shouldSearch: featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_VALUE_SEARCH_GATING]- ? isEmailLikeSearch- : undefined,- searchQueryHint: 'Search for an email address or domain.',- searchDescription: 'email addresses seen in person properties',- },- {- name: 'Autocapture events',- searchPlaceholder: 'autocapture events',- type: TaxonomicFilterGroupType.AutocaptureEvents,- endpoint: `api/projects/${teamId}/events/values/?key=$el_text&event_name=$autocapture`,- searchAlias: 'value',- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => `Autocapture event`,- minSearchQueryLength: 3,- searchDescription: 'element text seen on autocapture events',- },- {- name: 'Custom Events',- searchPlaceholder: 'custom events',- type: TaxonomicFilterGroupType.CustomEvents,- endpoint: combineUrl(`api/projects/${projectId}/event_definitions`, {- event_type: EventDefinitionType.EventCustom,- exclude_hidden: true,- fuzzy_search: fuzzyEventSearch,- }).url,- getName: (eventDefinition: EventDefinition) => eventDefinition.name,- getValue: (eventDefinition: EventDefinition) => eventDefinition.name,- ...eventTaxonomicGroupProps,- },- {- name: 'Wildcards',- searchPlaceholder: 'wildcards',- type: TaxonomicFilterGroupType.Wildcards,- // Populated via optionsFromProp- getName: (option: SimpleOption) => option.name,- getValue: (option: SimpleOption) => option.name,- getPopoverHeader: () => `Wildcard`,- },- {- name: 'Persons',- searchPlaceholder: 'persons',- type: TaxonomicFilterGroupType.Persons,- endpoint: `api/projects/${teamId}/persons/?include_matched_fields=true`,- getName: (person: PersonType) => person.name || 'Anon user?',- getValue: (person: PersonType) => person.distinct_ids?.[0],- getTag: (person: PersonListRecordApi) => <PersonSearchMatchTags matchedFields={person.matched_fields} />,- getPopoverHeader: () => `Person`,- },- {- name: 'Insights',- searchPlaceholder: 'insights',- type: TaxonomicFilterGroupType.Insights,- endpoint: combineUrl(`api/projects/${teamId}/insights/`, {- saved: true,- }).url,- getName: (insight: InsightModel) => insight.name,- getValue: (insight: InsightModel) => insight.short_id,- getPopoverHeader: () => `Insights`,- },- {- name: 'Feature Flags',- searchPlaceholder: 'feature flags',- type: TaxonomicFilterGroupType.FeatureFlags, // Feature flag dependencies- endpoint: combineUrl(`api/projects/${projectId}/feature_flags/`).url,- getName: (featureFlag: FeatureFlagType) => {- const name = featureFlag.key || featureFlag.name- const isInactive = featureFlag.active === false- return isInactive ? `${name} (disabled)` : name- },- getValue: (featureFlag: FeatureFlagType) => featureFlag.id || '',- getPopoverHeader: () => `Feature Flags`,- getIcon: (featureFlag: FeatureFlagType) => (- <IconFlag className={clsx('size-4', featureFlag.active === false && 'text-muted-alt opacity-50')} />- ),- // Recently-used entries are stored stripped of `active`, so treat only an explicit- // `false` as disabled — otherwise recent flags are wrongly disabled and unselectable.- // Keep in sync with the Feature Flags group in taxonomicFilterLogic.tsx.- getIsDisabled: (featureFlag: FeatureFlagType) => featureFlag.active === false,- localItemsSearch: (items: TaxonomicDefinitionTypes[], query: string): TaxonomicDefinitionTypes[] => {- // Note: This function doesn't have direct access to the current value- // The actual filtering logic needs to be implemented in the infinite list logic- // For now, just handle search filtering- if (!query) {- return items- }-- return items.filter((item: TaxonomicDefinitionTypes) => {- // Type guard for FeatureFlagType- if ('key' in item && 'name' in item) {- const flag = item as unknown as FeatureFlagType- return (flag.key || flag.name || '').toLowerCase().includes(query.toLowerCase())- }- // For other types, check if they have a name property- if ('name' in item) {- return (item.name || '').toLowerCase().includes(query.toLowerCase())- }- return true- })- },- excludedProperties: excludedProperties?.[TaxonomicFilterGroupType.FeatureFlags]?.filter(isString),- },- {- name: 'Experiments',- searchPlaceholder: 'experiments',- type: TaxonomicFilterGroupType.Experiments,- logic: experimentsLogic,- value: 'experiments',- getName: (experiment: Experiment) => experiment.name,- getValue: (experiment: Experiment) => experiment.id,- getPopoverHeader: () => `Experiments`,- },- {- name: 'Dashboards',- searchPlaceholder: 'dashboards',- type: TaxonomicFilterGroupType.Dashboards,- logic: dashboardsModel,- value: 'nameSortedDashboards',- valueLoading: 'dashboardsLoading',- getName: (dashboard: DashboardType) => dashboard.name,- getValue: (dashboard: DashboardType) => dashboard.id,- getPopoverHeader: () => `Dashboards`,- },- {- name: 'Notebooks',- searchPlaceholder: 'notebooks',- type: TaxonomicFilterGroupType.Notebooks,- value: 'notebooks',- endpoint: `api/projects/${projectId}/notebooks/`,- getName: (notebook: NotebookType) => notebook.title || `Notebook ${notebook.short_id}`,- getValue: (notebook: NotebookType) => notebook.short_id,- getPopoverHeader: () => 'Notebooks',- },- {- name: 'Session properties',- searchPlaceholder: 'sessions',- type: TaxonomicFilterGroupType.SessionProperties,- ...(propertyAllowList- ? {- options: propertyAllowList[TaxonomicFilterGroupType.SessionProperties]- ?.filter(isString)- ?.map((property: string) => ({- name: property,- value: property,- })),- }- : {- endpoint: `api/projects/${teamId}/sessions/property_definitions`,- }),- getName: (option: any) => option.name,- getValue: (option) => option.name,- getPopoverHeader: () => 'Session',- getIcon: getPropertyDefinitionIcon,- },- {- name: 'SQL expression',- searchPlaceholder: null,- categoryLabel: () => 'SQL expression',- type: TaxonomicFilterGroupType.HogQLExpression,- render: InlineHogQLEditor,- // The headless menu derives the committed value via group.getValue(item);- // without this the SQL expression resolves to null and the selection is- // silently dropped on save.- getValue: (option) => (option as { value?: TaxonomicFilterValue }).value ?? option.name,- getPopoverHeader: () => 'SQL expression',- componentProps: { metadataSource, ...hogQLExpressionComponentProps },- },- {- name: 'Replay',- searchPlaceholder: 'Replay',- type: TaxonomicFilterGroupType.Replay,- options: [- {- key: 'visited_page',- name: getFilterLabel('visited_page', TaxonomicFilterGroupType.Replay),- propertyFilterType: PropertyFilterType.Recording,- },- {- key: 'snapshot_source',- name: getFilterLabel('snapshot_source', TaxonomicFilterGroupType.Replay),- propertyFilterType: PropertyFilterType.Recording,- },- {- key: 'level',- name: getFilterLabel('level', TaxonomicFilterGroupType.LogEntries),- propertyFilterType: PropertyFilterType.LogEntry,- },- {- key: 'message',- name: getFilterLabel('message', TaxonomicFilterGroupType.LogEntries),- propertyFilterType: PropertyFilterType.LogEntry,- },- {- key: 'comment_text',- name: getFilterLabel('comment_text', TaxonomicFilterGroupType.Replay),- propertyFilterType: PropertyFilterType.Recording,- },- {- key: 'click_count',- name: getFilterLabel('click_count', TaxonomicFilterGroupType.Replay),- propertyFilterType: PropertyFilterType.Recording,- },- {- key: 'keypress_count',- name: getFilterLabel('keypress_count', TaxonomicFilterGroupType.Replay),- propertyFilterType: PropertyFilterType.Recording,- },- {- key: 'mouse_activity_count',- name: getFilterLabel('mouse_activity_count', TaxonomicFilterGroupType.Replay),- propertyFilterType: PropertyFilterType.Recording,- },- ],- getName: (option: Record<string, any>) => option.name,- getValue: (option: Record<string, any>) => option.key,- valuesEndpoint: (key) => {- if (key === 'visited_page') {- return (- `api/projects/${teamId}/events/values/?key=` +- encodeURIComponent('$current_url') +- '&event_name=' +- encodeURIComponent('$pageview')- )- }- },- getPopoverHeader: () => 'Replay',- },- {- name: 'Saved filters',- searchPlaceholder: 'saved filters',- type: TaxonomicFilterGroupType.ReplaySavedFilters,- endpoint: combineUrl(`api/projects/${projectId}/session_recording_playlists/`, {- type: 'filters',- order: '-last_modified_at',- }).url,- // Recording playlists are tiny per team — cache the first page- // and let fuse handle keystrokes locally.- clientFilterFirstPage: true,- render: SavedFiltersTaxonomicGroup,- getName: (filter: SessionRecordingPlaylistType) => filter.name || filter.derived_name || 'Unnamed',- getValue: (filter: SessionRecordingPlaylistType) => filter.short_id,- getPopoverHeader: () => 'Saved filter',- },- {- name: 'On this page',- searchPlaceholder: 'elements from this page',- type: TaxonomicFilterGroupType.MaxAIContext,- options: maxContextOptions,- getName: (option: MaxContextTaxonomicFilterOption) => option.name,- getValue: (option: MaxContextTaxonomicFilterOption) => option.value,- getIcon: (option: MaxContextTaxonomicFilterOption) => {- const IconComponent = option.icon- return <IconComponent />- },- getPopoverHeader: () => 'On this page',- },- {- name: suggestedFiltersLabel ?? 'Suggested filters',- searchPlaceholder: (suggestedFiltersLabel ?? 'Suggested filters').toLowerCase(),- categoryLabel: (count: number) =>- (suggestedFiltersLabel ?? 'Suggested filters') + (count > 0 ? `: ${count}` : ''),- type: TaxonomicFilterGroupType.SuggestedFilters,- isLocalOnly: true,- isMetaGroup: true,- options: [- // Promoted properties for any event in context come first — if a team- // has marked a property as the one that summarises this event, it's- // the property they almost certainly want to filter or break down by.- ...promotedPropertiesForContextEvents- .filter(- (name) =>- !showNumericalPropsOnly &&- !excludedProperties[TaxonomicFilterGroupType.EventProperties]?.includes(name) &&- (propertyAllowList?.[TaxonomicFilterGroupType.EventProperties] === undefined ||- propertyAllowList[TaxonomicFilterGroupType.EventProperties]?.includes(name))- )- .map((name) => ({- name,- group: TaxonomicFilterGroupType.EventProperties,- })),- ...(eventNames.includes('$autocapture')- ? (['text', 'selector'] as const)- .filter((name) => !excludedProperties[TaxonomicFilterGroupType.Elements]?.includes(name))- .map((name) => ({- name,- group: TaxonomicFilterGroupType.Elements,- }))- : []),- ...(eventNames.includes(MCP_TOOL_CALL_EVENT)- ? MCP_TOOL_CALL_SUGGESTED_PROPERTIES.map((name) => ({- name,- group: TaxonomicFilterGroupType.EventProperties,- }))- : []),- ],- getName: (item: TaxonomicDefinitionTypes) => ('name' in item ? item.name : '') || '',- getValue: (item: TaxonomicDefinitionTypes): TaxonomicFilterValue =>- 'name' in item ? (item.name ?? null) : null,- getPopoverHeader: () => suggestedFiltersLabel ?? 'Suggested filters',- },- ...RECENT_PINNED_TAB_DEFINITIONS,- ...groupAnalyticsTaxonomicGroups,- ...groupAnalyticsTaxonomicGroupNames,- ]-- return groups-}diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/collapsedContainsRow.ts b/frontend/src/lib/components/TaxonomicFilter/utils/collapsedContainsRow.tsindex a9b8bd609460..3788a9aacd14 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/collapsedContainsRow.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/collapsedContainsRow.ts@@ -5,9 +5,7 @@ import { QuickFilterItem, TaxonomicFilterGroupType } from '../types'/** Groups that collapse to a single "URL contains <query>" suggestion instead of* listing every matching value, and are not offered as a standalone value picker.* People filtering by URL overwhelmingly want a contains match, so one synthetic- * row (when any URL matches) beats a wall of exact URLs. Shared by the legacy- * picker (`infiniteListLogic`) and the rebuild menu (`menu/Combobox`) so both arms- * of the experiment collapse identically.+ * row (when any URL matches) beats a wall of exact URLs. Used by `infiniteListLogic`.** - `PageviewUrls` is the property-filter flavour ($current_url IContains <query>).* - `PageviewEvents` is the series flavour: a `$pageview` event filtered by the same@@ -22,12 +20,12 @@ const URL_SHAPED_QUERY = /[/.:]//** In a property filter's mixed list, page URLs offer the "URL contains" row only for a query like* `/pricing` or `example.com`. A plain word such as `email` usually names a property, and people* often picked the row for it by mistake. Series pickers and the dedicated Pageview URLs tab offer- * the row for any query. Shared by both surfaces. */+ * the row for any query. */export function offersUrlContainsRow(groupType: TaxonomicFilterGroupType, query: string): boolean {return groupType !== TaxonomicFilterGroupType.PageviewUrls || URL_SHAPED_QUERY.test(query)}-export function urlContainsRowLabel(query: string): string {+function urlContainsRowLabel(query: string): string {return `URL contains "${query}"`}@@ -41,9 +39,7 @@ export function urlContainsRowLabel(query: string): string {* - series host (`ActionFilterRow`) expands it into a `$pageview` event + the* `$current_url IContains` property filter (reads `eventName`);* - property/universal hosts intentionally ignore `eventName` (a property filter- * can't sprout an event) and commit the bare `$current_url IContains` filter;- * - the rebuild menu commits PageviewEvents via the group `type`, not `eventName`- * (its synthetic row is a plain item, not this QuickFilterItem). */+ * can't sprout an event) and commit the bare `$current_url IContains` filter. */export function buildUrlContainsShortcut(query: string, groupType?: TaxonomicFilterGroupType): QuickFilterItem {return {_type: 'quick_filter',@@ -57,17 +53,13 @@ export function buildUrlContainsShortcut(query: string, groupType?: TaxonomicFil}}-/** A row that is the synthetic "URL contains <query>" shortcut. Deliberately checks the- * tag directly rather than via `isQuickFilterItem`, because the rebuild menu's shortcut- * is a plain item (not a QuickFilterItem) while the legacy list's is a QuickFilterItem —- * both carry `isContainsShortcut`. */-export function isContainsShortcutItem(item: unknown): boolean {+/** A row that is the synthetic "URL contains <query>" shortcut. */+function isContainsShortcutItem(item: unknown): boolean {return !!item && typeof item === 'object' && (item as { isContainsShortcut?: boolean }).isContainsShortcut === true}/** Split a list so the synthetic "URL contains <query>" shortcut(s) come first.- * `getItem` maps a list element to its underlying definition item — the rebuild wraps it- * in a `{ item }` entry, the legacy list holds the item directly. Returns `[shortcuts, rest]`+ * `getItem` maps a list element to its underlying definition item. Returns `[shortcuts, rest]`* so callers can either lead with the shortcut or splice other rows (recents/pinned) between. */export function partitionContainsShortcuts<T>(list: T[], getItem: (entry: T) => unknown): [T[], T[]] {const shortcuts: T[] = []diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/floatRecentPinned.ts b/frontend/src/lib/components/TaxonomicFilter/utils/floatRecentPinned.tsindex d08142bc7f24..67336a92d975 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/floatRecentPinned.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/floatRecentPinned.ts@@ -31,8 +31,7 @@ export function pinnedSourceKey(item: TaxonomicDefinitionTypes): string | null {// float to the top, then pinned, then everything else keeps its order. The list stays flat// and deduped — each item appears once, because we reorder the group's own results in place// rather than prepending copies. `keyOf` keys a group result the same way recent/pinned-// entries are keyed (via `groupItemKey`) so the tiers line up. Shared by the legacy-// `infiniteListLogic` and the rebuild `useGroupList`.+// entries are keyed (via `groupItemKey`) so the tiers line up.//// A present synthetic aggregate row (e.g. "All events", whose value is null) leads and keeps// its place — a promoted real item never displaces the group's own catch-all row. Skeletonsdiff --git a/frontend/src/lib/components/TaxonomicFilter/utils/floatToFront.ts b/frontend/src/lib/components/TaxonomicFilter/utils/floatToFront.tsindex 5180624276e2..1893bf24688d 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/floatToFront.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/floatToFront.ts@@ -1,8 +1,7 @@/** Move the element at `index` to `offset` (0 by default, or 1 to preserve a leading* catch-all row), preserving the order of everything else.* No-op when `index <= offset` (already in place, or not found via `findIndex` -> -1).- * Shared by the rebuild menu's `Combobox` and the legacy `infiniteListLogic`- * for the committed-selection promotion; callers choose the offset per surface. */+ * `infiniteListLogic` uses it for the committed-selection promotion. */export function floatToFront<T>(list: T[], index: number, offset = 0): T[] {if (index <= offset) {return listdiff --git a/frontend/src/lib/components/TaxonomicFilter/utils/keywordShortcuts.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/keywordShortcuts.tsxdeleted file mode 100644index 2c9388f26a4e..000000000000--- a/frontend/src/lib/components/TaxonomicFilter/utils/keywordShortcuts.tsx+++ /dev/null@@ -1,52 +0,0 @@-import { IconCursor } from '@posthog/icons'--import {- QuickFilterItem,- TaxonomicFilterGroup,- TaxonomicFilterValue,- isQuickFilterItem,-} from 'lib/components/TaxonomicFilter/types'--export function keywordShortcutValue(item: QuickFilterItem): string {- // Synthetic identity string used only as a React/selection key. Never parsed by consumers.- return JSON.stringify({- q: item.propertyKey,- v: item.filterValue,- e: item.eventName ?? null,- })-}--export type BaseGroupFns<T> = {- getName: (instance: T) => string- getValue: (instance: T) => TaxonomicFilterValue- getIcon?: (instance: T) => JSX.Element- getPopoverHeader: (instance: T) => string-}--/** Extend a group's presentation methods so they also handle `QuickFilterItem`s (keyword- * shortcuts), and attach a `keywordShortcuts` builder. `popoverHeader` lets each group label- * its own shortcut kind (e.g. "Autocapture shortcut" for series, "Event type shortcut" for- * property filters). */-export function withKeywordShortcuts<T>(- base: BaseGroupFns<T>,- {- popoverHeader,- buildShortcuts,- }: {- popoverHeader: string- buildShortcuts: (searchQuery: string) => QuickFilterItem[]- }-): Pick<TaxonomicFilterGroup, 'getName' | 'getValue' | 'getIcon' | 'getPopoverHeader' | 'keywordShortcuts'> {- const baseGetIcon = base.getIcon- return {- getName: (item: T | QuickFilterItem) => (isQuickFilterItem(item) ? item.name : base.getName(item)),- getValue: (item: T | QuickFilterItem) =>- isQuickFilterItem(item) ? keywordShortcutValue(item) : base.getValue(item),- getIcon: baseGetIcon- ? (item: T | QuickFilterItem) => (isQuickFilterItem(item) ? <IconCursor /> : baseGetIcon(item))- : undefined,- getPopoverHeader: (item: T | QuickFilterItem) =>- isQuickFilterItem(item) ? popoverHeader : base.getPopoverHeader(item),- keywordShortcuts: buildShortcuts,- }-}diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts b/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.tsindex fb481faf1baa..8b24299e8f0d 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts@@ -1,8 +1,3 @@-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import {- buildTaxonomicGroups,- BuildTaxonomicGroupsContext,-} from 'lib/components/TaxonomicFilter/utils/buildTaxonomicGroups'import {MCP_TOOL_CALL_EVENT,getMCPPropertyFilterOptions,@@ -10,9 +5,6 @@ import {} from 'lib/components/TaxonomicFilter/utils/mcpProperties'import { getPrimaryPropertyForEvent } from 'lib/utils/events'-import { NodeKind } from '~/queries/schema/schema-general'-import { TeamType } from '~/types'-describe('mcpProperties', () => {it('leads with the funnel-relevant properties and derives the rest of the known schema', () => {const options = getMCPPropertyFilterOptions()@@ -49,92 +41,4 @@ describe('mcpProperties', () => {// tool-call funnel steps and event rows describe themselves by tool name.expect(getPrimaryPropertyForEvent(MCP_TOOL_CALL_EVENT)).toBe('$mcp_tool_name')})-- describe('rebuild group availability (buildTaxonomicGroups)', () => {- const baseContext: BuildTaxonomicGroupsContext = {- currentTeam: { id: 997 } as TeamType,- projectId: 997,- groupAnalyticsTaxonomicGroups: [],- groupAnalyticsTaxonomicGroupNames: [],- eventNames: [],- schemaColumns: [],- schemaColumnsLoading: false,- metadataSource: { kind: NodeKind.HogQLQuery, query: 'select event from events' },- suggestedFiltersLabel: undefined,- propertyFilters: { excludedProperties: {} },- eventMetadataPropertyDefinitions: [],- personMetadataPropertyDefinitions: [],- maxContextOptions: [],- hideBehavioralCohorts: false,- showCohortFlagTargeting: false,- endpointFilters: undefined,- hogQLExpressionComponentProps: { showBreakdownLabelHint: false },- featureFlags: {},- }-- it('only offers the MCP properties group when scoped to canonical MCP events', () => {- const unscoped = buildTaxonomicGroups(baseContext)- expect(unscoped.find((g) => g.type === TaxonomicFilterGroupType.MCPProperties)).toBeUndefined()-- const scoped = buildTaxonomicGroups({ ...baseContext, eventNames: [MCP_TOOL_CALL_EVENT] })- const mcpGroup = scoped.find((g) => g.type === TaxonomicFilterGroupType.MCPProperties)- expect(mcpGroup).toBeTruthy()- // Options remap to EventProperties so selecting one creates a plain event property filter.- expect(mcpGroup?.options?.[0]).toEqual({- name: '$mcp_tool_name',- value: '$mcp_tool_name',- group: TaxonomicFilterGroupType.EventProperties,- })- })-- it.each([- {- name: 'excludes the known schema from Event properties when the MCP tab is requested',- eventNames: [MCP_TOOL_CALL_EVENT],- taxonomicGroupTypes: [TaxonomicFilterGroupType.MCPProperties, TaxonomicFilterGroupType.EventProperties],- expectExcluded: true,- },- {- name: 'keeps Event properties intact when the MCP tab is not requested',- eventNames: [MCP_TOOL_CALL_EVENT],- taxonomicGroupTypes: [TaxonomicFilterGroupType.EventProperties],- expectExcluded: false,- },- {- name: 'keeps Event properties intact when not scoped to MCP events',- eventNames: ['$pageview'],- taxonomicGroupTypes: [TaxonomicFilterGroupType.MCPProperties, TaxonomicFilterGroupType.EventProperties],- expectExcluded: false,- },- ])('$name', ({ eventNames, taxonomicGroupTypes, expectExcluded }) => {- const groups = buildTaxonomicGroups({ ...baseContext, eventNames, taxonomicGroupTypes })- const eventProperties = groups.find((g) => g.type === TaxonomicFilterGroupType.EventProperties)- if (expectExcluded) {- // Exclusive like autocapture: the known schema lives only in the MCP tab.- // The concrete key guards against arrayContaining([]) matching vacuously.- expect(eventProperties?.excludedProperties).toContain('$mcp_tool_name')- expect(eventProperties?.excludedProperties).toEqual(- expect.arrayContaining(getMCPPropertyFilterOptions())- )- } else {- expect(eventProperties?.excludedProperties ?? []).not.toContain('$mcp_tool_name')- }- })-- it('seeds $mcp_is_error into SuggestedFilters when scoped to $mcp_tool_call', () => {- const scoped = buildTaxonomicGroups({ ...baseContext, eventNames: [MCP_TOOL_CALL_EVENT] })- const suggested = scoped.find((g) => g.type === TaxonomicFilterGroupType.SuggestedFilters)- expect(suggested?.options).toContainEqual({- name: '$mcp_is_error',- group: TaxonomicFilterGroupType.EventProperties,- })-- const unscoped = buildTaxonomicGroups(baseContext)- const unscopedSuggested = unscoped.find((g) => g.type === TaxonomicFilterGroupType.SuggestedFilters)- expect(unscopedSuggested?.options).not.toContainEqual({- name: '$mcp_is_error',- group: TaxonomicFilterGroupType.EventProperties,- })- })- })})diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.ts b/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.tsindex 491ea6c9eb4e..630da3cc9f3b 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.ts@@ -3,8 +3,7 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { CORE_FILTER_DEFINITIONS_BY_GROUP, POSTHOG_EVENT_PROMOTED_PROPERTIES } from '~/taxonomy/taxonomy'/**- * MCP analytics helpers shared by the legacy taxonomic filter (`taxonomicFilterLogic.tsx`)- * and the rebuild (`buildTaxonomicGroups.tsx`), so the two variants can't drift.+ * MCP analytics helpers for the taxonomic filter (`taxonomicFilterLogic.tsx`).** Events captured by the @posthog/mcp SDK carry a known `$mcp_*` property schema.* The `mcp_properties` group in `posthog/taxonomy/taxonomy.py` (the `$mcp_`-prefixed@@ -20,7 +19,7 @@ export const MCP_TOOL_CALL_EVENT = '$mcp_tool_call'* group always offers the full known schema (event-specific properties' popovers say* which event carries them). The frozen legacy names (`mcp_tool_call`, ...) carry an* unprefixed property schema, so they deliberately don't get the dedicated group. */-export function isMCPAnalyticsEventName(eventName: string): boolean {+function isMCPAnalyticsEventName(eventName: string): boolean {// eventNames is assembled dynamically by many surfaces; unlike the `.includes()`// scope checks alongside this one, `.startsWith` would throw on a stray null.return typeof eventName === 'string' && eventName.startsWith('$mcp_')@@ -49,9 +48,7 @@ export function getMCPPropertyFilterOptions(): string[] {/** Seeded into the Suggested tab when the picker is scoped to `$mcp_tool_call`, so* success/failure splits are one click away. `$mcp_tool_name` also lands there via- * the event's `primary_property` — in the legacy picker through taxonomicFilterLogic,- * and in the rebuild through `promotedPropertiesForContextEvents` (computed by- * `useTaxonomicGroupsContext`). */+ * the event's `primary_property`, through taxonomicFilterLogic. */export const MCP_TOOL_CALL_SUGGESTED_PROPERTIES: string[] = ['$mcp_is_error']/** When the MCP properties group is available in a picker, the known schema isdiff --git a/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts b/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.tsindex 40790ba6be50..86d249575041 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts@@ -1,7 +1,7 @@import { SkeletonItem, TaxonomicDefinitionTypes, isSkeletonItem } from 'lib/components/TaxonomicFilter/types'/** Search terms mapped to properties that should be promoted when that exact term is searched. */-export const PROMOTED_PROPERTIES_BY_SEARCH_TERM: Record<string, string[]> = {+const PROMOTED_PROPERTIES_BY_SEARCH_TERM: Record<string, string[]> = {url: ['$current_url'],path: ['$pathname'],email: ['$email'],diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.ts b/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.tsindex d3474f189ab3..83b318b751d4 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/suggestedContextFilters.ts@@ -8,11 +8,6 @@ import {TaxonomicFilterGroupType,} from 'lib/components/TaxonomicFilter/types'-/*- * The legacy `infiniteListLogic` picker and the rebuild both call these helpers,- * so a change to recent or pinned behavior reaches both.- */-/** Recents whose source group is one of the picker's groups, with operators the* host can't represent filtered out, and (when selecting a key only) deduped by* storage key, so the picker stops surfacing recents that belong to adiff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicMenuToggle.test.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicMenuToggle.test.tsxdeleted file mode 100644index 78167d16147f..000000000000--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicMenuToggle.test.tsx+++ /dev/null@@ -1,38 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, screen } from '@testing-library/react'-import { Provider } from 'kea'--import { initKeaTests } from '~/test/init'--import { SuppressTaxonomicMenuToggle, TaxonomicMenuToggle } from './TaxonomicMenuToggle'--describe('TaxonomicMenuToggle', () => {- beforeEach(() => {- initKeaTests()- })-- afterEach(() => {- cleanup()- })-- it('renders the menu-switch badge by default', () => {- render(- <Provider>- <TaxonomicMenuToggle />- </Provider>- )- expect(screen.getByTestId('taxonomic-menu-toggle')).toBeInTheDocument()- })-- it('renders nothing inside SuppressTaxonomicMenuToggle', () => {- render(- <Provider>- <SuppressTaxonomicMenuToggle>- <TaxonomicMenuToggle />- </SuppressTaxonomicMenuToggle>- </Provider>- )- expect(screen.queryByTestId('taxonomic-menu-toggle')).not.toBeInTheDocument()- })-})diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicMenuToggle.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicMenuToggle.tsxdeleted file mode 100644index 8fb2c8534372..000000000000--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicMenuToggle.tsx+++ /dev/null@@ -1,69 +0,0 @@-import { useActions, useValues } from 'kea'-import { ReactNode, createContext, useContext } from 'react'--import { IconClockRewind, IconFlask } from '@posthog/icons'--import { Tooltip } from 'lib/lemon-ui/Tooltip/Tooltip'--import { taxonomicMenuPreferenceLogic } from './taxonomicMenuPreferenceLogic'--/**- * Hides the menu toggle within a subtree without disabling the- * `taxonomic-filter-menu-rebuild` experiment: the user's chosen menu still- * renders, only the in-context switch badge is suppressed. Backed by React- * context, so it propagates through popover portals — wrapping a filter bar- * also covers the pickers rendered in its overlays (e.g. web analytics).- */-const MenuToggleSuppressionContext = createContext(false)--export function SuppressTaxonomicMenuToggle({ children }: { children: ReactNode }): JSX.Element {- return <MenuToggleSuppressionContext.Provider value={true}>{children}</MenuToggleSuppressionContext.Provider>-}--/**- * Floating corner badge rendered over every taxonomic filter trigger- * (legacy or rebuilt) wherever the `taxonomic-filter-menu-rebuild` flag is- * on. Flips the global `taxonomicMenuPreferenceLogic` so the user can opt- * in/out of the rebuilt menu everywhere at once.- *- * Positioned `absolute` inside the trigger's top-right corner — the parent- * must be `relative`. Kept inside the trigger box (no negative offset) so- * an `overflow-hidden` ancestor can't clip it.- *- * Renders nothing inside a `<SuppressTaxonomicMenuToggle>` subtree.- */-export function TaxonomicMenuToggle(): JSX.Element | null {- if (useContext(MenuToggleSuppressionContext)) {- return null- }- return <MenuToggleButton />-}--function MenuToggleButton(): JSX.Element {- const { useNewMenu } = useValues(taxonomicMenuPreferenceLogic)- const { setUseNewMenu } = useActions(taxonomicMenuPreferenceLogic)-- // Symmetric, state-neutral labels — the rebuilt menu is the default, so- // framing it as "beta / try" would mislabel the primary experience.- const label = useNewMenu ? 'Switch to the classic filter' : 'Switch to the new filter'-- return (- <Tooltip title={label}>- <button- type="button"- aria-label={label}- data-attr="taxonomic-menu-toggle"- onClick={(e) => {- // Don't let the click fall through to the trigger button- // underneath (which would open the picker).- e.preventDefault()- e.stopPropagation()- setUseNewMenu(!useNewMenu)- }}- className="absolute top-0 right-0 z-10 flex size-3.5 items-center justify-center rounded-full rounded-tr-sm border border-accent bg-surface-primary text-accent shadow-sm transition-opacity hover:opacity-70"- >- {useNewMenu ? <IconClockRewind className="size-2.5" /> : <IconFlask className="size-2.5" />}- </button>- </Tooltip>- )-}diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.test.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.test.tsxindex 57bdb3603478..3a64b16c22c8 100644--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.test.tsx+++ b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.test.tsx@@ -5,15 +5,12 @@ import userEvent from '@testing-library/user-event'import { Provider } from 'kea'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useMocks } from '~/mocks/jest'import { groupsModel } from '~/models/groupsModel'import { initKeaTests } from '~/test/init'import { mockGetEventDefinitions } from '~/test/mocks'-import { taxonomicMenuPreferenceLogic } from './taxonomicMenuPreferenceLogic'import { TaxonomicPopover, TaxonomicStringPopover } from './TaxonomicPopover'jest.mock('lib/components/AutoSizer', () => ({@@ -43,8 +40,6 @@ describe('TaxonomicPopover', () => {})afterEach(() => {- featureFlagLogic.actions.setFeatureFlags([], {})- taxonomicMenuPreferenceLogic.actions.setUseNewMenu(true)cleanup()})@@ -80,7 +75,7 @@ describe('TaxonomicPopover', () => {})})- it('resets the legacy picker search after closing completely', async () => {+ it('resets the picker search after closing completely', async () => {renderPopover()await userEvent.click(screen.getByText('Please select'))@@ -94,25 +89,6 @@ describe('TaxonomicPopover', () => {expect(screen.getByTestId('taxonomic-filter-searchfield')).toHaveValue('')})- it('opens the rebuilt actions picker', async () => {- featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]: true })- taxonomicMenuPreferenceLogic.mount()- taxonomicMenuPreferenceLogic.actions.setUseNewMenu(true)-- renderPopover({- groupType: TaxonomicFilterGroupType.Actions,- groupTypes: [TaxonomicFilterGroupType.Actions],- })-- await userEvent.click(screen.getByTestId('taxonomic-popover-menu-trigger'))- await userEvent.click(screen.getByTestId('taxonomic-filter-menu-new'))-- await waitFor(() => {- expect(screen.getByTestId('menu-filter-search')).toBeInTheDocument()- })- })-it('opens dropdown on click and calls onChange with correct args on selection', async () => {const { onChange } = renderPopover({ placeholder: 'Select an event' })await userEvent.click(screen.getByText('Select an event'))diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsxindex 9652d0a90724..515f9187064b 100644--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx+++ b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx@@ -1,11 +1,9 @@import { Placement } from '@floating-ui/react'-import { useValues } from 'kea'import { Ref, forwardRef, useEffect, useId, useState } from 'react'import { IconX } from '@posthog/icons'import { DisplayableEntity } from 'lib/components/EntityFilterInfo'-import { taxonomicTriggerWrapperClassName } from 'lib/components/TaxonomicFilter/menu/triggerLayout'import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import {DataWarehousePopoverField,@@ -16,18 +14,12 @@ import {TaxonomicFilterGroupType,TaxonomicFilterValue,} from 'lib/components/TaxonomicFilter/types'-import { FEATURE_FLAGS } from 'lib/constants'import { LemonButton, LemonButtonProps } from 'lib/lemon-ui/LemonButton'import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { MaxContextTaxonomicFilterOption } from 'scenes/max/maxTypes'import { AnyDataNode, DatabaseSchemaField } from '~/queries/schema/schema-general'-import { taxonomicMenuPreferenceLogic } from './taxonomicMenuPreferenceLogic'-import { TaxonomicMenuToggle } from './TaxonomicMenuToggle'-import { TaxonomicPopoverMenu } from './TaxonomicPopoverMenu'-export interface TaxonomicPopoverProps<ValueType extends TaxonomicFilterValue = TaxonomicFilterValue> extends Omit<LemonButtonProps,'children' | 'onClick' | 'sideAction'@@ -119,10 +111,6 @@ export const TaxonomicPopover = forwardRef(function TaxonomicPopover_<}: TaxonomicPopoverProps<ValueType>,ref: Ref<HTMLButtonElement>): JSX.Element {- const { featureFlags } = useValues(featureFlagLogic)- const { useNewMenu } = useValues(taxonomicMenuPreferenceLogic)- const menuRebuildEnabled = !!featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]-const generatedKey = useId()const taxonomicFilterLogicKey = `taxonomic-popover-${generatedKey}`const [localValue, setLocalValue] = useState<ValueType>(value || ('' as ValueType))@@ -155,7 +143,7 @@ export const TaxonomicPopover = forwardRef(function TaxonomicPopover_<}}, [value]) // oxlint-disable-line react-hooks/exhaustive-deps- const legacyEl = (+ return (<LemonDropdownoverlay={<TaxonomicFilter@@ -217,76 +205,6 @@ export const TaxonomicPopover = forwardRef(function TaxonomicPopover_<)}</LemonDropdown>)-- if (!menuRebuildEnabled) {- return legacyEl- }-- // Menu-rebuild rollout — the rebuilt menu is rendered by default; a- // visible toggle (persisted per-user via `taxonomicMenuPreferenceLogic`)- // lets the user swap back to the classic filter and forward again.- // Gated by `taxonomic-filter-menu-rebuild`.- //- // The rebuilt menu carries its own toggle (inside its trigger wrapper),- // so it's rendered with no extra DOM around it — the trigger inherits- // the call site's layout exactly. The legacy path needs a thin- // positioned wrapper to host the floating toggle.- //- // The rebuilt menu can't honour these legacy capabilities, so a call site- // that needs any of them stays on the classic filter (still with the- // toggle) — no behaviour is silently lost:- // - `allowClear` — the clear (X) affordance- // - `closeOnChange={false}` — keep-open-after-select- // - a forwarded `ref` — the rebuilt trigger can't receive it- //- // `selectingKeyOnly` (key-based onChange) and `definitionPopoverRenderer`- // (the hover definition card) are superseded by the rebuilt menu itself —- // its onChange already commits the resolved key and its preview pane- // replaces the definition popover — so they no longer gate the new menu.- const newMenuSupportsCallSite = !allowClear && closeOnChange && ref == null- if (useNewMenu && newMenuSupportsCallSite) {- return (- <TaxonomicPopoverMenu<ValueType>- groupType={groupType}- value={value}- filter={filter}- groupTypes={groupTypes}- onChange={onChange}- renderValue={renderValue}- placeholder={placeholder}- placeholderClass={placeholderClass}- eventNames={eventNames}- schemaColumns={schemaColumns}- metadataSource={metadataSource}- excludedProperties={excludedProperties}- excludedOperators={excludedOperators}- includeHiddenEvents={includeHiddenEvents}- selectedProperties={selectedProperties}- showNumericalPropsOnly={showNumericalPropsOnly}- dataWarehousePopoverFields={dataWarehousePopoverFields}- maxContextOptions={maxContextOptions}- allowNonCapturedEvents={allowNonCapturedEvents}- suggestedFiltersLabel={suggestedFiltersLabel}- enableKeywordShortcuts={enableKeywordShortcuts}- onOpen={onOpen}- triggerButtonProps={{- icon: buttonPropsRest.icon,- sideIcon: sideIcon,- fullWidth: buttonPropsRest.fullWidth,- size: buttonPropsRest.size,- type: buttonPropsRest.type ?? 'secondary',- className: buttonPropsRest.className,- disabledReason: buttonPropsRest.disabledReason,- }}- />- )- }- return (- <span className={taxonomicTriggerWrapperClassName(buttonPropsRest.fullWidth)}>- {legacyEl}- <TaxonomicMenuToggle />- </span>- )}) as <ValueType extends TaxonomicFilterValue = TaxonomicFilterValue>(props: TaxonomicPopoverProps<ValueType> & { ref?: Ref<HTMLButtonElement> }) => JSX.Elementdiff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.inputTrigger.test.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.inputTrigger.test.tsxdeleted file mode 100644index af38c7a0cf0c..000000000000--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.inputTrigger.test.tsx+++ /dev/null@@ -1,193 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { Provider } from 'kea'--import { __clearTaxonomicResourceCache } from 'lib/components/TaxonomicFilter/hooks/useTaxonomicResource'-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'--import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'-import { groupsModel } from '~/models/groupsModel'-import { performQuery } from '~/queries/query'-import { initKeaTests } from '~/test/init'-import { emptyPaginated } from '~/test/mocks/taxonomicFilterApiMock'-import { EntityTypes, FunnelDatawarehouseFilter } from '~/types'--import { TaxonomicPopoverMenu } from './TaxonomicPopoverMenu'--jest.mock('~/queries/query', () => ({- performQuery: jest.fn(),-}))--jest.mock('posthog-js', () => ({- __esModule: true,- default: { capture: jest.fn() },-}))--jest.mock('lib/api', () => require('~/test/mocks/taxonomicFilterApiMock').buildTaxonomicFilterApiMock())--const apiGet = jest.requireMock('lib/api').default.get as jest.MockedFunction<any>--function renderInputTriggerPopoverMenu(): ReturnType<typeof render> {- return render(- <Provider>- <TaxonomicPopoverMenu- groupType={TaxonomicFilterGroupType.EventProperties}- groupTypes={[TaxonomicFilterGroupType.EventProperties, TaxonomicFilterGroupType.HogQLExpression]}- triggerVariant="input"- onChange={jest.fn()}- />- </Provider>- )-}--describe('TaxonomicPopoverMenu', () => {- beforeEach(() => {- __clearTaxonomicResourceCache()- apiGet.mockReset()- apiGet.mockImplementation(emptyPaginated)- ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })- useMocks({})- initKeaTests()- actionsModel.mount()- groupsModel.mount()- })-- afterEach(() => cleanup())-- it('renders the placeholder input + filter-icon button before arming', () => {- renderInputTriggerPopoverMenu()-- expect(screen.getByTestId('taxonomic-filter-menu-input')).toBeInTheDocument()- expect(screen.getByLabelText('Open filter menu')).toBeInTheDocument()- })-- it('calls onOpen when the button trigger arms the rebuilt menu', async () => {- const onOpen = jest.fn()- render(- <Provider>- <TaxonomicPopoverMenu- groupType={TaxonomicFilterGroupType.Events}- onChange={jest.fn()}- onOpen={onOpen}- />- </Provider>- )-- await userEvent.click(screen.getByTestId('taxonomic-popover-menu-trigger'))-- expect(onOpen).toHaveBeenCalledTimes(1)- })-- it('arms to the dropdown menu (not the combobox) when the filter icon is clicked from the resting trigger', async () => {- renderInputTriggerPopoverMenu()-- await userEvent.click(screen.getByLabelText('Open filter menu'))-- // The icon arms straight to the menu — its "HogQL expression" entry confirms it.- await waitFor(() => {- expect(screen.getByTestId('taxonomic-filter-menu-hogql')).toBeInTheDocument()- })- // It must NOT open the combobox: the icon click must not bubble to the- // input's focus handler, which would arm the combobox instead.- expect(screen.queryByTestId('menu-filter-search')).not.toBeInTheDocument()- })-- it.each(['before opening', 'after opening'] as const)(- 'reopens warehouse configuration when the schema loads %s',- async (schemaTiming) => {- const schema = {- tables: {- orders: {- id: 'orders-table',- name: 'orders',- type: 'data_warehouse',- id_field: 'id',- fields: {- id: { name: 'id', type: 'string' },- distinct_id: { name: 'distinct_id', type: 'string' },- created_at: { name: 'created_at', type: 'datetime' },- },- },- },- joins: [],- results: [],- }- let resolveSchema!: (value: typeof schema) => void- const schemaResponse = new Promise<typeof schema>((resolve) => {- resolveSchema = resolve- })- ;(performQuery as jest.Mock).mockReturnValue(schemaResponse)- const unmount = databaseTableListLogic.mount()- const onChange = jest.fn()- const filter: FunnelDatawarehouseFilter = {- type: EntityTypes.DATA_WAREHOUSE,- id: 'orders',- table_name: 'orders',- id_field: 'distinct_id',- timestamp_field: 'created_at',- aggregation_target_field: 'distinct_id',- }- try {- databaseTableListLogic.actions.loadDatabase({ force: true })- if (schemaTiming === 'before opening') {- resolveSchema(schema)- await waitFor(() =>- expect(databaseTableListLogic.values.dataWarehouseTablesMap.orders).not.toBeUndefined()- )- }- render(- <Provider>- <TaxonomicPopoverMenu- groupType={TaxonomicFilterGroupType.DataWarehouse}- groupTypes={[TaxonomicFilterGroupType.DataWarehouse]}- value="orders"- filter={filter}- dataWarehousePopoverFields={[- { key: 'timestamp_field', label: 'Timestamp Field' },- { key: 'id_field', label: 'Data Warehouse Join Key' },- ]}- onChange={onChange}- />- </Provider>- )-- await userEvent.click(screen.getByText('orders', { selector: 'span' }))- if (schemaTiming === 'after opening') {- expect(screen.getByText('Select a value')).toBeInTheDocument()- resolveSchema(schema)- }- expect(- await screen.findByText('created_at', { selector: '[data-slot="item-title"]' })- ).toBeInTheDocument()- await userEvent.click(screen.getByText('created_at', { selector: '[data-slot="item-title"]' }))- expect(await screen.findByPlaceholderText('Search columns')).toBeInTheDocument()- expect(- await screen.findByText('distinct_id', { selector: '[data-slot="item-title"]' })- ).toBeInTheDocument()- await userEvent.keyboard('{Escape}')- await userEvent.click(screen.getByText('Data Warehouse Join Key', { selector: 'button' }))- expect(- await screen.findByText('distinct_id', { selector: '[data-slot="item-title"]' })- ).toBeInTheDocument()- await userEvent.click(screen.getByText('Select', { exact: true }))-- expect(onChange).toHaveBeenCalledWith(- 'orders',- TaxonomicFilterGroupType.DataWarehouse,- expect.objectContaining({- timestamp_field: 'created_at',- id_field: 'distinct_id',- fields: expect.any(Object),- }),- expect.any(Object)- )- } finally {- unmount()- }- }- )-})diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsxdeleted file mode 100644index 8497b2e4d0d3..000000000000--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx+++ /dev/null@@ -1,376 +0,0 @@-/**- * Central bridge from the legacy `TaxonomicPopover` API to the rebuilt- * `TaxonomicFilterMenu` (dropdown + preview-pane UI).- *- * `TaxonomicPopover` renders this whenever the `taxonomic-filter-menu-rebuild`- * flag is on and the user prefers the new menu, at every popover call site.- *- * The adapter translates `TaxonomicPopover`'s `(value, groupType, item)`- * shape into the headless orchestrator + menu:- * - `value` → a synthetic `MenuFilterEntry` so the trigger reflects the- * current selection and re-opening routes into the right panel.- * - the headless `onChange(group, value, item)` → the legacy- * `onChange(value, groupType, item, group)`.- *- * Lazy mount: the headless orchestrator (`buildTaxonomicGroups` + several- * kea subscriptions) is expensive and the picker is rendered at many call- * sites. So until the user first clicks the trigger, only a lightweight- * placeholder button is rendered — the heavy `ArmedTaxonomicPopoverMenu` is- * mounted on first click and opened immediately via `defaultOpen`.- */-import { useActions, useValues } from 'kea'-import { ReactElement, useEffect, useMemo, useState } from 'react'--import { IconChevronDown, IconFilter } from '@posthog/icons'--import { DisplayableEntity, SeriesRename, getSeriesRename } from 'lib/components/EntityFilterInfo'-import { TaxonomicFilterHeadless } from 'lib/components/TaxonomicFilter/headless'-import { MenuFilterEntry, TaxonomicFilterMenu } from 'lib/components/TaxonomicFilter/menu'-import { MenuInputTrigger } from 'lib/components/TaxonomicFilter/menu/InputTrigger'-import { taxonomicTriggerWrapperClassName } from 'lib/components/TaxonomicFilter/menu/triggerLayout'-import {- AllowedProperties,- DataWarehousePopoverField,- ExcludedOperators,- ExcludedProperties,- SelectedProperties,- SimpleOption,- TaxonomicFilterGroup,- TaxonomicFilterGroupType,- TaxonomicFilterValue,-} from 'lib/components/TaxonomicFilter/types'-import { LemonButton, LemonButtonProps } from 'lib/lemon-ui/LemonButton'-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'-import { MaxContextTaxonomicFilterOption } from 'scenes/max/maxTypes'--import { AnyDataNode, DatabaseSchemaField } from '~/queries/schema/schema-general'--import { TaxonomicMenuToggle } from './TaxonomicMenuToggle'--/**- * Shortcut/aggregator groups that have no real items of their own — a- * selection never genuinely "belongs" to one. `TaxonomicPopover.groupType`- * often defaults to `SuggestedFilters` (e.g. the insights series picker),- * so a synthetic entry stamped with it would lock the combobox to that- * near-empty group instead of opening on the value's real category.- */-const NON_SELECTABLE_GROUP_TYPES: ReadonlySet<TaxonomicFilterGroupType> = new Set([- TaxonomicFilterGroupType.SuggestedFilters,- TaxonomicFilterGroupType.RecentFilters,- TaxonomicFilterGroupType.PinnedFilters,- TaxonomicFilterGroupType.Empty,-])--type TriggerButtonProps = Pick<- LemonButtonProps,- 'icon' | 'sideIcon' | 'fullWidth' | 'size' | 'type' | 'className' | 'disabledReason' | 'truncate'->--export interface TaxonomicPopoverMenuProps<ValueType extends TaxonomicFilterValue = TaxonomicFilterValue> {- groupType: TaxonomicFilterGroupType- value?: ValueType | null- /** The series/entity filter being edited — surfaces its rename on the committed selection. */- filter?: DisplayableEntity- groupTypes?: TaxonomicFilterGroupType[]- /** The 4th arg is the orchestrator's resolved group — consumers that- * need the full `TaxonomicFilterGroup` (not just its type) can use it. */- onChange: (value: ValueType, groupType: TaxonomicFilterGroupType, item: any, group: TaxonomicFilterGroup) => void- renderValue?: (value: ValueType) => JSX.Element | null- placeholder?: React.ReactNode- placeholderClass?: string- eventNames?: string[]- schemaColumns?: DatabaseSchemaField[]- metadataSource?: AnyDataNode- excludedProperties?: ExcludedProperties- excludedOperators?: ExcludedOperators- includeHiddenEvents?: boolean- selectedProperties?: SelectedProperties- propertyAllowList?: AllowedProperties- optionsFromProp?: Partial<Record<TaxonomicFilterGroupType, SimpleOption[]>>- hideBehavioralCohorts?: boolean- /** Mark each cohort row with what feature flags can do with it. See `TaxonomicFilterProps`. */- showCohortFlagTargeting?: boolean- endpointFilters?: Record<string, any>- hogQLGlobals?: Record<string, any>- showNumericalPropsOnly?: boolean- dataWarehousePopoverFields?: DataWarehousePopoverField[]- maxContextOptions?: MaxContextTaxonomicFilterOption[]- allowNonCapturedEvents?: boolean- suggestedFiltersLabel?: string- enableKeywordShortcuts?: boolean- /** Called when the lazy menu is first opened. */- onOpen?: () => void- /** Trigger button styling, forwarded so the rebuilt menu's trigger- * matches the legacy `TaxonomicPopover` button at the call site. */- triggerButtonProps?: TriggerButtonProps- /**- * `'input'` renders a replay-style search box + filter-icon trigger- * instead of a single button, while no value is selected. Focusing the- * box opens the combobox; clicking the icon opens the dropdown menu.- */- triggerVariant?: 'button' | 'input'-}--/**- * Builds the trigger `LemonButton` element — shared by the lazy placeholder- * and the live menu trigger so the two are visually identical. Returns a- * bare `LemonButton` (no wrapper) so base-ui's `DropdownMenuTrigger` can- * render onto it directly and the DOM matches a plain button.- */-function buildTriggerButton(args: {- value: TaxonomicFilterValue | null | undefined- renderValue?: (value: any) => JSX.Element | null- placeholder?: React.ReactNode- placeholderClass?: string- triggerButtonProps?: TriggerButtonProps- open?: boolean- onClick?: () => void-}): ReactElement {- const { value, renderValue, placeholder, placeholderClass, triggerButtonProps, open, onClick } = args- return (- <LemonButton- type="secondary"- {...triggerButtonProps}- // LemonButton only auto-adds the dropdown chevron inside a- // LemonDropdown; this trigger isn't, so default it explicitly- // (legacy parity). A caller passing `sideIcon={null}` still- // suppresses it.- sideIcon={triggerButtonProps?.sideIcon === undefined ? <IconChevronDown /> : triggerButtonProps.sideIcon}- active={open}- onClick={onClick}- data-attr="taxonomic-popover-menu-trigger"- >- {value ? (- (renderValue?.(value) ?? <span>{String(value)}</span>)- ) : (- <span className={placeholderClass ?? 'text-secondary'}>{placeholder}</span>- )}- </LemonButton>- )-}--export function TaxonomicPopoverMenu<ValueType extends TaxonomicFilterValue = TaxonomicFilterValue>(- props: TaxonomicPopoverMenuProps<ValueType>-): JSX.Element {- // Lazy mount — until the user first clicks the trigger, render only the- // placeholder button. Mounting the orchestrator for pickers the user- // never opens would multiply mount cost across every call site on a page.- const [armed, setArmed] = useState(false)- // Which panel the first interaction should land on once armed. The input- // variant has two entry points (search box → combobox, icon → menu); the- // button variant always resolves its own open state, so this is ignored.- const [armOpenTo, setArmOpenTo] = useState<'menu' | 'combobox'>('combobox')-- const {- value,- renderValue,- placeholder = 'Select',- placeholderClass,- triggerButtonProps,- triggerVariant,- onOpen,- } = props- const useInputTrigger = triggerVariant === 'input' && (value == null || value === '')-- if (armed) {- return <ArmedTaxonomicPopoverMenu {...props} defaultOpenState={useInputTrigger ? armOpenTo : undefined} />- }-- const arm = (to: 'menu' | 'combobox'): void => {- onOpen?.()- setArmOpenTo(to)- setArmed(true)- }-- return (- <span className={taxonomicTriggerWrapperClassName(triggerButtonProps?.fullWidth)}>- {useInputTrigger ? (- <MenuInputTrigger- iconButton={- // Keep the resting placeholder visually identical to the armed trigger.- // data-attr differs from the armed trigger's — intentional for analytics.- <LemonButton- size="small"- icon={<IconFilter />}- aria-label="Open filter menu"- data-attr="taxonomic-popover-menu-trigger"- // Stop the click bubbling to the LemonInput wrapper, whose- // onClick focuses the input, whose onFocus arms the combobox.- // Without this the icon would open the combobox, not the menu.- onClick={(e) => {- e.stopPropagation()- arm('menu')- }}- />- }- fullWidth={!!triggerButtonProps?.fullWidth}- placeholder={typeof placeholder === 'string' ? placeholder : 'Add filter'}- onFocus={() => arm('combobox')}- />- ) : (- buildTriggerButton({- value,- renderValue,- placeholder,- placeholderClass,- triggerButtonProps,- onClick: () => arm('combobox'),- })- )}- <TaxonomicMenuToggle />- </span>- )-}--function ArmedTaxonomicPopoverMenu<ValueType extends TaxonomicFilterValue = TaxonomicFilterValue>({- groupType,- value,- filter,- groupTypes,- onChange,- renderValue,- placeholder = 'Select',- placeholderClass,- eventNames = [],- schemaColumns,- metadataSource,- excludedProperties,- excludedOperators,- includeHiddenEvents,- selectedProperties,- propertyAllowList,- optionsFromProp,- hideBehavioralCohorts,- showCohortFlagTargeting,- endpointFilters,- hogQLGlobals,- showNumericalPropsOnly,- dataWarehousePopoverFields,- maxContextOptions,- allowNonCapturedEvents,- suggestedFiltersLabel,- enableKeywordShortcuts,- triggerButtonProps,- triggerVariant,- defaultOpenState,-}: TaxonomicPopoverMenuProps<ValueType> & { defaultOpenState?: 'menu' | 'combobox' }): JSX.Element {- // Data warehouse tables carry their column schema (`fields`) in- // `databaseTableListLogic`, not in the bare popover value — needed so- // the DWH config form can render its column dropdowns / preview. Read- // here (not in the lazy outer component) so non-opened pickers don't- // subscribe to it.- const { dataWarehouseTablesMap } = useValues(databaseTableListLogic)- const { ensureAllTableFields } = useActions(databaseTableListLogic)- useEffect(() => {- if (- groupType === TaxonomicFilterGroupType.DataWarehouse ||- groupTypes?.includes(TaxonomicFilterGroupType.DataWarehouse)- ) {- ensureAllTableFields()- }- }, [groupType, groupTypes, ensureAllTableFields])-- // The group a synthetic `selected` entry should claim. `groupType` is- // the popover's *default tab*, not the value's real category — and it's- // often a non-selectable shortcut group. Fall back to the first real- // group in `groupTypes` so the menu opens on a browsable category.- const selectedGroupType = useMemo<TaxonomicFilterGroupType>(() => {- if (!NON_SELECTABLE_GROUP_TYPES.has(groupType)) {- return groupType- }- return (groupTypes ?? []).find((t) => !NON_SELECTABLE_GROUP_TYPES.has(t)) ?? groupType- }, [groupType, groupTypes])-- // Synthetic entry — the menu reads `group.type` to route the initial- // open and `name` to highlight the matching row. A full- // `TaxonomicFilterGroup` isn't needed; the orchestrator's resolved group- // is used once the user commits. For a data warehouse value, merge in- // the resolved table schema so re-opening lands on a populated config- // form (column dropdowns, preview) rather than an empty one.- const selected = useMemo<MenuFilterEntry | null>(() => {- // Only a primitive scalar can become a synthetic entry — a stray- // array/object value would stringify to junk ("[object Object]").- if (value == null || value === '' || (typeof value !== 'string' && typeof value !== 'number')) {- return null- }- const isDataWarehouse = selectedGroupType === TaxonomicFilterGroupType.DataWarehouse- const item = {- id: value,- name: String(value),- ...(isDataWarehouse ? dataWarehouseTablesMap[String(value)] : {}),- ...(isDataWarehouse ? filter : {}),- }- return {- item,- group: {- type: selectedGroupType,- getName: (t: any) => t?.name,- getValue: (t: any) => t?.name ?? t?.id,- },- name: String(value),- } as unknown as MenuFilterEntry- }, [value, selectedGroupType, dataWarehouseTablesMap, filter])-- // A renamed series doesn't reveal the thing it queries — surface the rename on the- // committed selection's row so the user can connect it to the series they clicked.- const selectedRename = useMemo<SeriesRename | null>(() => getSeriesRename(filter), [filter])-- return (- <TaxonomicFilterHeadless.Root- // `display: contents` — the Root wrapper div must not affect- // layout, so the trigger sizes exactly as a bare button would.- className="contents"- // Skip the legacy rootProps keydown handler — it intercepts- // Tab/Arrow for the old list UI we don't render here.- bindRootProps={false}- taxonomicGroupTypes={groupTypes ?? [groupType]}- groupType={groupType}- value={value ?? undefined}- eventNames={eventNames}- schemaColumns={schemaColumns}- metadataSource={metadataSource}- excludedProperties={excludedProperties}- excludedOperators={excludedOperators}- includeHiddenEvents={includeHiddenEvents}- selectedProperties={selectedProperties}- propertyAllowList={propertyAllowList}- optionsFromProp={optionsFromProp}- hideBehavioralCohorts={hideBehavioralCohorts}- showCohortFlagTargeting={showCohortFlagTargeting}- endpointFilters={endpointFilters}- hogQLGlobals={hogQLGlobals}- showNumericalPropsOnly={showNumericalPropsOnly}- maxContextOptions={maxContextOptions}- allowNonCapturedEvents={allowNonCapturedEvents}- suggestedFiltersLabel={suggestedFiltersLabel}- enableKeywordShortcuts={enableKeywordShortcuts}- onChange={(group, changedValue, item) => {- // Defensive — the orchestrator always resolves a real group- // on commit, but a missing one would crash consumers that- // dereference `group.type`.- if (!group) {- return- }- onChange(changedValue as ValueType, group.type, item, group)- }}- >- <TaxonomicFilterMenu- selected={selected}- selectedRename={selectedRename}- dataWarehousePopoverFields={dataWarehousePopoverFields}- fullWidthTrigger={!!triggerButtonProps?.fullWidth}- triggerAccessory={<TaxonomicMenuToggle />}- triggerVariant={triggerVariant}- // Open immediately — this component is mounted in response- // to the user's first trigger interaction (see `TaxonomicPopoverMenu`).- // `defaultOpenState` routes that open to the panel matching the- // interaction: the search box → combobox, the filter icon → menu.- defaultOpen- defaultOpenState={defaultOpenState}- trigger={({ open }) =>- buildTriggerButton({ value, renderValue, placeholder, placeholderClass, triggerButtonProps, open })- }- />- </TaxonomicFilterHeadless.Root>- )-}diff --git a/frontend/src/lib/components/TaxonomicPopover/taxonomicMenuPreferenceLogic.ts b/frontend/src/lib/components/TaxonomicPopover/taxonomicMenuPreferenceLogic.tsdeleted file mode 100644index 80aad75337f9..000000000000--- a/frontend/src/lib/components/TaxonomicPopover/taxonomicMenuPreferenceLogic.ts+++ /dev/null@@ -1,48 +0,0 @@-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'-import posthog from 'posthog-js'--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface taxonomicMenuPreferenceLogicValues {- useNewMenu: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface taxonomicMenuPreferenceLogicActions {- setUseNewMenu: (useNewMenu: boolean) => {- useNewMenu: boolean- }-}--export type taxonomicMenuPreferenceLogicType = MakeLogicType<- taxonomicMenuPreferenceLogicValues,- taxonomicMenuPreferenceLogicActions->--/**- * Global, persisted preference for which taxonomic filter UI to render- * wherever the `taxonomic-filter-menu-rebuild` flag is enabled.- *- * Defaults to the rebuilt menu; the toggle in `TaxonomicMenuToggle` lets a- * user opt back to the classic filter (and forward again). One logic- * instance, so flipping it anywhere flips every picker at once.- */-export const taxonomicMenuPreferenceLogic = kea<taxonomicMenuPreferenceLogicType>([- path(['lib', 'components', 'TaxonomicPopover', 'taxonomicMenuPreferenceLogic']),- actions({- setUseNewMenu: (useNewMenu: boolean) => ({ useNewMenu }),- }),- reducers({- useNewMenu: [- true,- { persist: true },- {- setUseNewMenu: (_, { useNewMenu }) => useNewMenu,- },- ],- }),- listeners(() => ({- setUseNewMenu: ({ useNewMenu }) => {- posthog.capture('taxonomic filter menu preference changed', { useNewMenu })- },- })),-])diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex a24c1f543278..7dee153dbacc 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -540,7 +540,6 @@ export const FEATURE_FLAGS = {TASKS: 'tasks', // owner: #team-ai-observabilityTAXONOMIC_FILTER_EVENT_MATCH: 'taxonomic-filter-event-match', // owner: @pauldambra multivariate=control,test, experiment: test asks the decision model which core events an events search with no results describes, then suggests them or says why there are none; control asks nothingTAXONOMIC_FILTER_FUZZY_EVENT_SEARCH: 'taxonomic-filter-fuzzy-event-search', // owner: @pauldambra multivariate=control,test, experiment: test makes Events and Custom events searches with no match ask the API for similar event names- TAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model. control changes nothing, banner suggests the right tab, promote moves the predicted group to the top of the All tabTAXONOMIC_FILTER_VALUE_SEARCH_GATING: 'taxonomic-filter-value-search-gating', // owner: @pauldambraTEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cardsdiff --git a/frontend/src/models/cohortsModel.ts b/frontend/src/models/cohortsModel.tsindex 0fd894031209..815ded295a7e 100644--- a/frontend/src/models/cohortsModel.ts+++ b/frontend/src/models/cohortsModel.ts@@ -16,12 +16,6 @@ import type { LocationChangedPayload } from 'kea-router/lib/types'import { v4 as uuidv4 } from 'uuid'import api, { CountedPaginatedResponse } from 'lib/api'-import {- TAXONOMIC_LIST_KEY_FAMILY,- TAXONOMIC_LIST_SEARCH_KEY_FAMILY,- invalidateTaxonomicResourcesWhere,-} from 'lib/components/TaxonomicFilter/hooks/useTaxonomicResource'-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { ConcurrencyController } from 'lib/utils/concurrencyController'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { permanentlyMount } from 'lib/utils/kea-logic-builders'@@ -186,22 +180,6 @@ function processCohortCriteria(criteria: AnyCohortCriteriaType): AnyCohortCriterreturn processedCriteria}-/**- * Predicate for `invalidateTaxonomicResourcesWhere` — matches the cache- * entries belonging to the `Cohorts` / `CohortsWithAllUsers` taxonomic- * groups. `useGroupList.ts` caches under two key families — `remoteKey`- * (`TAXONOMIC_LIST_KEY_FAMILY`) and `serverSearchKey`- * (`TAXONOMIC_LIST_SEARCH_KEY_FAMILY`) — both shaped- * `[family, groupType, ...fetch params]` and growing with new fetch params,- * so rely only on the leading two positions here.- */-function isCohortTaxonomicListKey(key: unknown[]): boolean {- if (key[0] !== TAXONOMIC_LIST_KEY_FAMILY && key[0] !== TAXONOMIC_LIST_SEARCH_KEY_FAMILY) {- return false- }- return key[1] === TaxonomicFilterGroupType.Cohorts || key[1] === TaxonomicFilterGroupType.CohortsWithAllUsers-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface cohortsModelValues {currentTeam: TeamPublicType | TeamType | null // teamLogic@@ -546,17 +524,6 @@ export const cohortsModel = kea<cohortsModelType>([actions.loadAllCohorts()}},- // Flush the TaxonomicFilter cohort cache whenever cohorts mutate- // so the next open of the cohort picker re-fetches the first page.- // The picker pins its request to `?search=&limit=100` and runs- // fuse client-side — invalidation here is what keeps that snappy- // local cache honest after create / update / delete.- cohortCreated: () => {- invalidateTaxonomicResourcesWhere(isCohortTaxonomicListKey)- },- updateCohort: () => {- invalidateTaxonomicResourcesWhere(isCohortTaxonomicListKey)- },loadCohortsSuccess: async ({ cohorts }: { cohorts: CountedPaginatedResponse<CohortType> }) => {const is_calculating = cohorts.results.filter((cohort) => cohort.is_calculating).length > 0if (!is_calculating || !router.values.location.pathname.includes(urls.cohorts())) {@@ -572,16 +539,10 @@ export const cohortsModel = kea<cohortsModelType>([actions.setPollTimeout(window.setTimeout(actions.loadAllCohorts, POLL_TIMEOUT))},deleteCohort: async ({ cohort }) => {- invalidateTaxonomicResourcesWhere(isCohortTaxonomicListKey)await deleteWithUndo({endpoint: api.cohorts.determineDeleteEndpoint(),object: cohort,callback: (undo) => {- if (undo) {- // The delete-time invalidation above already ran; a restore needs its- // own, or pickers keep serving the deleted-state cache for staleTime.- invalidateTaxonomicResourcesWhere(isCohortTaxonomicListKey)- }// Refresh `allCohorts` (the source for `cohortsById`) so an undo restores// the row's name to breadcrumbs and pickers, not just the `cohorts` list.actions.loadAllCohorts()diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsxindex 2a225dbc2bd5..79e8935e7d30 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx@@ -1087,56 +1087,6 @@ describe('ActionFilterRow', () => {expect(screen.queryByText(label)).not.toBeInTheDocument()}})-- it('reopens a flag calls series on the event and picks it again in the rebuilt menu', async () => {- featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]: true })- try {- teamLogic.actions.loadCurrentTeamSuccess({- ...MOCK_DEFAULT_TEAM,- flag_evaluations_mode: FlagEvaluationsModeEnumApi.Number1,- })- const flagCallsNode: SeriesNode = {- kind: NodeKind.DataWarehouseNode,- id: 'posthog.flag_evaluations',- table_name: 'posthog.flag_evaluations',- name: 'Feature flag called',- timestamp_field: 'timestamp',- id_field: 'uuid',- distinct_id_field: 'distinct_id',- }- const { logic, onChange } = setup([flagCallsNode])- renderRow(logic, {- ...INLINE_CONTEXT,- node: flagCallsNode,- flagCallsFromFlagEvaluations: true,- actionsTaxonomicGroupTypes: [- TaxonomicFilterGroupType.Events,- TaxonomicFilterGroupType.Actions,- TaxonomicFilterGroupType.DataWarehouse,- ],- })-- await userEvent.click(screen.getByTestId('taxonomic-popover-menu-trigger'))- await userEvent.type(await screen.findByTestId('menu-filter-search'), '$feature_flag_called')- const options = await screen.findAllByRole('option')- const flagCalledOption = options.find((option) => option.textContent?.includes('Feature flag called'))- await userEvent.click(flagCalledOption!)-- await waitFor(() => {- const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1]?.[0]- expect(lastCall?.[0]).toEqual(- expect.objectContaining({- kind: NodeKind.DataWarehouseNode,- table_name: 'posthog.flag_evaluations',- })- )- })- } finally {- // The flag persists across tests, so the classic-picker tests after this one need it off.- featureFlagLogic.actions.setFeatureFlags([], {})- }- })})describe('all events entity filter', () => {diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsxindex 8d94ed5f41c5..0e1c2c84dbf2 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx@@ -263,12 +263,9 @@ export function ActionFilterRow({)/**- * Shared selection handler for both the legacy `TaxonomicPopover` and the- * new `TaxonomicFilterMenu` / `TaxonomicAutocomplete`. The pseudo-event- * groups (Pageview / Screen / Autocapture events) and quick filters don't- * map to a plain `EntityType` — they expand into a base event plus a- * property filter. Keeping one handler guarantees the new picker behaves- * identically to the legacy one.+ * The pseudo-event groups (Pageview / Screen / Autocapture events) and+ * quick filters don't map to a plain `EntityType` — they expand into a+ * base event plus a property filter.*/const applyTaxonomicSelection = useCallback((@@ -832,7 +829,6 @@ export function ActionFilterRow({excludedProperties={excludedProperties}hogQLGlobals={hogQLGlobals}operatorAllowlist={operatorAllowlist}- triggerVariant="input"framedRows={behavioralFiltersEnabled}addText={behavioralFiltersEnabled ? 'Filter' : undefined}addFilterSuffix={diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsxindex cec23e7a2ae1..a0fc261a7556 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx@@ -19,7 +19,6 @@ import {} from 'lib/components/PropertyFilters/utils'import { baseModifier } from 'lib/components/Shortcuts/shortcuts'import { useShortcut } from 'lib/components/Shortcuts/useShortcut'-import { SuppressTaxonomicMenuToggle } from 'lib/components/TaxonomicPopover/TaxonomicMenuToggle'import { FEATURE_FLAGS } from 'lib/constants'import { IconLink, IconMonitor, IconWithCount } from 'lib/lemon-ui/icons/icons'import { LemonField } from 'lib/lemon-ui/LemonField'@@ -105,15 +104,11 @@ export const WebAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Elemenconst { featureFlags } = useValues(featureFlagLogic)if (featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_FILTERS_V2] || featureFlags[FEATURE_FLAGS.CONDENSED_FILTER_BAR]) {- return (- <SuppressTaxonomicMenuToggle>- <CondensedWebAnalyticsFilterBar tabs={tabs} />- </SuppressTaxonomicMenuToggle>- )+ return <CondensedWebAnalyticsFilterBar tabs={tabs} />}return (- <SuppressTaxonomicMenuToggle>+ <><IncompatibleFiltersWarning /><div data-attr="web-analytics-filters">@@ -155,7 +150,7 @@ export const WebAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Elemen}/></div>- </SuppressTaxonomicMenuToggle>+ </>)}diff --git a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.test.ts b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.test.tsindex fce2f1291bd3..a2803df7340b 100644--- a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.test.ts+++ b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.test.ts@@ -7,7 +7,7 @@ import { PropertyFilterType, PropertyOperator } from '~/types'import { addLogsValueFilter } from './LogsFilterBar'// The Logs group's getValue returns option.key, so `value` is 'message' while the searched-for text-// lives on item.value. See buildTaxonomicGroups' localItemsSearch for the Logs group.+// lives on item.value. See the Logs group's localItemsSearch in taxonomicFilterLogic.tsx.const LOGS_GROUP = { name: 'Logs', type: TaxonomicFilterGroupType.Logs } as TaxonomicFilterGroupconst messageSearchItem = (query: string): Record<string, any> => ({key: 'message',