Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(insights): scaffold headless TaxonomicFilter behind feature flag (#56666)

Adam Leith60c9e49519be
diff --git a/common/tailwind/tailwind.css b/common/tailwind/tailwind.css
index 53d0187ba0d5..ffa2106bf5ca 100644
--- a/common/tailwind/tailwind.css
+++ b/common/tailwind/tailwind.css
@@ -3,6 +3,18 @@
/* if this shows a warning, change the type of file in vscode to 'tailwind CSS' */
@config "./tailwind.config.js";
+/*
+ * Scan @posthog/quill source so utilities used in primitive/component
+ * authoring (including arbitrary values like `w-[601px]`) get emitted
+ * into this precompiled bundle. The config's `content` array already
+ * lists quill's compiled `dist/**` output; these sources cover classes
+ * that live in JSX/TSX before bundling strips them.
+ */
+@source "../../packages/quill/packages/primitives/src/**/*.{ts,tsx}";
+@source "../../packages/quill/packages/components/src/**/*.{ts,tsx}";
+@source "../../packages/quill/packages/blocks/src/**/*.{ts,tsx}";
+@source "../../packages/quill/packages/quill/src/**/*.{ts,tsx}";
+
@theme {
--text-xxs: 0.625rem;
--text-xxs--line-height: 0.75rem;
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 14da4a51a286..798548dbecfa 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1744,6 +1744,46 @@ snapshots:
hash: v1.k794b7964.e503fd34c51bed2938ea70593de2a34e2bb44585a94779268dbe9caa6a430c38.td6RRIB5rlR-53hCaS6Mlj7-wA7vEPm6EOydbtul8xE
filters-taxonomic-filter--three-groups-default-layout--light:
hash: v1.k794b7964.7d03de4d736f21437d1009fc19719734175f0c0822cd2ccdbc380ffa8f5e627c.lGDn7Z4UhsMOqLuuLQ9_TO9FuIbd45s3RKUs7A69z7s
+ filters-taxonomic-filter-headless--events-and-actions--dark:
+ hash: v1.k794b7964.213467e7f830b0c9023dbdac9c1a3015e184e7085d7037edce62a29180badfa1.O54qNf00yRPwFinPNCaNIrIBpnE8MQwcaKoMxWkyB2o
+ filters-taxonomic-filter-headless--events-and-actions--light:
+ hash: v1.k794b7964.df52b9239063606edb4522016d7626ab4d67961f1cf14287b697e467969fe932.xr044YgPtb3G8tGrDNFsjWohsN7xaGdll9bENI4jBTg
+ filters-taxonomic-filter-headless--properties--dark:
+ hash: v1.k794b7964.d3d71ef038d250b734f23f1b0d99b9450ecd75dc5d0ac5cbc232332bd020a9c7.QHFTGF0-fDG4Vc_NRI041gOI9GFehTJ1cRfgO_q51RM
+ filters-taxonomic-filter-headless--properties--light:
+ hash: v1.k794b7964.589d2f8ed0cf686abd23d27b87ffdb992e7e7cf0ee5cc2735a594fa890f2a884.j7fICS44ODNnJK0T_k2qD7wwlodvUdms6mCi9nTmoYM
+ filters-taxonomic-filter-headless--suggested-filters-with-recents--dark:
+ hash: v1.k794b7964.d8442f9a40a14588155ec4761cb04962a29578a3be99e07d32c6f6be594e1d2b.mLywCXOggV6IQvCI9OEpR2HoLOfginGqMXU4CUeeiek
+ filters-taxonomic-filter-headless--suggested-filters-with-recents--light:
+ hash: v1.k794b7964.698cb62280c95e89006f27deff5b9f0815f5d1d7708aad0656804c9abbafeaff.4_y9imo29homBpNLeJLJRjFQKXa2KDQhGgYDT86MaZg
+ filters-taxonomic-filter-menu-rebuild--data-warehouse-config--dark:
+ hash: v1.k794b7964.08cb28ef771b07306b60e9b1921ae0e5b31ed750737708ba70094bbf58b781ea.kpx11ijYcolN6k7wlqbIeu2-g2fk7Wwb2h-vm4ipteY
+ filters-taxonomic-filter-menu-rebuild--data-warehouse-config--light:
+ hash: v1.k794b7964.6867eac73493be009f6e5c587313077edf9673190cc3236cf5d3f4ee5455d14a.YGBBjhWUR6xO7ZhT_-tRjvCh_RJHnhuQfES_44jmL3Y
+ filters-taxonomic-filter-menu-rebuild--events-and-actions--dark:
+ hash: v1.k794b7964.28409752a51540006c6e81a3310dd3d66e34c938d1953ce75df53c6badd0beed.qCGpVbB_xHTb6c2fI8ryY6w6WspAfdah8dgFjTrrwNQ
+ filters-taxonomic-filter-menu-rebuild--events-and-actions--light:
+ hash: v1.k794b7964.2411e2fe3f00926b85a964baf4f376718e399347d8dd89ba1b3445c2ab812397.ywspZ2T5FptWYfqMVyFa4uKHexbpsqsC50FG5J6J3mw
+ filters-taxonomic-filter-menu-rebuild--hog-ql-only--dark:
+ hash: v1.k794b7964.c2d1d6891ede150f715882f3651e902ec7f281587a7d1db7ae847677f5853847.MuLrubRLum8PppPaVKUdXm6om-aSI5SrSRJ3KoAaJbk
+ filters-taxonomic-filter-menu-rebuild--hog-ql-only--light:
+ hash: v1.k794b7964.4e2576ce6ed99a9832eca7d33a6651a60d7ecc73b55ec5cbc11f595decee3e45.HA3XBd4T9HAeKrkofyAefc1s0LHsMNWhm5ss6bIcE5M
+ filters-taxonomic-filter-menu-rebuild--pre-selected-event--dark:
+ hash: v1.k794b7964.f961af82be7ba0b1455a79c3c558b009b446efba53b3b263e5d126658eb70696.5XWyOffo9vLB3-BSZuwwteh0wM5xR8xdOn1ViEkRPvY
+ filters-taxonomic-filter-menu-rebuild--pre-selected-event--light:
+ hash: v1.k794b7964.1468663455686c23475aa49f217e582928e9658d3cab8bdc55dd1ecba81381da.oIajIOGbbXzDcyY9ZWL0FC8eDHDwNK0IUPwvdMyHAA8
+ filters-taxonomic-filter-menu-rebuild--pre-selected-hog-ql--dark:
+ hash: v1.k794b7964.3c09a271ece484b640afb886ad09f9bc19f7963511e7d460816b1fa333ef2c80.r7TcPInlz90xpIUZ0GNu6e9Xwi9VN4HVWRTClneYsao
+ filters-taxonomic-filter-menu-rebuild--pre-selected-hog-ql--light:
+ hash: v1.k794b7964.d40362e52505856df808c152743b5a6ab68b9bb03937ed470a8f57f2d0dfdd27.MG2EVba7FTKqCi7mdiSonHbYeSYNkm_gnH6KGEqyEjk
+ filters-taxonomic-filter-menu-rebuild--properties--dark:
+ hash: v1.k794b7964.f33159fe00d676dc20c66b5180128b23bec90d71545df7d1799f58f9b3c02696.BylIrFIG049z_ZCtsOAAkLQCFyFU76mR4LMNvkoJ2Vw
+ filters-taxonomic-filter-menu-rebuild--properties--light:
+ hash: v1.k794b7964.40d47b36ffdeb0e8fafd70791c6383e93799b7941d169cf4cb6e4831b87b5bab.iIb1YjbnrkHpyfYC7Eqcth4cDTqyQABDcTzT8buA51Y
+ filters-taxonomic-filter-menu-rebuild--series-plus-data-warehouse--dark:
+ hash: v1.k794b7964.4f00350e27b99d13cbd4fec9c8dc0042b0d71e0395ae5b517be2468a40a80b8c.jF3AISTnOSp_iLSHftAAdMLaGYaUsZXASjz8e1Fja_o
+ filters-taxonomic-filter-menu-rebuild--series-plus-data-warehouse--light:
+ hash: v1.k794b7964.66eb7e64c0e61e70057ab9b39d5ce92e4c52e4098a985cc4400829b7ccc4e751.WV58ZkBoOn4X5pBDJxcBHdES99Ur-peElfudd9qvDIc
filters-taxonomicpopover--multiple-categories--dark:
hash: v1.k794b7964.6378ff79fb307a6d1fd9ce1d8661cec0a226ec3930ff40587a52ffbacffbf152.LzZ6hnqtCW00R9vHVaf5BBtpA7wqbfil8yEZ1pdyogo
filters-taxonomicpopover--multiple-categories--light:
@@ -5307,9 +5347,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-integrations--light:
hash: v1.k794b7964.13fb903b5f9b89a223c5cc2a96deaa206a3ae5a843897899b6961b7aa3209173.VgGmucGEeJ46Ab9gq1JLFeflFK-PHTcDcEVUbkuNnaE
scenes-app-settings-environment--settings-environment-marketing-analytics--dark:
- hash: v1.k794b7964.fc84dfb6779b169c70e59dafd9dca8f7c0745a0223b03b92121a7fd562c4ab82.U34nm0qCyAr0jD_dGJwcPXppi4wUq4_R8LeFmBQKi9g
+ hash: v1.k794b7964.6e532a111a9e6b5ea2f93cc6379ab36c43348080ee083bc1de548082cfc7a666.gyd_ZFvcWga2u2QLu9WQWVCU7EJaDeVmXjJ-zEo67RE
scenes-app-settings-environment--settings-environment-marketing-analytics--light:
- hash: v1.k794b7964.c6afbfa62f0d3f80052edb6c702f950246788cc23ae160c7f9a5cf44acd7dca8.DtJU0g9pm1z8S91m4UXAS_iZaqjJtfnO-kYuehUAUr0
+ hash: v1.k794b7964.6de78d023201259e7b914085b435fd1bb20d44227bd12b338f5890a2dd30a4a4.TboIVKNweJiId3voUf-NUUGkjFlk8UVLDBaWJqmPM0s
scenes-app-settings-environment--settings-environment-max--dark:
hash: v1.k794b7964.1a0507dd836f11eb876052993223d3efbe8a764e9dcc037b6ae748fef8b7e439.1QYb_DtwfeC8t_DOZ-0gsBTbNCmaPTz5EqRvCiyBIQk
scenes-app-settings-environment--settings-environment-max--light:
diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx
index e3d6a66407b5..b023e4e8ffee 100644
--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx
@@ -22,11 +22,20 @@ import { urls } from 'scenes/urls'
import { CategoryDropdown } from './CategoryDropdown'
import { InfiniteSelectResults } from './InfiniteSelectResults'
+import { TaxonomicFilterAdapter } from './TaxonomicFilterAdapter'
import { defaultDataWarehousePopoverFields, taxonomicFilterLogic } from './taxonomicFilterLogic'
let uniqueMemoizedIndex = 0
-export function TaxonomicFilter({
+export function TaxonomicFilter(props: TaxonomicFilterProps): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ if (featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_HEADLESS]) {
+ return <TaxonomicFilterAdapter {...props} />
+ }
+ return <TaxonomicFilterLegacy {...props} />
+}
+
+function TaxonomicFilterLegacy({
taxonomicFilterLogicKey: taxonomicFilterLogicKeyInput,
groupType,
value,
diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilterAdapter.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilterAdapter.tsx
new file mode 100644
index 000000000000..12b8b124be56
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilterAdapter.tsx
@@ -0,0 +1,118 @@
+/**
+ * Bridges the legacy `TaxonomicFilterProps` API to the new headless component
+ * tree. Used by the entry `<TaxonomicFilter>` component when the
+ * `TAXONOMIC_FILTER_HEADLESS` feature flag is on, so existing call-sites get
+ * the new implementation without touching their props.
+ *
+ * Translation table is intentionally narrow for the v1 flip:
+ * - search / tabs / list / select / keyboard nav → fully wired
+ * - definition popover → not yet (legacy renderer
+ * not supported in v1; the
+ * `<Panel>` row uses the
+ * Quill `<ItemMenuItem>`)
+ * - DataWarehouse pinned-row detail-pane → deferred (see PRD §3.3)
+ * - keyword shortcut promotion in SuggestedFilters → deferred (orchestrator
+ * doesn't yet aggregate
+ * top matches across tabs)
+ *
+ * Anything in those buckets is documented inline + in the rewrite PRD. When
+ * the flag is off, the legacy kea implementation runs exactly as before.
+ */
+import { KeyboardEvent, useCallback } from 'react'
+
+import { TaxonomicFilterHeadless } from './headless'
+import { TaxonomicFilterProps } from './types'
+
+export function TaxonomicFilterAdapter(props: TaxonomicFilterProps): JSX.Element {
+ const {
+ taxonomicGroupTypes,
+ groupType,
+ value,
+ onChange,
+ onEnter,
+ onClose,
+ optionsFromProp,
+ metadataSource,
+ eventNames,
+ schemaColumns,
+ schemaColumnsLoading,
+ excludedProperties,
+ selectedProperties,
+ propertyAllowList,
+ showNumericalPropsOnly,
+ hideBehavioralCohorts,
+ maxContextOptions,
+ allowNonCapturedEvents,
+ hogQLGlobals,
+ hogQLExpressionShowBreakdownLabelHint,
+ minSearchQueryLength,
+ suggestedFiltersLabel,
+ hideSearchInput,
+ searchQuery,
+ initialSearchQuery,
+ enableKeywordShortcuts,
+ selectFirstItem = true,
+ width,
+ height,
+ } = props
+
+ // Bridge legacy `onClose` (fires on Escape) by wrapping the orchestrator's
+ // keyboard handler at the adapter level — the headless API doesn't ship a
+ // dedicated onClose option to keep the surface small.
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLDivElement>): void => {
+ if (e.key === 'Escape') {
+ onClose?.()
+ }
+ },
+ [onClose]
+ )
+
+ const style = {
+ ...(width ? { width: typeof width === 'number' ? `${width}px` : width } : {}),
+ ...(height ? { height: typeof height === 'number' ? `${height}px` : height } : {}),
+ }
+
+ return (
+ <div
+ className="taxonomic-filter taxonomic-filter--headless"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={style}
+ onKeyDown={handleKeyDown}
+ >
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={taxonomicGroupTypes}
+ groupType={groupType}
+ value={value}
+ onChange={onChange}
+ onEnter={onEnter}
+ searchQuery={searchQuery}
+ initialSearchQuery={initialSearchQuery}
+ eventNames={eventNames}
+ schemaColumns={schemaColumns}
+ schemaColumnsLoading={schemaColumnsLoading}
+ metadataSource={metadataSource}
+ suggestedFiltersLabel={suggestedFiltersLabel}
+ excludedProperties={excludedProperties}
+ selectedProperties={selectedProperties}
+ propertyAllowList={propertyAllowList}
+ maxContextOptions={maxContextOptions}
+ hideBehavioralCohorts={hideBehavioralCohorts}
+ hogQLGlobals={hogQLGlobals}
+ hogQLExpressionShowBreakdownLabelHint={hogQLExpressionShowBreakdownLabelHint}
+ optionsFromProp={optionsFromProp}
+ showNumericalPropsOnly={showNumericalPropsOnly}
+ minSearchQueryLength={minSearchQueryLength}
+ allowNonCapturedEvents={allowNonCapturedEvents}
+ enableKeywordShortcuts={enableKeywordShortcuts}
+ selectFirstItem={selectFirstItem}
+ >
+ {!hideSearchInput && <TaxonomicFilterHeadless.Input />}
+ {taxonomicGroupTypes.length > 1 && (
+ <TaxonomicFilterHeadless.Categories className="flex flex-row flex-wrap gap-1 my-2" />
+ )}
+ <TaxonomicFilterHeadless.Panel className="flex-1 min-h-0 overflow-auto" />
+ </TaxonomicFilterHeadless.Root>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/dataWarehouseItemUtils.ts b/frontend/src/lib/components/TaxonomicFilter/dataWarehouseItemUtils.ts
index 7501813076e6..91bede70f082 100644
--- a/frontend/src/lib/components/TaxonomicFilter/dataWarehouseItemUtils.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/dataWarehouseItemUtils.ts
@@ -21,6 +21,13 @@ function findFieldByNameCandidates(
warehouseItem: DataWarehouseTableForInsight,
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
+ // selection only carries `name` / `id`. Bail out cleanly instead of
+ // throwing on `Object.values(undefined)`.
+ if (!warehouseItem.fields) {
+ return undefined
+ }
const fields = Object.values(warehouseItem.fields)
for (const candidate of candidates) {
@@ -38,6 +45,9 @@ function findFieldByNameCandidates(
function findDateOrDatetimeField(
warehouseItem: DataWarehouseTableForInsight
): DataWarehouseTableForInsight['fields'][string] | undefined {
+ if (!warehouseItem.fields) {
+ return undefined
+ }
return Object.values(warehouseItem.fields).find((field) => field.type === 'datetime' || field.type === 'date')
}
@@ -49,6 +59,9 @@ function findJoinedFieldExpression(
const normalizedTableName = normalizeFieldName(tableName)
const normalizedFieldName = normalizeFieldName(fieldName)
+ if (!warehouseItem.fields) {
+ return undefined
+ }
const exactJoinField = Object.values(warehouseItem.fields).find(
(field) =>
normalizeFieldName(field.name) === normalizedTableName &&
diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx
new file mode 100644
index 000000000000..97005f55b810
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/AutocompleteInput.tsx
@@ -0,0 +1,2116 @@
+/**
+ * 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 { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
+import { getCoreFilterDefinition } from '~/taxonomy/helpers'
+import { PropertyDefinitionType } from '~/types'
+
+import { useGroupList } from '../hooks/useGroupList'
+import { hasPinnedContext, taxonomicFilterPinnedPropertiesLogic } from '../taxonomicFilterPinnedPropertiesLogic'
+import {
+ TaxonomicDefinitionTypes,
+ TaxonomicFilterGroup,
+ TaxonomicFilterGroupType,
+ TaxonomicFilterValue,
+} 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 | null>
+ /** 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>(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]
+ )
+
+ 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
+ }, [targetGroups, itemsByType])
+
+ 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'),
+ }
+ const groupCats = ctx.visibleGroups.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="ghost"
+ 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 } = 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 } }
+ >
+ )
+ .map((item) => buildEntry(item, item._pinnedContext?.sourceGroupType))
+ .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])
+}
+
+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.tsx
new file mode 100644
index 000000000000..b995ad3aef03
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/Categories.tsx
@@ -0,0 +1,79 @@
+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.tsx
new file mode 100644
index 000000000000..8aa082f4d078
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/Input.tsx
@@ -0,0 +1,55 @@
+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.tsx
new file mode 100644
index 000000000000..899aedfc2089
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/Panel.tsx
@@ -0,0 +1,148 @@
+import { ReactNode, useEffect, useRef } from 'react'
+
+import { Empty, EmptyHeader, EmptyTitle, ItemMenuItem, Spinner } from '@posthog/quill'
+
+import { useGroupList, UseGroupListResult } from '../hooks/useGroupList'
+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 } = useTaxonomicFilterContext()
+ const list: UseGroupListResult = useGroupList(getGroupListInput(group))
+
+ // 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.showEmptyState) {
+ return (
+ <div className={className}>
+ {emptyState !== undefined ? (
+ emptyState
+ ) : (
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>
+ {list.needsMoreSearchCharacters ? 'Type more to search' : '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>
+ }
+ return (
+ <ItemMenuItem
+ key={index}
+ size="sm"
+ role="option"
+ aria-selected={isActive}
+ data-attr={`taxonomic-row-${group.type}-${index}`}
+ onClick={onSelect}
+ onMouseEnter={onMouseEnter}
+ >
+ {group.getName?.(item) ?? ('name' in item ? (item as { name?: string }).name : '')}
+ </ItemMenuItem>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/Root.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/Root.tsx
new file mode 100644
index 000000000000..629427d8bf0f
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/Root.tsx
@@ -0,0 +1,27 @@
+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/TaxonomicFilterHeadless.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/TaxonomicFilterHeadless.stories.tsx
new file mode 100644
index 000000000000..b19c558706b1
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/TaxonomicFilterHeadless.stories.tsx
@@ -0,0 +1,114 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useMountedLogic } from 'kea'
+import { useState } from 'react'
+
+import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__mocks__/taxonomicFilterMocksDecorator'
+
+import { actionsModel } from '~/models/actionsModel'
+
+import { TaxonomicFilterGroup, TaxonomicFilterGroupType, TaxonomicFilterValue } from '../types'
+import { TaxonomicFilterHeadless } from './index'
+
+const meta: Meta = {
+ title: 'Filters/Taxonomic Filter (Headless)',
+ decorators: [taxonomicFilterMocksDecorator],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Headless TaxonomicFilter built on Quill primitives. The compound `<Root>/<Input>/<Categories>/<Panel>` API is opt-in via the `TAXONOMIC_FILTER_HEADLESS` feature flag and replaces the kea-based `<TaxonomicFilter>` once parity is verified.',
+ },
+ },
+ },
+ tags: ['autodocs'],
+}
+
+export default meta
+
+type Story = StoryObj
+
+interface ContainerArgs {
+ taxonomicGroupTypes: TaxonomicFilterGroupType[]
+ initialSearchQuery?: string
+ suggestedFiltersLabel?: string
+}
+
+function Container({ taxonomicGroupTypes, initialSearchQuery, suggestedFiltersLabel }: ContainerArgs): JSX.Element {
+ useMountedLogic(actionsModel)
+ const [lastPick, setLastPick] = useState<{
+ group: string
+ value: TaxonomicFilterValue | null
+ name?: string
+ } | null>(null)
+
+ return (
+ <div className="flex flex-col gap-3 max-w-xl border rounded p-3 bg-surface-primary">
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={taxonomicGroupTypes}
+ initialSearchQuery={initialSearchQuery}
+ suggestedFiltersLabel={suggestedFiltersLabel}
+ onChange={(group: TaxonomicFilterGroup, value, item: any) => {
+ setLastPick({ group: group.type, value, name: item?.name })
+ }}
+ >
+ <TaxonomicFilterHeadless.Input />
+ <TaxonomicFilterHeadless.Categories className="flex flex-row flex-wrap gap-1" />
+ <TaxonomicFilterHeadless.Panel className="max-h-80 overflow-auto" />
+ </TaxonomicFilterHeadless.Root>
+ {lastPick && (
+ <div className="text-xs text-secondary">
+ Selected: <code>{lastPick.group}</code> / <code>{String(lastPick.value)}</code>
+ {lastPick.name ? ` (${lastPick.name})` : ''}
+ </div>
+ )}
+ </div>
+ )
+}
+
+export const EventsAndActions: Story = {
+ render: () => (
+ <Container taxonomicGroupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]} />
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: 'Two tabs: Events + Actions. Tab strip uses Quill `<Button>`, list uses `<ItemMenuItem>`.',
+ },
+ },
+ },
+}
+
+export const Properties: Story = {
+ render: () => (
+ <Container
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties, TaxonomicFilterGroupType.PersonProperties]}
+ />
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: 'Property picker — Event + Person properties. Uses the same headless API as the Events story.',
+ },
+ },
+ },
+}
+
+export const SuggestedFiltersWithRecents: Story = {
+ render: () => (
+ <Container
+ taxonomicGroupTypes={[
+ TaxonomicFilterGroupType.SuggestedFilters,
+ TaxonomicFilterGroupType.Events,
+ TaxonomicFilterGroupType.EventProperties,
+ ]}
+ suggestedFiltersLabel="Top picks"
+ />
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: 'Demonstrates the auto-injected SuggestedFilters tab + a custom label.',
+ },
+ },
+ },
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/UX_SPEC.md b/frontend/src/lib/components/TaxonomicFilter/headless/UX_SPEC.md
new file mode 100644
index 000000000000..94182804d7e7
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/UX_SPEC.md
@@ -0,0 +1,213 @@
+# 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.ts
new file mode 100644
index 000000000000..f7bf01aa8428
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/context.ts
@@ -0,0 +1,16 @@
+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.tsx
new file mode 100644
index 000000000000..5c8a85322c2d
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/headless.test.tsx
@@ -0,0 +1,161 @@
+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 { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'
+import { TaxonomicFilterGroupType } from '../types'
+import { TaxonomicFilterHeadless } from './index'
+
+jest.mock('~/queries/query', () => ({
+ performQuery: jest.fn(),
+}))
+
+jest.mock('lib/api', () => ({
+ __esModule: true,
+ default: {
+ 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()
+ ;(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('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())
+ })
+})
diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/index.ts b/frontend/src/lib/components/TaxonomicFilter/headless/index.ts
new file mode 100644
index 000000000000..a7839d4620f6
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/headless/index.ts
@@ -0,0 +1,66 @@
+/**
+ * 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.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts
new file mode 100644
index 000000000000..546ea2bd553a
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/fetchTaxonomicListPage.ts
@@ -0,0 +1,86 @@
+/**
+ * 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 } from 'lib/components/TaxonomicFilter/types'
+
+export interface FetchTaxonomicPageParams {
+ group: TaxonomicFilterGroup
+ searchQuery: string
+ offset: number
+ limit: number
+ isExpanded: boolean
+ showNumericalPropsOnly?: boolean
+ hideBehavioralCohorts?: boolean
+ signal?: AbortSignal
+}
+
+const EMPTY_LIST: ListStorage = { results: [], searchQuery: '', count: 0 }
+
+export async function fetchTaxonomicListPage({
+ group,
+ searchQuery,
+ offset,
+ limit,
+ isExpanded,
+ showNumericalPropsOnly,
+ hideBehavioralCohorts,
+ 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) {
+ 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 useScoped = group.scopedEndpoint && !isExpanded
+ const primaryUrl = useScoped ? group.scopedEndpoint! : remoteEndpoint
+
+ const [primary, expandedCount] = await Promise.all([
+ api.get(combineUrl(primaryUrl, baseParams).url, { signal }),
+ useScoped
+ ? api.get(combineUrl(remoteEndpoint, { ...baseParams, limit: 1, offset: 0 }).url, { signal })
+ : Promise.resolve(null),
+ ])
+
+ const results = primary?.results ?? primary ?? []
+ const count = primary?.count ?? (Array.isArray(primary) ? primary.length : results.length)
+
+ return {
+ results,
+ searchQuery,
+ count,
+ expandedCount: expandedCount?.count,
+ }
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx
new file mode 100644
index 000000000000..d9b3454e4aca
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.test.tsx
@@ -0,0 +1,279 @@
+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('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('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('exposes expandable state when scoped + expandedCount > count', async () => {
+ apiGet
+ // primary scoped fetch
+ .mockResolvedValueOnce({ results: [{ name: 's' }], count: 1 })
+ // extra full count fetch
+ .mockResolvedValueOnce({ 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))
+ expect(result.current.isExpandable).toBe(true)
+ expect(result.current.rowCount).toBe(2) // results + expand button
+ })
+
+ 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('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))
+ })
+
+ it('allowNonCapturedEvents surfaces the option for empty Events search', async () => {
+ apiGet.mockResolvedValueOnce({ results: [], count: 0 })
+ const group = makeGroup({
+ type: TaxonomicFilterGroupType.Events,
+ endpoint: 'api/projects/1/event_definitions',
+ })
+ const { result } = renderHook(() =>
+ useGroupList({ group, searchQuery: 'unseen', allowNonCapturedEvents: true })
+ )
+ await waitFor(() => expect(result.current.isLoading).toBe(false))
+ expect(result.current.showNonCapturedEventOption).toBe(true)
+ })
+ })
+})
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
new file mode 100644
index 000000000000..ffcff812b18c
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useGroupList.ts
@@ -0,0 +1,336 @@
+/**
+ * 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
+ * - performance instrumentation (`captureTimeToSeeData`)
+ * - the GroupNamesPrefix clickhouse fast path (still goes through generic
+ * endpoint fetcher; behaviour identical, just slower for large groups)
+ */
+import { useMemo, useState } from 'react'
+
+import {
+ isQuickFilterItem,
+ ListStorage,
+ QuickFilterItem,
+ SimpleOption,
+ TaxonomicDefinitionTypes,
+ TaxonomicFilterGroup,
+ TaxonomicFilterGroupType,
+} from 'lib/components/TaxonomicFilter/types'
+import { createFuse } from 'lib/utils/fuseSearch'
+
+import { getCoreFilterDefinition } from '~/taxonomy/helpers'
+
+import { fetchTaxonomicListPage } from './fetchTaxonomicListPage'
+import { 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
+ /** 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
+}
+
+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
+ showEmptyState: boolean
+ showLoadingState: boolean
+ showNonCapturedEventOption: boolean
+
+ isExpandable: boolean
+ isExpanded: boolean
+ expand: () => void
+
+ refetch: () => void
+}
+
+const DEFAULT_LIMIT = 100
+
+export function useGroupList(input: UseGroupListInput): UseGroupListResult {
+ const {
+ group,
+ searchQuery,
+ localOverride,
+ optionsFromProp,
+ showNumericalPropsOnly = false,
+ hideBehavioralCohorts = false,
+ minSearchQueryLength: minSearchOverride,
+ limit = DEFAULT_LIMIT,
+ allowNonCapturedEvents = false,
+ enableKeywordShortcuts = false,
+ autoSelectItem = true,
+ selectFirstItem = true,
+ } = 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
+ return { name, posthogName, recentLabel: undefined, 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
+
+ const remoteKey = useMemo(
+ () => [
+ 'taxonomic-list',
+ group.type,
+ group.endpoint,
+ group.scopedEndpoint ?? null,
+ isExpanded,
+ searchQuery,
+ limit,
+ showNumericalPropsOnly,
+ hideBehavioralCohorts,
+ ],
+ [
+ group.type,
+ group.endpoint,
+ group.scopedEndpoint,
+ isExpanded,
+ searchQuery,
+ limit,
+ showNumericalPropsOnly,
+ hideBehavioralCohorts,
+ ]
+ )
+
+ const remote = useTaxonomicResource<ListStorage>(
+ remoteKey,
+ ({ signal }) =>
+ fetchTaxonomicListPage({
+ group,
+ searchQuery,
+ offset: 0,
+ limit,
+ isExpanded,
+ showNumericalPropsOnly,
+ hideBehavioralCohorts,
+ signal,
+ }),
+ { enabled: remoteEnabled, staleTime: 60_000, keepPreviousData: true }
+ )
+
+ const remoteItems: ListStorage = remote.data ?? EMPTY_LIST_STORAGE
+
+ // ---- 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)
+ }
+ return merged
+ }, [keywordShortcuts, localItems, remoteItems])
+
+ const isExpandable = !!(
+ group.endpoint &&
+ group.scopedEndpoint &&
+ remoteItems.expandedCount &&
+ remoteItems.expandedCount > 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 ---------------------------------------------
+ const isLoading = remote.isLoading
+ const isFetching = remote.isFetching
+
+ const showNonCapturedEventOption = useMemo(() => {
+ if (!allowNonCapturedEvents) {
+ return false
+ }
+ if (group.type !== TaxonomicFilterGroupType.Events && group.type !== TaxonomicFilterGroupType.CustomEvents) {
+ return false
+ }
+ if (!trimmedSearch || isLoading) {
+ return false
+ }
+ const realResults = items.filter((item) => !isQuickFilterItem(item))
+ return realResults.length === 0
+ }, [allowNonCapturedEvents, group.type, trimmedSearch, isLoading, items])
+
+ // 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 =
+ (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,
+ showEmptyState,
+ showLoadingState,
+ showNonCapturedEventOption,
+ isExpandable,
+ isExpanded,
+ expand,
+ refetch: () => {
+ remote.refetch()
+ },
+ }
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx
new file mode 100644
index 000000000000..4f1d71776f62
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx
@@ -0,0 +1,325 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { Provider } from 'kea'
+import { ReactNode } from 'react'
+
+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 { TaxonomicFilterGroupType } from '../types'
+import { useTaxonomicFilter } from './useTaxonomicFilter'
+import { __clearTaxonomicResourceCache } from './useTaxonomicResource'
+
+jest.mock('~/queries/query', () => ({
+ performQuery: jest.fn(),
+}))
+
+jest.mock('lib/api', () => ({
+ __esModule: true,
+ default: { get: jest.fn().mockResolvedValue({ results: [], count: 0 }) },
+}))
+
+const wrapper = ({ children }: { children: ReactNode }): JSX.Element => <Provider>{children}</Provider>
+
+describe('useTaxonomicFilter', () => {
+ beforeEach(() => {
+ __clearTaxonomicResourceCache()
+ ;(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('exposes groups in the consumer-requested order, with Recent + Pinned auto-injected', () => {
+ const { result } = renderHook(
+ () =>
+ useTaxonomicFilter({
+ taxonomicGroupTypes: [
+ TaxonomicFilterGroupType.Events,
+ TaxonomicFilterGroupType.Actions,
+ TaxonomicFilterGroupType.PersonProperties,
+ ],
+ }),
+ { wrapper }
+ )
+ // Recent + Pinned auto-inject at the start (no other meta groups
+ // requested, so they go in at index 0).
+ expect(result.current.groupTypes).toEqual([
+ TaxonomicFilterGroupType.RecentFilters,
+ TaxonomicFilterGroupType.PinnedFilters,
+ TaxonomicFilterGroupType.Events,
+ TaxonomicFilterGroupType.Actions,
+ TaxonomicFilterGroupType.PersonProperties,
+ ])
+ expect(result.current.groups.map((g) => g.type)).toEqual(result.current.groupTypes)
+ })
+
+ 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({
+ taxonomicGroupTypes: [TaxonomicFilterGroupType.SuggestedFilters, TaxonomicFilterGroupType.Events],
+ }),
+ { 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('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,
+ showEmptyState: 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 groups (incl. auto-injected Recent + Pinned)', () => {
+ 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)
+ })
+})
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
new file mode 100644
index 000000000000..131931ca549f
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
@@ -0,0 +1,530 @@
+/**
+ * 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+
+import {
+ hasRecentContext,
+ recentTaxonomicFiltersLogic,
+ stripRecentContext,
+} from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'
+import {
+ AllowedProperties,
+ ExcludedProperties,
+ SelectedProperties,
+ SimpleOption,
+ 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 { 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
+ selectedProperties?: SelectedProperties
+ propertyAllowList?: AllowedProperties
+ maxContextOptions?: MaxContextTaxonomicFilterOption[]
+ hideBehavioralCohorts?: 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
+}
+
+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
+
+ // 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 `RecentFilters` and `PinnedFilters` after the meta
+ * group block (Suggested → Recent → Pinned)
+ * 4. 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))
+
+ // 2. Auto-inject Recent / Pinned (Suggested stays opt-in)
+ for (const metaType of AUTO_INJECT_META_GROUPS) {
+ if (available.has(metaType) && !filtered.includes(metaType)) {
+ filtered.splice(indexAfterLastMetaGroup(filtered), 0, metaType)
+ }
+ }
+
+ // 3. Promote shortcut groups to right after the meta block
+ 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,
+ selectedProperties,
+ propertyAllowList,
+ maxContextOptions,
+ hideBehavioralCohorts,
+ endpointFilters,
+ hogQLGlobals,
+ hogQLExpressionShowBreakdownLabelHint,
+ optionsFromProp,
+ showNumericalPropsOnly,
+ minSearchQueryLength,
+ allowNonCapturedEvents,
+ enableKeywordShortcuts,
+ selectFirstItem,
+ autoSelectItem,
+ } = opts
+
+ const ctx = useTaxonomicGroupsContext({
+ eventNames,
+ schemaColumns,
+ schemaColumnsLoading,
+ metadataSource,
+ suggestedFiltersLabel,
+ excludedProperties,
+ propertyAllowList,
+ selectedProperties,
+ maxContextOptions,
+ hideBehavioralCohorts,
+ endpointFilters,
+ hogQLGlobals,
+ hogQLExpressionShowBreakdownLabelHint,
+ })
+
+ const allGroups = useMemo(() => buildTaxonomicGroups(ctx), [ctx])
+ const allGroupTypes = useMemo(() => new Set(allGroups.map((g) => g.type)), [allGroups])
+ const getLocalOverride = useTaxonomicLocalOverrides()
+
+ const groupTypes = useMemo(
+ () => resolveTaxonomicGroupTypes(taxonomicGroupTypes, allGroupTypes, eventNames ?? []),
+ [taxonomicGroupTypes, allGroupTypes, eventNames]
+ )
+
+ 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]
+ )
+
+ // ---- 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])
+
+ const [activeGroupType, setActiveGroupTypeInternal] = useState<TaxonomicFilterGroupType>(defaultActiveGroup)
+
+ // If the resolved tab list shrinks beneath the active type, fall back.
+ useEffect(() => {
+ if (!groupTypes.includes(activeGroupType)) {
+ setActiveGroupTypeInternal(defaultActiveGroup)
+ }
+ }, [groupTypes, activeGroupType, defaultActiveGroup])
+
+ const setActiveGroupType = useCallback(
+ (t: TaxonomicFilterGroupType) => {
+ if (groupTypes.includes(t)) {
+ setActiveGroupTypeInternal(t)
+ }
+ },
+ [groupTypes]
+ )
+
+ const tabLeft = useCallback(() => {
+ const idx = groupTypes.indexOf(activeGroupType)
+ if (idx <= 0) {
+ return
+ }
+ for (let i = idx - 1; i >= 0; i--) {
+ setActiveGroupTypeInternal(groupTypes[i])
+ return
+ }
+ }, [groupTypes, activeGroupType])
+
+ const tabRight = useCallback(() => {
+ const idx = groupTypes.indexOf(activeGroupType)
+ if (idx === -1 || idx >= groupTypes.length - 1) {
+ return
+ }
+ setActiveGroupTypeInternal(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 are skipped (they're
+ // shortcuts, not filterable definitions); pinned/recent
+ // context wrappers get stripped before persisting.
+ if (valueIn != null && item && !isQuickFilterItem(item)) {
+ const sourceGroupType = hasRecentContext(item) ? item._recentContext.sourceGroupType : group.type
+ const stripped = hasRecentContext(item) ? stripRecentContext(item) : item
+ const cleanItem = {
+ name: stripped.name,
+ ...(stripped.id ? { id: stripped.id } : {}),
+ }
+ const sourceGroupName = hasRecentContext(item) ? item._recentContext.sourceGroupName : group.name
+ const propertyFilterFromRecent = hasRecentContext(item) ? item._recentContext.propertyFilter : undefined
+ // 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('')
+ },
+ [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),
+ }),
+ [
+ searchQuery,
+ optionsFromProp,
+ showNumericalPropsOnly,
+ hideBehavioralCohorts,
+ minSearchQueryLength,
+ allowNonCapturedEvents,
+ enableKeywordShortcuts,
+ selectFirstItem,
+ autoSelectItem,
+ getLocalOverride,
+ ]
+ )
+
+ // ---- 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,
+ 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.tsx
new file mode 100644
index 000000000000..8cdb60411997
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.test.tsx
@@ -0,0 +1,104 @@
+import { cleanup, renderHook } from '@testing-library/react'
+import { Provider } from 'kea'
+import { ReactNode } from 'react'
+
+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 { 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('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)
+ })
+})
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts
new file mode 100644
index 000000000000..06fd194f6bdc
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicGroupsContext.ts
@@ -0,0 +1,145 @@
+/**
+ * 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 { useValues } from 'kea'
+import { 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 { 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 { 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 {
+ eventNames?: string[]
+ schemaColumns?: DatabaseSchemaField[]
+ schemaColumnsLoading?: boolean
+ metadataSource?: AnyDataNode
+ suggestedFiltersLabel?: string
+ excludedProperties?: ExcludedProperties
+ propertyAllowList?: AllowedProperties
+ selectedProperties?: SelectedProperties
+ maxContextOptions?: MaxContextTaxonomicFilterOption[]
+ hideBehavioralCohorts?: 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 } = useValues(propertyDefinitionsModel)
+ const { featureFlags } = useValues(featureFlagLogic)
+
+ 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,
+ }
+ 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[]),
+ schemaColumns: input.schemaColumns ?? (EMPTY_ARRAY as unknown as DatabaseSchemaField[]),
+ schemaColumnsLoading: input.schemaColumnsLoading,
+ metadataSource: input.metadataSource ?? DEFAULT_METADATA_SOURCE,
+ suggestedFiltersLabel: input.suggestedFiltersLabel,
+ propertyFilters,
+ eventMetadataPropertyDefinitions,
+ maxContextOptions: input.maxContextOptions ?? (EMPTY_ARRAY as unknown as MaxContextTaxonomicFilterOption[]),
+ hideBehavioralCohorts: input.hideBehavioralCohorts ?? 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'],
+ }
+ }, [
+ currentTeam,
+ currentProjectId,
+ groupTypes,
+ aggregationLabel,
+ eventMetadataPropertyDefinitions,
+ featureFlags,
+ input.eventNames,
+ input.schemaColumns,
+ input.schemaColumnsLoading,
+ input.metadataSource,
+ input.suggestedFiltersLabel,
+ input.excludedProperties,
+ input.propertyAllowList,
+ input.maxContextOptions,
+ input.hideBehavioralCohorts,
+ 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.ts
new file mode 100644
index 000000000000..8b8c5cc84e49
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicLocalOverrides.ts
@@ -0,0 +1,68 @@
+/**
+ * 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 } from 'react'
+
+import { recentTaxonomicFiltersLogic } from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'
+import { taxonomicFilterPinnedPropertiesLogic } from 'lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic'
+import { TaxonomicDefinitionTypes, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { dataWarehouseSettingsSceneLogic } from 'scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic'
+import { experimentsLogic } from 'scenes/experiments/experimentsLogic'
+
+import { actionsModel } from '~/models/actionsModel'
+import { dashboardsModel } from '~/models/dashboardsModel'
+
+import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
+
+export type GetLocalOverride = (groupType: TaxonomicFilterGroupType) => TaxonomicDefinitionTypes[] | undefined
+
+export function useTaxonomicLocalOverrides(): GetLocalOverride {
+ 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)
+
+ return useCallback(
+ (groupType: TaxonomicFilterGroupType): TaxonomicDefinitionTypes[] | undefined => {
+ switch (groupType) {
+ case TaxonomicFilterGroupType.Actions:
+ return actionsSorted as unknown as TaxonomicDefinitionTypes[]
+ case TaxonomicFilterGroupType.RecentFilters:
+ return recentFilterItems
+ case TaxonomicFilterGroupType.PinnedFilters:
+ return pinnedFilterItems
+ 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,
+ recentFilterItems,
+ pinnedFilterItems,
+ 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.ts
new file mode 100644
index 000000000000..66bba59b0fa6
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.test.ts
@@ -0,0 +1,205 @@
+import { act, renderHook, waitFor } from '@testing-library/react'
+
+import {
+ __clearTaxonomicResourceCache,
+ invalidateTaxonomicResource,
+ 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', async () => {
+ const seenSignals: AbortSignal[] = []
+ const fn = jest.fn().mockImplementation(({ signal }: { signal: AbortSignal }) => {
+ seenSignals.push(signal)
+ return new Promise(() => {})
+ })
+ const { unmount } = renderHook(() => useTaxonomicResource(['abort'], fn))
+ expect(seenSignals).toHaveLength(1)
+ expect(seenSignals[0].aborted).toBe(false)
+ unmount()
+ expect(seenSignals[0].aborted).toBe(true)
+ })
+
+ 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('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.ts
new file mode 100644
index 000000000000..a93d6bfa666e
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicResource.ts
@@ -0,0 +1,255 @@
+/**
+ * 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 { useEffect, useRef, useSyncExternalStore } from 'react'
+
+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
+ }
+ 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.
+ useSyncExternalStore(
+ (notifyChange) => {
+ entry.subscribers.add(notifyChange)
+ return () => {
+ entry.subscribers.delete(notifyChange)
+ if (entry.subscribers.size === 0 && entry.abort) {
+ entry.abort.abort()
+ }
+ }
+ },
+ () => 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)
+ }
+}
+
+/** 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.ts
index e7f924dd0414..65381a644882 100644
--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts
@@ -28,6 +28,7 @@ import {
TaxonomicFilterGroup,
TaxonomicFilterGroupType,
} from 'lib/components/TaxonomicFilter/types'
+import { promoteMatchingProperties } from 'lib/components/TaxonomicFilter/utils/promoteProperties'
import { createFuse } from 'lib/utils/fuseSearch'
import { mapGroupQueryResponse } from 'lib/utils/groups'
@@ -52,53 +53,6 @@ function pinnedItemMatchesSearch(
return name.toLowerCase().includes(query) || (label?.toLowerCase().includes(query) ?? false)
}
-/** Search terms mapped to properties that should be promoted when that exact term is searched. */
-const PROMOTED_PROPERTIES_BY_SEARCH_TERM: Record<string, string[]> = {
- url: ['$current_url'],
- email: ['$email'],
-}
-
-/**
- * If the search query matches a promoted property's search terms, move that property
- * to the top of results so users find it quickly.
- */
-function promoteMatchingProperties<T extends TaxonomicDefinitionTypes | SkeletonItem>(
- results: T[],
- searchQuery: string
-): T[] {
- if (!searchQuery) {
- return results
- }
-
- const query = searchQuery.toLowerCase().trim()
- const promotedPropertyNames = PROMOTED_PROPERTIES_BY_SEARCH_TERM[query]
- if (!promotedPropertyNames?.length) {
- return results
- }
-
- const promotedPropertyNameSet = new Set(promotedPropertyNames)
- const promoted: T[] = []
- const rest: T[] = []
-
- for (const item of results as (T | undefined)[]) {
- if (!item) {
- continue
- }
- if (isSkeletonItem(item)) {
- rest.push(item)
- continue
- }
- const name = 'name' in item ? (item as { name?: string }).name : undefined
- if (name && promotedPropertyNameSet.has(name)) {
- promoted.push(item)
- } else {
- rest.push(item)
- }
- }
-
- return promoted.length > 0 ? [...promoted, ...rest] : results
-}
-
export interface RowInfo {
startIndex: number
stopIndex: number
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
new file mode 100644
index 000000000000..8c3b1e1e2818
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
@@ -0,0 +1,652 @@
+/**
+ * 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+
+import { IconCheck, IconChevronRight } from '@posthog/icons'
+import { Button, cn, InputGroup, InputGroupInput, MenuLabel, ScrollArea, Separator } from '@posthog/quill'
+
+import { createFuse } from 'lib/utils/fuseSearch'
+
+import { getCoreFilterDefinition } from '~/taxonomy/helpers'
+
+import { useTaxonomicFilterContext } from '../headless/context'
+import { useGroupList } from '../hooks/useGroupList'
+import { TaxonomicDefinitionTypes, TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'
+import { MenuFilterHeader } from './Header'
+import { PreviewPane } from './PreviewPane'
+import { CommitFn, DrillCategory, MenuFilterEntry } from './types'
+
+// `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'],
+ ignoreLocation: true,
+}
+
+/** Categories filtered out of the chip row when drillTo === 'all'. */
+const HIDDEN_FROM_CHIPS: ReadonlySet<TaxonomicFilterGroupType> = new Set([
+ // `SuggestedFilters` from taxonomicFilterLogic is a tiny set of
+ // primary-property promotions for the *currently-selected event* +
+ // autocapture text/selector. It's empty for almost every flow that
+ // doesn't have an event-in-context, and even when populated it
+ // duplicates what shows up under Event properties. Hide entirely;
+ // our own `Suggested` chip (Recent ∪ Pinned) covers what users
+ // actually want.
+ TaxonomicFilterGroupType.SuggestedFilters,
+ // RecentFilters / PinnedFilters surface via the dropdown menu
+ // (Recent / Pinned entries with chevrons), 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,
+])
+
+export interface MenuFilterComboboxProps {
+ drillTo: DrillCategory
+ /** Pre-resolved entries for `drillTo='recent' | 'pinned'`. Skips fetching. */
+ drillItems?: MenuFilterEntry[]
+ /** Pre-resolved entries for the `'suggested'` chip / drill — Recent ∪ Pinned across groups. Always passed; used whenever the active scope is `'suggested'` regardless of `drillTo`. */
+ suggestedItems?: 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
+}
+
+export function MenuFilterCombobox({
+ drillTo,
+ drillItems,
+ suggestedItems,
+ placeholder,
+ onCommit,
+ onBack,
+ title,
+ selectedEntry,
+}: 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()
+ // When opening with chips visible (`drillTo='all'`) and a current
+ // selection exists, start on the matching chip so the user lands on
+ // their selection's category by default — they can still tab back to
+ // "All" or any other chip without leaving the combobox.
+ const [activeChip, setActiveChip] = useState<DrillCategory>(() => {
+ if (drillTo === 'all' && selectedEntry) {
+ return selectedEntry.group.type
+ }
+ return drillTo
+ })
+ const [itemsByType, setItemsByType] = useState<Record<string, TaxonomicDefinitionTypes[]>>({})
+ // 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 inputRef = useRef<HTMLInputElement | null>(null)
+
+ // Stable DOM id for the selected row — must mirror `Row`'s `stableId`
+ // so the checkmark + scroll target can be derived identically here.
+ const selectedRowId = useMemo<string | null>(() => {
+ if (!selectedEntry) {
+ return null
+ }
+ const value = selectedEntry.group.getValue?.(selectedEntry.item) ?? selectedEntry.name
+ return `menu-filter-row-${selectedEntry.group.type}-${String(value)}`
+ }, [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])
+
+ const reportItems = useCallback((type: string, next: TaxonomicDefinitionTypes[]): void => {
+ setItemsByType((prev) => (prev[type] === next ? prev : { ...prev, [type]: next }))
+ }, [])
+
+ // 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])
+
+ // Resolve which groups feed the visible list, based on the active chip
+ // (or the drill scope when chips are hidden).
+ const targetGroups = useMemo<TaxonomicFilterGroup[]>(() => {
+ const scope = showChips ? activeChip : drillTo
+ if (scope === 'all') {
+ return visibleChipGroups
+ }
+ if (scope === 'recent' || scope === 'pinned' || scope === 'suggested') {
+ return [] // items come from `drillItems` / `suggestedItems`
+ }
+ const g = groups.find((gr) => gr.type === scope)
+ return g ? [g] : []
+ }, [showChips, activeChip, drillTo, groups, visibleChipGroups])
+
+ // Indexed entries — flat list across all visible groups (or
+ // pre-resolved `drillItems` for recent/pinned, or pre-merged
+ // `suggestedItems` for the Suggested chip / drill).
+ const indexed = useMemo<MenuFilterEntry[]>(() => {
+ const scope = showChips ? activeChip : drillTo
+ if (scope === 'suggested' && suggestedItems) {
+ return suggestedItems
+ }
+ if (drillItems) {
+ return drillItems
+ }
+ const merged: MenuFilterEntry[] = []
+ for (const group of targetGroups) {
+ const items = itemsByType[group.type] ?? []
+ for (const item of items) {
+ merged.push({
+ item,
+ group,
+ name: getRawName(item, group),
+ friendlyLabel: getFriendlyLabel(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) {
+ const fitsScope =
+ scope === 'all' ||
+ scope === selectedEntry.group.type ||
+ scope === 'recent' ||
+ scope === 'pinned' ||
+ scope === 'suggested'
+ if (fitsScope) {
+ const selectedValue = selectedEntry.group.getValue?.(selectedEntry.item) ?? selectedEntry.name
+ const present = merged.some(
+ (e) =>
+ e.group.type === selectedEntry.group.type &&
+ (e.group.getValue?.(e.item) ?? e.name) === selectedValue
+ )
+ if (!present) {
+ merged.unshift(selectedEntry)
+ }
+ }
+ }
+ return merged
+ }, [drillItems, suggestedItems, targetGroups, itemsByType, selectedEntry, showChips, activeChip, drillTo])
+
+ const filtered = useMemo<MenuFilterEntry[]>(() => {
+ const q = searchQuery.trim()
+ const base = q
+ ? createFuse(indexed, FUSE_OPTIONS as Parameters<typeof createFuse<MenuFilterEntry>>[1])
+ .search(q)
+ .map((r) => r.item)
+ : indexed
+ // 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 pane shows the right definition, and `Enter` re-commits
+ // without forcing the user to scroll. Skip when the user has
+ // typed a search query — relevance order should win there.
+ if (!q && selectedRowId) {
+ const idx = base.findIndex(
+ (e) =>
+ `menu-filter-row-${e.group.type}-${String(e.group.getValue?.(e.item) ?? e.name)}` === selectedRowId
+ )
+ if (idx > 0) {
+ return [base[idx], ...base.slice(0, idx), ...base.slice(idx + 1)]
+ }
+ }
+ return base
+ }, [indexed, searchQuery, selectedRowId])
+
+ // 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' || activeChip === 'suggested') {
+ 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])
+
+ // 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?: string } | null>(() => {
+ if (filtered.length > 0) {
+ return null
+ }
+ const scope = showChips ? activeChip : drillTo
+ const singleGroup =
+ scope !== 'all' && scope !== 'recent' && scope !== 'pinned'
+ ? (groups.find((g) => g.type === scope) ?? 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.`,
+ }
+ }
+ const categoryLabel = singleGroup?.name ?? (showChips ? null : null)
+ if (trimmedLen > 0) {
+ return {
+ title: categoryLabel ? `No "${categoryLabel}" found` : 'No matches',
+ }
+ }
+ return {
+ title: categoryLabel ? `No "${categoryLabel}" found` : 'No items',
+ }
+ }, [filtered.length, showChips, activeChip, drillTo, groups, searchQuery])
+
+ const headerTitle =
+ title ??
+ (drillTo === 'all'
+ ? 'Choose filter'
+ : drillTo === 'recent'
+ ? 'Recent'
+ : drillTo === 'pinned'
+ ? 'Pinned'
+ : drillTo === 'suggested'
+ ? 'Suggested'
+ : (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 chips while focus stays on input. Wraps both directions.
+ const ordered: DrillCategory[] = [
+ 'all',
+ ...(suggestedItems && suggestedItems.length > 0 ? (['suggested'] as const) : []),
+ ...visibleChipGroups.map((g) => g.type),
+ ]
+ const idx = ordered.indexOf(activeChip)
+ const dir = e.shiftKey ? -1 : 1
+ const next = ordered[(idx + dir + ordered.length) % ordered.length]
+ setActiveChip(next)
+ e.preventDefault()
+ e.stopPropagation()
+ }
+ }
+
+ 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={filtered}
+ 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)}
+ >
+ {/* 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">
+ <div className="p-2 border-b">
+ <InputGroup>
+ <Autocomplete.Input
+ render={
+ <InputGroupInput
+ ref={inputRef}
+ autoFocus
+ data-attr="menu-filter-search"
+ placeholder={activePlaceholder}
+ onKeyDown={handleInputKeyDown}
+ />
+ }
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ </InputGroup>
+ </div>
+ {showChips && (
+ <div role="tablist" className="flex flex-wrap gap-1 px-2 py-1 border-b">
+ <ChipButton
+ label="All"
+ active={activeChip === 'all'}
+ onSelect={() => {
+ setActiveChip('all')
+ inputRef.current?.focus()
+ }}
+ />
+ {/* `Suggested` chip = Recent ∪ Pinned across
+ groups. Only render when there's something
+ to surface — empty Suggested just adds
+ visual noise. */}
+ {suggestedItems && suggestedItems.length > 0 && (
+ <ChipButton
+ label="Suggested"
+ active={activeChip === 'suggested'}
+ onSelect={() => {
+ setActiveChip('suggested')
+ inputRef.current?.focus()
+ }}
+ />
+ )}
+ {visibleChipGroups.map((g) => (
+ <ChipButton
+ key={g.type}
+ label={g.name}
+ active={activeChip === g.type}
+ onSelect={() => {
+ setActiveChip(g.type)
+ inputRef.current?.focus()
+ }}
+ />
+ ))}
+ </div>
+ )}
+ {!drillItems &&
+ targetGroups.map((g) => <Fetcher key={g.type} group={g} onItems={reportItems} />)}
+ <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">
+ {emptyState && (
+ <div 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>
+ )}
+ </div>
+ )}
+ </Autocomplete.Empty>
+ <Autocomplete.Collection>
+ {(entry: MenuFilterEntry) => (
+ <Row
+ entry={entry}
+ // Show the category label on mixed-group views (All)
+ // and on Recent/Pinned drills — 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' || drillTo === 'recent' || drillTo === 'pinned'
+ }
+ // DWH rows open the column-config
+ // form, not a final selection —
+ // signal that with a chevron.
+ opensSubmenu={drillTo === TaxonomicFilterGroupType.DataWarehouse}
+ selectedRowId={selectedRowId}
+ onCommit={onCommit}
+ />
+ )}
+ </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 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
+ /** 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
+ onCommit: CommitFn
+}
+
+/**
+ * Resolve a row's three normalized cells:
+ * - name: human-friendly label (e.g. "Pageview", "/checkout")
+ * - value: raw underlying value when distinct from the name
+ * (e.g. "$pageview", "localhost:8010")
+ * - category: group name shown as an uppercase tag at the bottom
+ *
+ * URLs split into path (name) + host (value); friendly definitions
+ * surface the friendly label as the name and the raw `$key` as the
+ * value; everything else uses the entry name as the name and omits
+ * the value cell.
+ */
+function resolveRowCells(entry: MenuFilterEntry): { name: string; value?: string; category: string } {
+ const friendly = entry.friendlyLabel
+ const url = parseUrl(entry.name)
+ if (url) {
+ return { name: url.pathTail, value: url.host, 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, opensSubmenu, selectedRowId, onCommit }: RowProps): JSX.Element {
+ const { item, group } = entry
+ const { name, value, category } = resolveRowCells(entry)
+ const stableId = `menu-filter-row-${group.type}-${String(group.getValue?.(item) ?? entry.name)}`
+ const isSelected = selectedRowId === stableId
+ return (
+ <Autocomplete.Item
+ value={entry}
+ onClick={(e) => {
+ e.preventDefault()
+ onCommit(entry)
+ }}
+ 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-[var(--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-[var(--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>
+
+ <span className="font-mono text-xs text-tertiary/50 leading-tight truncate max-w-full">
+ {value || <span className="opacity-50">N/A</span>}
+ </span>
+ {showCategory && <MenuLabel className="text-tertiary/50 text-xxs p-0 mt-px">{category}</MenuLabel>}
+ </div>
+ {isSelected && <IconCheck className="size-3.5 text-foreground shrink-0" />}
+ {opensSubmenu && <IconChevronRight className="size-3.5 text-tertiary shrink-0" />}
+ </Autocomplete.Item>
+ )
+}
+
+interface ChipButtonProps {
+ label: string
+ active: boolean
+ onSelect: () => void
+}
+
+function ChipButton({ label, active, onSelect }: ChipButtonProps): JSX.Element {
+ return (
+ <Button
+ type="button"
+ role="tab"
+ size="sm"
+ aria-selected={active}
+ variant={active ? 'primary' : 'outline'}
+ onMouseDown={(e: React.MouseEvent<HTMLButtonElement>) => e.preventDefault()}
+ onClick={onSelect}
+ >
+ {label}
+ </Button>
+ )
+}
+
+/**
+ * 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,
+ onItems,
+}: {
+ group: TaxonomicFilterGroup
+ onItems: (type: string, items: TaxonomicDefinitionTypes[]) => void
+}): null {
+ const { getGroupListInput } = useTaxonomicFilterContext()
+ const list = useGroupList(getGroupListInput(group))
+ useEffect(() => {
+ onItems(group.type, list.items)
+ }, [group.type, list.items, onItems])
+ return null
+}
+
+/**
+ * Parse a URL-shaped string into `{ host, pathTail }` for two-line row
+ * rendering. Returns `null` for anything that isn't a `http(s)://` URL or
+ * fails to parse — caller falls back to default rendering.
+ */
+function parseUrl(s: string): { host: string; pathTail: string } | null {
+ if (typeof s !== 'string' || !/^https?:\/\//i.test(s)) {
+ return null
+ }
+ try {
+ const u = new URL(s)
+ const tail = (u.pathname || '/') + u.search + u.hash
+ return { host: u.host, pathTail: tail }
+ } 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
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/DwhFlow.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/DwhFlow.tsx
new file mode 100644
index 000000000000..ed390a6c9070
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/DwhFlow.tsx
@@ -0,0 +1,573 @@
+/**
+ * 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, useState } from 'react'
+
+import {
+ Badge,
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldLabel,
+ ItemContent,
+ ItemDescription,
+ ItemTitle,
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ 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 { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
+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 { 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 HIDDEN_FIELD_TYPES: DatabaseSerializedFieldType[] = ['lazy_table', 'virtual_table', 'view', 'materialized_view']
+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 a real column on the
+ // table (including `''`, the sentinel for "user picked SQL expression
+ // but hasn't typed anything yet"). Keeping the truthy guard off this
+ // check is what surfaces the Monaco editor as soon as the user selects
+ // `SQL expression` from the dropdown.
+ const activeFieldIsHogQL = useMemo(
+ () => !!activeField?.allowHogQL && !columns.some((c) => c.name === activeFieldValue),
+ [activeField, activeFieldValue, columns]
+ )
+
+ // ---- 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 row gap + min-width
+ bound for the LemonTable. */}
+ <DialogBody className="w-full max-w-[700px] 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__'
+
+function ColumnSelect({ options, value, onChange, allowHogQL }: ColumnSelectProps): JSX.Element {
+ // 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
+ return (
+ <Select<string>
+ value={displayValue || undefined}
+ onValueChange={(v) => onChange((v === HOGQL_SENTINEL ? '' : (v as string)) ?? '')}
+ itemToStringLabel={(o) => o ?? ''}
+ itemToStringValue={(o) => o ?? ''}
+ >
+ <SelectTrigger render={(props) => <Button variant="outline" {...props} className="h-min" />}>
+ <SelectValue placeholder="Select a value">
+ {(option: string | null) => {
+ if (!option) {
+ return null
+ }
+ if (option === HOGQL_SENTINEL) {
+ return (
+ <ItemContent variant="menuItem">
+ <ItemTitle>SQL expression</ItemTitle>
+ <ItemDescription className="leading-none">Use a HogQL expression</ItemDescription>
+ </ItemContent>
+ )
+ }
+ const opt = options.find((o) => o.name === option)
+ return (
+ <ItemContent variant="menuItem">
+ <ItemTitle>{option}</ItemTitle>
+ {opt?.type && <ItemDescription className="leading-none">{opt.type}</ItemDescription>}
+ </ItemContent>
+ )
+ }}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent className="min-w-(--anchor-width)" align="start" sideOffset={8}>
+ <SelectGroup>
+ {options.map((o) => (
+ <SelectItem key={o.name} value={o.name} className="py-0">
+ <ItemContent variant="menuItem">
+ <ItemTitle>{o.name}</ItemTitle>
+ <ItemDescription className="leading-none">{o.type}</ItemDescription>
+ </ItemContent>
+ </SelectItem>
+ ))}
+ {allowHogQL && (
+ <SelectItem value={HOGQL_SENTINEL} className="py-0">
+ <ItemContent variant="menuItem">
+ <ItemTitle>SQL expression</ItemTitle>
+ <ItemDescription className="leading-none">Use a HogQL expression</ItemDescription>
+ </ItemContent>
+ </SelectItem>
+ )}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ )
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Header.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Header.tsx
new file mode 100644
index 000000000000..2649d8f40bd4
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Header.tsx
@@ -0,0 +1,53 @@
+/**
+ * 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.tsx
new file mode 100644
index 000000000000..4b4f972367c0
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/HogQLEditor.tsx
@@ -0,0 +1,137 @@
+/**
+ * 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 { lazy, 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 { useTaxonomicFilterContext } from '../headless/context'
+import { TaxonomicFilterGroupType } from '../types'
+import { MenuFilterHeader } from './Header'
+import { CommitFn, MenuFilterEntry } from './types'
+
+const CodeEditorInline = lazy(() =>
+ 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/PreviewPane.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/PreviewPane.tsx
new file mode 100644
index 000000000000..d7c7a8d1876e
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/PreviewPane.tsx
@@ -0,0 +1,170 @@
+/**
+ * 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 { IconPin } from '@posthog/icons'
+import { Button, cn, ScrollArea, Separator } from '@posthog/quill'
+
+import { Link } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { ActionType, CohortType, EventDefinition, PropertyDefinition } from '~/types'
+
+import { useTaxonomicAutocompleteItemDetails } from '../headless'
+import { TaxonomicFilterGroupType } from '../types'
+import { ActionMatchGroups } from './preview/ActionMatchGroups'
+import { MenuFilterEntry } from './types'
+
+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)
+ 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)
+
+ return (
+ <ScrollArea className="flex-1 min-h-0">
+ <div className="flex flex-col gap-3 p-3 text-sm">
+ <PreviewHeader details={details} viewUrl={viewUrl} />
+
+ {details.description ? (
+ <p className="text-xs leading-relaxed text-secondary">{details.description}</p>
+ ) : (
+ <p className="text-xs italic text-tertiary">No 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-xxs uppercase tracking-wide text-secondary">Property type</div>
+ <div className="text-xs">{details.propertyType}</div>
+ </div>
+ )}
+
+ {details.rawName && details.rawName !== details.title && (
+ <div className="flex flex-col gap-0.5 border-t pt-2">
+ <div className="text-xxs uppercase tracking-wide text-secondary">Sent as</div>
+ <code className="text-xs break-all font-mono">{details.rawName}</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
+}
+
+function PreviewHeader({ details, viewUrl }: 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={details.togglePin}
+ >
+ <IconPin className="size-3.5" />
+ {details.isPinned ? 'Pinned' : 'Pin'}
+ </Button>
+ {viewUrl && (
+ <Button
+ variant="link"
+ className="text-primary"
+ size="sm"
+ 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>
+ </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.
+ */
+function resolveViewUrl(entry: MenuFilterEntry): 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 = (item as PropertyDefinition).id
+ 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.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx
new file mode 100644
index 000000000000..cc43d89c547a
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx
@@ -0,0 +1,301 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useMountedLogic } from 'kea'
+import { useState } from 'react'
+
+import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__mocks__/taxonomicFilterMocksDecorator'
+
+import { actionsModel } from '~/models/actionsModel'
+
+import { TaxonomicFilterHeadless } from '../headless'
+import { DataWarehousePopoverField, TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'
+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: {
+ 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).',
+ },
+ },
+ },
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx
new file mode 100644
index 000000000000..7323dc6b9ac8
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx
@@ -0,0 +1,613 @@
+/**
+ * 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 } from '@posthog/icons'
+import {
+ Button,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@posthog/quill'
+
+import { getCoreFilterDefinition } from '~/taxonomy/helpers'
+
+import { useTaxonomicFilterContext } from '../headless/context'
+import { recentTaxonomicFiltersLogic } from '../recentTaxonomicFiltersLogic'
+import { taxonomicFilterPinnedPropertiesLogic } from '../taxonomicFilterPinnedPropertiesLogic'
+import { META_GROUP_TYPES, TaxonomicDefinitionTypes, TaxonomicFilterGroupType } from '../types'
+import { MenuFilterCombobox } from './Combobox'
+import { MenuFilterDwhConfig } from './DwhFlow'
+import { MenuFilterHogQLEditor } from './HogQLEditor'
+import { CommitFn, DrillCategory, MenuFilterEntry, MenuFilterState, 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
+ /**
+ * 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
+}
+
+export interface TriggerState {
+ label: string
+ selected: MenuFilterEntry | null
+ open: boolean
+}
+
+export function TaxonomicFilterMenu({
+ triggerLabel,
+ selected,
+ trigger,
+ onCommit,
+ placeholder,
+ comboboxTitle,
+ dataWarehousePopoverFields,
+ insightProps,
+}: TaxonomicFilterMenuProps): JSX.Element {
+ const { groups, selectItem, inputProps, searchQuery } = useTaxonomicFilterContext()
+ const [state, setState] = useState<MenuFilterState>({ kind: 'closed' })
+
+ // 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') {
+ openedAtRef.current = Date.now()
+ hadCommitRef.current = false
+ posthog.capture('taxonomic filter menu opened', {
+ openedTo: next,
+ hadSelection: !!selected,
+ triggerLabel,
+ })
+ } else if (previous !== 'closed' && next !== 'closed' && previous !== next) {
+ posthog.capture('taxonomic filter menu drilled', {
+ fromState: previous,
+ toState: next,
+ })
+ } else if (previous !== 'closed' && next === 'closed') {
+ posthog.capture('taxonomic filter menu closed', {
+ dwellMs: openedAtRef.current ? Date.now() - openedAtRef.current : null,
+ hadCommit: hadCommitRef.current,
+ lastState: previous,
+ })
+ 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' }), [])
+
+ /**
+ * Resolve the initial state when the trigger opens. 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.
+ */
+ const resolveOpenState = useCallback((): 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' }
+ }
+ // Land on the regular combobox with chips visible — the matching
+ // chip auto-selects via `selectedEntry` inside the combobox so the
+ // user keeps full context and can switch categories without
+ // bouncing back to the dropdown menu.
+ return { kind: 'combobox', drillTo: 'all' }
+ }, [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)
+
+ const recentEntries = useMemo<MenuFilterEntry[]>(
+ () => mapShortcutItems(recentFilterItems as ShortcutItem[], groups),
+ [recentFilterItems, groups]
+ )
+ const pinnedEntries = useMemo<MenuFilterEntry[]>(
+ () => mapShortcutItems(pinnedFilterItems as ShortcutItem[], groups),
+ [pinnedFilterItems, groups]
+ )
+ /*
+ * Suggested = Recent ∪ Pinned across all groups, mirroring the
+ * legacy popover's "Suggested step" view. Recent comes first
+ * (chronologically more relevant to the user); pinned fills in
+ * the curated picks. Dedup on `(group.type, value)` so a pinned
+ * entry that's also recent only shows once. Each entry keeps its
+ * source `group` reference so the row's category label still
+ * reads "Events", "Actions", etc. (not "Suggested filters").
+ */
+ const suggestedEntries = useMemo<MenuFilterEntry[]>(() => {
+ const seen = new Set<string>()
+ const out: MenuFilterEntry[] = []
+ for (const entry of [...recentEntries, ...pinnedEntries]) {
+ const value = entry.group.getValue?.(entry.item) ?? entry.name
+ const key = `${entry.group.type}::${String(value)}`
+ if (seen.has(key)) {
+ continue
+ }
+ seen.add(key)
+ out.push(entry)
+ }
+ return out
+ }, [recentEntries, pinnedEntries])
+
+ 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) => {
+ const mergedItem = extra
+ ? ({ ...(entry.item as unknown as object), ...extra } as unknown as TaxonomicDefinitionTypes)
+ : entry.item
+ const itemValue = entry.group.getValue?.(mergedItem) ?? 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,
+ })
+ 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>)
+
+ // -- 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'
+
+ // 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
+ }
+ 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()
+ }}
+ >
+ {/*
+ * `flex min-w-0 w-full` (not `inline-flex`) so the wrap
+ * fills its parent column instead of sizing to the
+ * trigger's intrinsic width. Without `min-w-0` the
+ * default `min-width: auto` makes the wrap grow to its
+ * content and overflow narrow parents — long filter
+ * names then bleed past the parity wrapper instead of
+ * truncating like the legacy trigger.
+ */}
+ <span ref={triggerWrapRef} className="relative flex min-w-0 w-full">
+ <DropdownMenuTrigger render={triggerEl} data-attr="taxonomic-filter-menu-trigger" />
+ <PopoverTrigger
+ render={<span aria-hidden tabIndex={-1} className="absolute inset-0 pointer-events-none" />}
+ />
+ </span>
+ <PopoverContent
+ align="start"
+ side="bottom"
+ sideOffset={4}
+ container={popoverContainer}
+ 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
+ : state.drillTo === 'suggested'
+ ? suggestedEntries
+ : undefined
+ }
+ // Always pass `suggestedItems` so the chip
+ // works in 'all' mode too (without forcing a
+ // drill via the dropdown menu).
+ suggestedItems={suggestedEntries}
+ 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}
+ onCommit={handleCommit}
+ onBack={openMenu}
+ />
+ )}
+ {(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}
+ />
+ )}
+ {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
+ 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]">
+ <DropdownMenuItem onClick={() => openCombobox('all')} data-attr="taxonomic-filter-menu-new">
+ New filter…
+ <IconChevronRight className="ml-auto size-3.5 text-tertiary" />
+ </DropdownMenuItem>
+ {recentEntries.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => openCombobox('recent')}>
+ Recent
+ <IconChevronRight className="ml-auto size-3.5 text-tertiary" />
+ </DropdownMenuItem>
+ </>
+ )}
+ {pinnedEntries.length > 0 && (
+ <DropdownMenuItem onClick={() => openCombobox('pinned')}>
+ Pinned
+ <IconChevronRight className="ml-auto size-3.5 text-tertiary" />
+ </DropdownMenuItem>
+ )}
+ {(hasDwh || hasHogql) && <DropdownMenuSeparator />}
+ {hasDwh && (
+ <DropdownMenuItem onClick={openDwhPick} data-attr="taxonomic-filter-menu-dwh">
+ Data warehouse tables
+ <IconChevronRight className="ml-auto size-3.5 text-tertiary" />
+ </DropdownMenuItem>
+ )}
+ {hasHogql && (
+ <DropdownMenuItem onClick={openHogql} data-attr="taxonomic-filter-menu-hogql">
+ HogQL expression
+ <IconChevronRight className="ml-auto size-3.5 text-tertiary" />
+ </DropdownMenuItem>
+ )}
+ </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?: unknown }
+ _recentContext?: { sourceGroupType?: TaxonomicFilterGroupType; sourceValue?: unknown }
+}
+
+/**
+ * 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?: unknown } | undefined)?.sourceValue ??
+ (ctx as { value?: unknown } | undefined)?.value
+ const group = resolveShortcutGroup(item, sourceType, sourceValue, groups)
+ if (!group) {
+ return null
+ }
+ const name = (item.name as string) ?? group.getName?.(item as TaxonomicDefinitionTypes) ?? ''
+ return {
+ item: item as TaxonomicDefinitionTypes,
+ group,
+ name,
+ friendlyLabel: getCoreFilterDefinition(name, group.type)?.label,
+ } as MenuFilterEntry
+ })
+ .filter((e): e is MenuFilterEntry => e != null)
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/index.ts b/frontend/src/lib/components/TaxonomicFilter/menu/index.ts
new file mode 100644
index 000000000000..bba8d411d609
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/index.ts
@@ -0,0 +1,34 @@
+/**
+ * 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.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/preview/ActionMatchGroups.tsx
new file mode 100644
index 000000000000..3b1a186d6fa9
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/preview/ActionMatchGroups.tsx
@@ -0,0 +1,107 @@
+/**
+ * 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 { Separator } from '@posthog/quill'
+
+import { genericOperatorToHumanName, propertyValueToHumanName } from 'lib/components/DefinitionPopover/utils'
+
+import { ActionStepType, ActionType } from '~/types'
+
+import { TaxonomicDefinitionTypes } from '../../types'
+
+export function ActionMatchGroups({ item }: { item: TaxonomicDefinitionTypes }): JSX.Element | null {
+ const action = item as ActionType
+ 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/types.ts b/frontend/src/lib/components/TaxonomicFilter/menu/types.ts
new file mode 100644
index 000000000000..13898914cf5c
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/types.ts
@@ -0,0 +1,55 @@
+/**
+ * Shared types for the dropdown-menu-fronted taxonomic filter.
+ *
+ * See `../headless/UX_SPEC.md` for the full design.
+ */
+import {
+ TaxonomicDefinitionTypes,
+ TaxonomicFilterGroup,
+ TaxonomicFilterGroupType,
+ TaxonomicFilterValue,
+} from '../types'
+
+/** A single selectable entry — what the picker commits when chosen. */
+export interface MenuFilterEntry {
+ item: TaxonomicDefinitionTypes
+ group: TaxonomicFilterGroup
+ name: string
+ friendlyLabel?: string
+}
+
+/** Synthetic categories the combobox panel can be drilled into.
+ * - `'suggested'` mixes Recent ∪ Pinned across groups, mirroring the
+ * legacy popover's "Suggested step" view; the row's category label
+ * still names the original source group. */
+export type DrillCategory = 'all' | 'recent' | 'pinned' | 'suggested' | 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
+}
+
+export type CommitFn = (entry: MenuFilterEntry, extra?: Record<string, unknown>) => void
+
+export type { TaxonomicFilterGroup, TaxonomicFilterGroupType, TaxonomicFilterValue, TaxonomicDefinitionTypes }
diff --git a/frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts b/frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts
index 3567b17389e7..f357296f576e 100644
--- a/frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts
@@ -31,6 +31,12 @@ export interface RecentTaxonomicFilter {
export interface RecentItemContext {
sourceGroupType: TaxonomicFilterGroupType
sourceGroupName: string
+ /**
+ * Canonical value the entry was recorded under (e.g. `action.id`,
+ * `event.name`). Lets consumers resolve the underlying definition
+ * when the recorded source group is a META group (Suggested filters)
+ * or otherwise unavailable.
+ */
sourceValue: TaxonomicFilterValue
teamId?: number
propertyFilter?: AnyPropertyFilter
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts
index 1574e6ace4ee..43caa825f353 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts
@@ -77,15 +77,20 @@ describe('taxonomicFilterPinnedPropertiesLogic', () => {
expect(logic.values.isPinned(groupType, value)).toBe(pinned)
})
- it('pinnedFilterItems includes _pinnedContext with sourceGroupType and sourceGroupName', () => {
+ it('pinnedFilterItems includes _pinnedContext with sourceGroupType, sourceGroupName, and value', () => {
const item = { name: '$pageview' }
logic.actions.togglePin(TaxonomicFilterGroupType.Events, 'Events', '$pageview', item)
const items = logic.values.pinnedFilterItems
expect(items).toHaveLength(1)
+ // `value` is on the context so groups whose `getValue` reads a
+ // field other than `name` (e.g. Actions → `id`) can roundtrip
+ // through the shrunk-down stored item without losing the key
+ // needed for isPinned / togglePin lookups.
expect((items[0] as any)._pinnedContext).toEqual({
sourceGroupType: TaxonomicFilterGroupType.Events,
sourceGroupName: 'Events',
+ value: '$pageview',
})
})
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts
index 9f5f1c67114d..8f7e19bbcb68 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts
@@ -16,6 +16,14 @@ export interface PinnedTaxonomicFilter {
export interface PinnedItemContext {
sourceGroupType: TaxonomicFilterGroupType
sourceGroupName: string
+ /**
+ * Canonical value the entry was pinned under (e.g. `action.id`,
+ * `property.name`). Stored alongside the item because the reducer
+ * shrinks `item` down to `{ name }` for storage; without this,
+ * groups whose `getValue` reads a different field (Actions →
+ * `id`) can't roundtrip into a pinned/unpinned check.
+ */
+ value: TaxonomicFilterValue
}
export function hasPinnedContext(item: unknown): item is Record<string, any> & { _pinnedContext: PinnedItemContext } {
@@ -91,6 +99,7 @@ export const taxonomicFilterPinnedPropertiesLogic = kea<taxonomicFilterPinnedPro
_pinnedContext: {
sourceGroupType: f.groupType,
sourceGroupName: f.groupName,
+ value: f.value,
} as PinnedItemContext,
}) as unknown as TaxonomicDefinitionTypes
),
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts b/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts
new file mode 100644
index 000000000000..5c27e97af2d0
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildGroupAnalyticsGroups.ts
@@ -0,0 +1,64 @@
+import { combineUrl } from 'kea-router'
+
+import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { capitalizeFirstLetter, toParams } from 'lib/utils'
+import { getPropertyDefinitionIcon } from 'scenes/data-management/events/DefinitionHeader'
+import { groupDisplayId } from 'scenes/persons/GroupActorDisplay'
+
+import { Group, GroupType } from '~/types'
+
+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/environments/${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.tsx
new file mode 100644
index 000000000000..5f49046e93d3
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx
@@ -0,0 +1,1030 @@
+import clsx from 'clsx'
+import { combineUrl } from 'kea-router'
+
+import { IconFlag, IconServer } from '@posthog/icons'
+
+import {
+ buildAutocaptureSeriesShortcuts,
+ buildEventTypeFilterShortcuts,
+} from 'lib/components/TaxonomicFilter/eventTypeShortcuts'
+import { recentTaxonomicFiltersLogic } from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'
+import { taxonomicFilterPinnedPropertiesLogic } from 'lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic'
+import {
+ DataWarehousePopoverField,
+ SimpleOption,
+ TaxonomicDefinitionTypes,
+ TaxonomicFilterGroup,
+ TaxonomicFilterGroupType,
+ TaxonomicFilterValue,
+} from 'lib/components/TaxonomicFilter/types'
+import { withKeywordShortcuts } from 'lib/components/TaxonomicFilter/utils/keywordShortcuts'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { IconCohort } from 'lib/lemon-ui/icons'
+import { Link } from 'lib/lemon-ui/Link'
+import { isString, pluralize } from 'lib/utils'
+import {
+ getEventDefinitionIcon,
+ getEventMetadataDefinitionIcon,
+ getPropertyDefinitionIcon,
+ getRevenueAnalyticsDefinitionIcon,
+} from 'scenes/data-management/events/DefinitionHeader'
+import { dataWarehouseSettingsSceneLogic } from 'scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic'
+import { experimentsLogic } from 'scenes/experiments/experimentsLogic'
+import { COHORT_BEHAVIORAL_LIMITATIONS_URL } from 'scenes/feature-flags/constants'
+import {
+ getProductEventFilterOptions,
+ getProductEventPropertyFilterOptions,
+} from 'scenes/hog-functions/filters/HogFunctionFiltersInternal'
+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,
+ QueryBasedInsightModel,
+ SessionRecordingPlaylistType,
+ TeamType,
+} from '~/types'
+
+import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
+import { HogFlowTaxonomicFilters } from 'products/workflows/frontend/Workflows/hogflows/filters/HogFlowTaxonomicFilters'
+
+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[]
+ /**
+ * 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)[]>>
+ }
+ eventMetadataPropertyDefinitions: PropertyDefinition[]
+ maxContextOptions: MaxContextTaxonomicFilterOption[]
+ hideBehavioralCohorts: boolean
+ endpointFilters: Record<string, any> | undefined
+ hogQLExpressionComponentProps: {
+ globals?: Record<string, any>
+ showBreakdownLabelHint: boolean
+ }
+ featureFlags: Record<string, boolean | string | undefined>
+}
+
+export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): TaxonomicFilterGroup[] {
+ const {
+ currentTeam,
+ projectId,
+ groupAnalyticsTaxonomicGroups,
+ groupAnalyticsTaxonomicGroupNames,
+ eventNames,
+ promotedPropertiesForContextEvents = [],
+ schemaColumns,
+ schemaColumnsLoading,
+ metadataSource,
+ suggestedFiltersLabel,
+ propertyFilters,
+ eventMetadataPropertyDefinitions,
+ maxContextOptions,
+ hideBehavioralCohorts,
+ endpointFilters,
+ hogQLExpressionComponentProps,
+ featureFlags,
+ } = ctx
+ const { id: teamId } = currentTeam
+ const { excludedProperties, propertyAllowList } = propertyFilters
+ 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,
+ }).url,
+ excludedProperties: excludedProperties?.[TaxonomicFilterGroupType.Events]?.filter(isString) ?? [],
+ ...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: HogFlowTaxonomicFilters,
+ 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'].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
+ : []),
+ ],
+ 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',
+ },
+ {
+ 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/environments/${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,
+ })),
+ ...(currentTeam?.person_display_name_properties
+ ? currentTeam.person_display_name_properties.map((property) => ({
+ name: property,
+ value: property,
+ group: TaxonomicFilterGroupType.PersonProperties,
+ }))
+ : []),
+ ],
+ 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: (option: PropertyDefinition): JSX.Element => getRevenueAnalyticsDefinitionIcon(option),
+ 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/environments/${projectId}/revenue_analytics/taxonomy/values?key=${encodeURIComponent(key)}`
+ },
+ getPopoverHeader: () => 'Revenue analytics properties',
+ },
+ {
+ name: 'Logs',
+ searchPlaceholder: 'logs',
+ type: TaxonomicFilterGroupType.Logs,
+ options: [{ key: 'message', name: 'Message', propertyFilterType: 'log' }],
+ localItemsSearch: (items: any[], q: string): any[] => {
+ if (!q) {
+ return items
+ }
+ return [
+ {
+ key: 'message',
+ name: 'Search log message for "' + q + '"',
+ value: q,
+ propertyFilterType: 'log',
+ },
+ ].concat(items.filter((item) => item.name?.toLowerCase().includes(q.toLowerCase())))
+ },
+ 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/environments/${projectId}/logs/attributes`, {
+ attribute_type: 'log',
+ search_values: 'true',
+ ...endpointFilters,
+ }).url,
+ valuesEndpoint: (key) =>
+ combineUrl(`api/environments/${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/environments/${projectId}/logs/attributes`, {
+ attribute_type: 'resource',
+ search_values: 'true',
+ ...endpointFilters,
+ }).url,
+ valuesEndpoint: (key) =>
+ combineUrl(`api/environments/${projectId}/logs/values`, {
+ attribute_type: 'resource',
+ key: key,
+ ...endpointFilters,
+ }).url,
+ getName: (option: SimpleOption) => option.name,
+ getValue: (option: SimpleOption) => option.name,
+ getPopoverHeader: () => 'Resource 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/environments/${projectId}/tracing/spans/values`, {
+ attribute_type: 'span',
+ key: key,
+ ...endpointFilters,
+ }).url
+ : undefined,
+ localItemsSearch: (items: any[], q: string): any[] => {
+ if (!q) {
+ return items
+ }
+ return [
+ {
+ key: 'message',
+ name: 'Search span message for "' + q + '"',
+ value: q,
+ propertyFilterType: 'span',
+ },
+ ].concat(items.filter((item) => item.name?.toLowerCase().includes(q.toLowerCase())))
+ },
+ 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/environments/${projectId}/tracing/spans/attributes`, {
+ attribute_type: 'span',
+ ...endpointFilters,
+ }).url,
+ valuesEndpoint: (key) =>
+ combineUrl(`api/environments/${projectId}/tracing/spans/values`, {
+ attribute_type: 'span',
+ 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/environments/${projectId}/tracing/spans/attributes`, {
+ attribute_type: 'resource',
+ ...endpointFilters,
+ }).url,
+ valuesEndpoint: (key) =>
+ combineUrl(`api/environments/${projectId}/tracing/spans/values`, {
+ attribute_type: 'resource',
+ 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),
+ },
+ {
+ name: 'Cohorts',
+ searchPlaceholder: 'cohorts',
+ type: TaxonomicFilterGroupType.Cohorts,
+ endpoint: combineUrl(`api/projects/${projectId}/cohorts/`).url,
+ value: 'cohorts',
+ getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,
+ getValue: (cohort: CohortType) => cohort.id,
+ 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/`).url,
+ options: COHORTS_WITH_ALL_USERS_OPTIONS,
+ getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,
+ getValue: (cohort: CohortType) => cohort.id,
+ 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/environments/${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,
+ searchDescription: 'URLs seen on pageview events',
+ },
+ {
+ name: 'Pageview events',
+ searchPlaceholder: 'pageview events',
+ type: TaxonomicFilterGroupType.PageviewEvents,
+ endpoint: `api/environments/${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,
+ 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/environments/${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/environments/${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/environments/${teamId}/persons/values/?key=email`,
+ searchAlias: 'value',
+ getName: (option: SimpleOption) => option.name,
+ getValue: (option: SimpleOption) => option.name,
+ getPopoverHeader: () => `Email address`,
+ minSearchQueryLength: 5,
+ searchDescription: 'email addresses seen in person properties',
+ },
+ {
+ name: 'Autocapture events',
+ searchPlaceholder: 'autocapture events',
+ type: TaxonomicFilterGroupType.AutocaptureEvents,
+ endpoint: `api/environments/${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,
+ }).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/environments/${teamId}/persons/`,
+ getName: (person: PersonType) => person.name || 'Anon user?',
+ getValue: (person: PersonType) => person.distinct_ids[0],
+ getPopoverHeader: () => `Person`,
+ },
+ {
+ name: 'Insights',
+ searchPlaceholder: 'insights',
+ type: TaxonomicFilterGroupType.Insights,
+ endpoint: combineUrl(`api/environments/${teamId}/insights/`, {
+ saved: true,
+ }).url,
+ getName: (insight: QueryBasedInsightModel) => insight.name,
+ getValue: (insight: QueryBasedInsightModel) => 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
+ return isInactive ? `${name} (disabled)` : name
+ },
+ getValue: (featureFlag: FeatureFlagType) => featureFlag.id || '',
+ getPopoverHeader: () => `Feature Flags`,
+ getIcon: (featureFlag: FeatureFlagType) => (
+ <IconFlag className={clsx('size-4', !featureFlag.active && 'text-muted-alt opacity-50')} />
+ ),
+ getIsDisabled: (featureFlag: FeatureFlagType) => !featureFlag.active,
+ 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',
+ 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/environments/${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,
+ 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,
+ },
+ ],
+ getName: (option: Record<string, any>) => option.name,
+ getValue: (option: Record<string, any>) => option.key,
+ valuesEndpoint: (key) => {
+ if (key === 'visited_page') {
+ return (
+ `api/environments/${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,
+ 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.map((name) => ({
+ name,
+ group: TaxonomicFilterGroupType.EventProperties,
+ })),
+ ...(eventNames.includes('$autocapture')
+ ? (['text', 'selector'] as const).map((name) => ({
+ name,
+ group: TaxonomicFilterGroupType.Elements,
+ }))
+ : []),
+ ],
+ getName: (item: TaxonomicDefinitionTypes) => ('name' in item ? item.name : '') || '',
+ getValue: (item: TaxonomicDefinitionTypes): TaxonomicFilterValue =>
+ 'name' in item ? (item.name ?? null) : null,
+ getPopoverHeader: () => suggestedFiltersLabel ?? 'Suggested filters',
+ },
+ {
+ name: 'Recent',
+ searchPlaceholder: 'recent',
+ type: TaxonomicFilterGroupType.RecentFilters,
+ isLocalOnly: true,
+ isMetaGroup: true,
+ logic: recentTaxonomicFiltersLogic,
+ value: 'recentFilterItems',
+ getName: (item: TaxonomicDefinitionTypes) => ('name' in item ? item.name : '') || '',
+ getValue: (item: TaxonomicDefinitionTypes): TaxonomicFilterValue =>
+ 'name' in item ? (item.name ?? null) : null,
+ getPopoverHeader: () => 'Recent',
+ } as TaxonomicFilterGroup,
+ {
+ name: 'Pinned',
+ searchPlaceholder: 'pinned',
+ type: TaxonomicFilterGroupType.PinnedFilters,
+ isLocalOnly: true,
+ isMetaGroup: true,
+ logic: taxonomicFilterPinnedPropertiesLogic,
+ value: 'pinnedFilterItems',
+ getName: (item: TaxonomicDefinitionTypes) => ('name' in item ? item.name : '') || '',
+ getValue: (item: TaxonomicDefinitionTypes): TaxonomicFilterValue =>
+ 'name' in item ? (item.name ?? null) : null,
+ getPopoverHeader: () => 'Pinned',
+ } as TaxonomicFilterGroup,
+ ...groupAnalyticsTaxonomicGroups,
+ ...groupAnalyticsTaxonomicGroupNames,
+ ]
+
+ return groups
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/keywordShortcuts.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/keywordShortcuts.tsx
new file mode 100644
index 000000000000..2c9388f26a4e
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/keywordShortcuts.tsx
@@ -0,0 +1,52 @@
+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/promoteProperties.ts b/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts
new file mode 100644
index 000000000000..8429f70fe567
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts
@@ -0,0 +1,48 @@
+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[]> = {
+ url: ['$current_url'],
+ email: ['$email'],
+}
+
+/**
+ * If the search query matches a promoted property's search terms, move that property
+ * to the top of results so users find it quickly.
+ */
+export function promoteMatchingProperties<T extends TaxonomicDefinitionTypes | SkeletonItem>(
+ results: T[],
+ searchQuery: string
+): T[] {
+ if (!searchQuery) {
+ return results
+ }
+
+ const query = searchQuery.toLowerCase().trim()
+ const promotedPropertyNames = PROMOTED_PROPERTIES_BY_SEARCH_TERM[query]
+ if (!promotedPropertyNames?.length) {
+ return results
+ }
+
+ const promotedPropertyNameSet = new Set(promotedPropertyNames)
+ const promoted: T[] = []
+ const rest: T[] = []
+
+ for (const item of results as (T | undefined)[]) {
+ if (!item) {
+ continue
+ }
+ if (isSkeletonItem(item)) {
+ rest.push(item)
+ continue
+ }
+ const name = 'name' in item ? (item as { name?: string }).name : undefined
+ if (name && promotedPropertyNameSet.has(name)) {
+ promoted.push(item)
+ } else {
+ rest.push(item)
+ }
+ }
+
+ return promoted.length > 0 ? [...promoted, ...rest] : results
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/redistributeTopMatches.ts b/frontend/src/lib/components/TaxonomicFilter/utils/redistributeTopMatches.ts
new file mode 100644
index 000000000000..753c47c2814b
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/redistributeTopMatches.ts
@@ -0,0 +1,78 @@
+import { TaxonomicDefinitionTypes, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+export const DEFAULT_SLOTS_PER_GROUP = 5
+export const MAX_TOP_MATCHES_PER_GROUP = 10
+export const SKELETON_ROWS_PER_GROUP = 3
+
+export const REDISTRIBUTION_PRIORITY_GROUPS: TaxonomicFilterGroupType[] = [
+ TaxonomicFilterGroupType.CustomEvents,
+ TaxonomicFilterGroupType.PageviewUrls,
+ TaxonomicFilterGroupType.Screens,
+]
+
+export type TopMatchItem = TaxonomicDefinitionTypes & { group: TaxonomicFilterGroupType }
+
+export function redistributeTopMatches(
+ items: TopMatchItem[],
+ activeGroupCount: number,
+ groupTypeOrder: TaxonomicFilterGroupType[] = []
+): TopMatchItem[] {
+ if (items.length === 0) {
+ return []
+ }
+
+ const byGroup = new Map<TaxonomicFilterGroupType, TopMatchItem[]>()
+ for (const item of items) {
+ if (!byGroup.has(item.group)) {
+ byGroup.set(item.group, [])
+ }
+ byGroup.get(item.group)!.push(item)
+ }
+
+ const allocated = new Map<TaxonomicFilterGroupType, TopMatchItem[]>()
+ let usedSlots = 0
+ for (const [groupType, groupItems] of byGroup) {
+ const take = Math.min(groupItems.length, DEFAULT_SLOTS_PER_GROUP)
+ allocated.set(groupType, groupItems.slice(0, take))
+ usedSlots += take
+ }
+
+ if (byGroup.size < 3) {
+ const totalSlots = DEFAULT_SLOTS_PER_GROUP * activeGroupCount
+ let surplus = totalSlots - usedSlots
+ if (surplus > 0) {
+ const presentGroups = Array.from(byGroup.keys())
+ const priorityOrder = [
+ ...REDISTRIBUTION_PRIORITY_GROUPS.filter((g) => presentGroups.includes(g)),
+ ...presentGroups.filter((g) => !REDISTRIBUTION_PRIORITY_GROUPS.includes(g)),
+ ]
+
+ for (const groupType of priorityOrder) {
+ if (surplus <= 0) {
+ break
+ }
+ const groupItems = byGroup.get(groupType)!
+ const currentlyAllocated = allocated.get(groupType) || []
+ const remaining = groupItems.slice(currentlyAllocated.length, MAX_TOP_MATCHES_PER_GROUP)
+ const extra = Math.min(remaining.length, surplus)
+ if (extra > 0) {
+ allocated.set(groupType, [...currentlyAllocated, ...remaining.slice(0, extra)])
+ surplus -= extra
+ }
+ }
+ }
+ }
+
+ const displayOrder =
+ groupTypeOrder.length > 0 ? groupTypeOrder.filter((g) => allocated.has(g)) : Array.from(allocated.keys())
+
+ const result: TopMatchItem[] = []
+ for (const groupType of displayOrder) {
+ const groupItems = allocated.get(groupType)
+ if (groupItems) {
+ result.push(...groupItems)
+ }
+ }
+
+ return result
+}
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7cb2d57e9b4a..67b933eb4450 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -473,6 +473,8 @@ export const FEATURE_FLAGS = {
TASK_TOOL: 'phai-task-tool', // owner: @kappa90 #team-posthog-ai
TASKS: 'tasks', // owner: #team-llm-analytics
TAXONOMIC_FILTER_CATEGORY_DROPDOWN: 'taxonomic-filter-category-dropdown', // owner: @pauldambra #team-product-analytics multivariate=control,pill
+ TAXONOMIC_FILTER_HEADLESS: 'taxonomic-filter-headless', // owner: @adamleith, opt-in to the headless useTaxonomicFilter rewrite
+ TAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the new TaxonomicFilterMenu (column / preview-pane) for series row pickers
TOGGLE_PROPERTY_ARRAYS: 'toggle-property-arrays', // owner: @arthurdedeus #team-customer-analytics
TRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)
TRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analytics
diff --git a/frontend/src/scenes/insights/EditorFilters/funnelDataWarehouseStepDefinitionPopoverLogic.ts b/frontend/src/scenes/insights/EditorFilters/funnelDataWarehouseStepDefinitionPopoverLogic.ts
index dd8b4248fff8..ff00228fa123 100644
--- a/frontend/src/scenes/insights/EditorFilters/funnelDataWarehouseStepDefinitionPopoverLogic.ts
+++ b/frontend/src/scenes/insights/EditorFilters/funnelDataWarehouseStepDefinitionPopoverLogic.ts
@@ -72,19 +72,28 @@ export const funnelDataWarehouseStepDefinitionPopoverLogic = kea<funnelDataWareh
selectors({
columnOptions: [
(_, p) => [p.table],
+ // `table.fields` may be missing when the table is reconstructed
+ // from a committed filter (new menu rebuild path passes
+ // `{ name, id }` without re-attaching the full schema). Empty
+ // array prevents the `Object.values(undefined)` crash; the
+ // user reopens via the table picker to get full options.
(table) =>
- Object.values(table.fields).map((column) => ({
- label: `${column.name} (${column.type})`,
- value: column.name,
- type: column.type,
- })),
+ table.fields
+ ? Object.values(table.fields).map((column) => ({
+ label: `${column.name} (${column.type})`,
+ value: column.name,
+ type: column.type,
+ }))
+ : [],
],
linkedTables: [
(_, p) => [p.table],
(table) =>
- Object.values(table.fields)
- .filter((field) => LINKED_TABLE_TYPES.includes(field.type))
- .map((field) => field.name),
+ table.fields
+ ? Object.values(table.fields)
+ .filter((field) => LINKED_TABLE_TYPES.includes(field.type))
+ .map((field) => field.name)
+ : [],
],
activeFieldKeyOptions: [
(s) => [s.dataWarehousePopoverFields],
@@ -115,15 +124,19 @@ export const funnelDataWarehouseStepDefinitionPopoverLogic = kea<funnelDataWareh
(_, p) => [p.table],
(table) => ({
...table,
- fields: Object.fromEntries(
- Object.entries(table.fields).filter(([_, field]) => !HIDDEN_FIELD_TYPES.includes(field.type))
- ),
+ fields: table.fields
+ ? Object.fromEntries(
+ Object.entries(table.fields).filter(([_, field]) => !HIDDEN_FIELD_TYPES.includes(field.type))
+ )
+ : {},
}),
],
previewExpressionColumns: [
(s, p) => [p.table, s.dataWarehousePopoverFields, s.scopedLocalDefinition],
(table, dataWarehousePopoverFields, scopedLocalDefinition): TablePreviewExpressionColumn[] => {
- const tableFieldNames = new Set(Object.values(table.fields).map((field) => field.name))
+ const tableFieldNames = new Set(
+ table.fields ? Object.values(table.fields).map((field) => field.name) : []
+ )
const usedKeys = new Set(tableFieldNames)
return EDITABLE_FIELD_ORDER.flatMap((fieldKey) => {
const configuredValue = (
@@ -184,7 +197,8 @@ export const funnelDataWarehouseStepDefinitionPopoverLogic = kea<funnelDataWareh
],
activeFieldIsHogQL: [
(s, p) => [s.activeFieldValue, p.table],
- (activeFieldValue, table) => !Object.values(table.fields).some((field) => field.name === activeFieldValue),
+ (activeFieldValue, table) =>
+ !table.fields || !Object.values(table.fields).some((field) => field.name === activeFieldValue),
],
isAggregatingByGroup: [
(s) => [s.querySource],
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
index ab6d08d98beb..09ebe529a733 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
@@ -8,11 +8,21 @@ import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
import { useCallback } from 'react'
-import { IconCopy, IconFilter, IconGroupIntersect, IconPencil, IconTrash } from '@posthog/icons'
+import {
+ IconChevronDown,
+ IconCopy,
+ IconFilter,
+ IconGroupIntersect,
+ IconInfo,
+ IconPencil,
+ IconTrash,
+} from '@posthog/icons'
import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
import { SeriesGlyph, SeriesLetter } from 'lib/components/SeriesGlyph'
+import { TaxonomicAutocomplete, TaxonomicFilterHeadless } from 'lib/components/TaxonomicFilter/headless'
+import { MenuFilterEntry, TaxonomicFilterMenu } from 'lib/components/TaxonomicFilter/menu'
import { defaultDataWarehousePopoverFields } from 'lib/components/TaxonomicFilter/taxonomicFilterLogic'
import {
DataWarehousePopoverField,
@@ -21,8 +31,11 @@ import {
quickFilterToPropertyFilters,
} from 'lib/components/TaxonomicFilter/types'
import { TaxonomicPopover, TaxonomicPopoverProps } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
+import { FEATURE_FLAGS } from 'lib/constants'
import { IconWithCount, SortableDragIcon } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { Tooltip } from 'lib/lemon-ui/Tooltip/Tooltip'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getEventNamesForAction } from 'lib/utils'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
@@ -131,6 +144,15 @@ export function ActionFilterRow({
const { actions } = useValues(actionsModel)
const { mathDefinitions } = useValues(mathsLogic)
const { dataWarehouseTablesMap } = useValues(databaseTableListLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const useMenuRebuild = !!featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]
+ const useHeadlessAutocomplete = !!featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_HEADLESS]
+ // The new picker ramps in via either flag — `useNewPicker` gates the
+ // entire wrapper so users with both flags off see only the legacy
+ // `filterElement`. Without this guard the parity widget mounts for
+ // every user (even outside the rollout), which contradicts the
+ // "legacy path unchanged" promise.
+ const useNewPicker = useMenuRebuild || useHeadlessAutocomplete
const mountedInsightDataLogic = insightDataLogic.findMounted({ dashboardItemId: typeKey })
const query = mountedInsightDataLogic?.values?.query
@@ -543,6 +565,204 @@ export function ActionFilterRow({
)}
>
<div className="flex-1 min-w-36 overflow-hidden">{filterElement}</div>
+ {/* Production-testing variant: the new
+ TaxonomicFilterMenu (column / preview-pane
+ view) renders alongside the legacy
+ TaxonomicPopover so we can ramp it as the
+ series-row picker. Gated behind either
+ rollout flag so the parity wrapper +
+ `TaxonomicFilterHeadless.Root` orchestrator
+ aren't mounted for users outside the
+ ramp — preserves the "legacy path
+ unchanged" promise from the PR. */}
+ {useNewPicker && (
+ <div
+ className="flex-1 min-w-36 overflow-hidden"
+ data-attr={`series-parity-autocomplete-${index}`}
+ >
+ <TaxonomicFilterHeadless.Root
+ // Skip the legacy rootProps wrapper —
+ // its onKeyDown intercepts Tab/Arrow
+ // for the old list UI we don't render
+ // here, and traps Tab off the trigger.
+ bindRootProps={false}
+ taxonomicGroupTypes={effectiveActionsTaxonomicGroupTypes}
+ onChange={(group, changedValue, item) => {
+ const groupType = taxonomicFilterGroupTypeToEntityType(group.type)
+ if (!groupType) {
+ return
+ }
+ updateFilter({
+ type: groupType,
+ id: changedValue ? String(changedValue) : null,
+ name: item?.name ?? '',
+ index,
+ })
+ }}
+ >
+ {useMenuRebuild ? (
+ <TaxonomicFilterMenu
+ triggerLabel="All events"
+ comboboxTitle="Choose series filter"
+ // Synthetic entry — the menu only
+ // reads `group.type` (to route
+ // the initial open) and `name` /
+ // `friendlyLabel` (for the
+ // trigger label). A full
+ // `TaxonomicFilterGroup` isn't
+ // needed here.
+ selected={
+ // DWH filters often have `filter.id == null`
+ // (the table name lives on `filter.name`),
+ // so gate on whichever of id/name is present
+ // — otherwise the trigger label falls back to
+ // the default and ignores the active selection.
+ filter.type && (filter.id != null || filter.name)
+ ? ({
+ // DWH filters need the saved column
+ // mapping (`id_field` /
+ // `timestamp_field` /
+ // `distinct_id_field` etc.) on the
+ // `item` so re-opening the menu
+ // routes into `dwh-config` with the
+ // form pre-filled. Spread the whole
+ // filter for DWH; events/actions
+ // only need id + name.
+ item:
+ filter.type === EntityTypes.DATA_WAREHOUSE
+ ? {
+ // `...filter` already provides
+ // `name`; DWH `getValue` reads
+ // it. Pull in the resolved
+ // schema (`fields` etc.) from
+ // `dataWarehouseTablesMap` so
+ // re-opening the menu routes
+ // into `dwh-config` with the
+ // form pre-filled.
+ ...filter,
+ ...dataWarehouseTablesMap[
+ String(filter.name)
+ ],
+ }
+ : { id: filter.id, name: filter.name },
+ group: {
+ type:
+ filter.type === EntityTypes.ACTIONS
+ ? TaxonomicFilterGroupType.Actions
+ : filter.type === EntityTypes.DATA_WAREHOUSE
+ ? TaxonomicFilterGroupType.DataWarehouse
+ : TaxonomicFilterGroupType.Events,
+ // DWH config form reads `getName`
+ // / `getValue` off `selected.group`
+ // when re-opening, so provide them
+ // for the DWH branch. Events /
+ // Actions don't need them — the
+ // resolved orchestrator group is
+ // used for those once the user
+ // commits.
+ getName: (t: any) => t?.name,
+ getValue: (t: any) => t?.name,
+ },
+ name: String(name ?? filter.name ?? filter.id),
+ friendlyLabel: name ? String(name) : undefined,
+ } as unknown as MenuFilterEntry)
+ : null
+ }
+ trigger={({ selected, label, open }) => (
+ // `min-w-0` lets the truncate inside the button
+ // actually clip — without it the flex child grows
+ // to its content's intrinsic width and the row
+ // overflows the parent column.
+ <div className="relative min-w-0 border border-dashed border-accent p-1 rounded-sm">
+ <LemonButton
+ type="secondary"
+ fullWidth
+ data-attr={`series-parity-autocomplete-trigger-${index}`}
+ aria-expanded={open}
+ sideIcon={<IconChevronDown />}
+ truncate
+ >
+ {selected ? (
+ <EntityFilterInfo
+ filter={filter}
+ showIcon
+ allowWrap={false}
+ />
+ ) : (
+ <span className="text-secondary truncate">{label}</span>
+ )}
+ </LemonButton>
+ <div className="absolute -top-1 -right-1">
+ <Tooltip
+ title={
+ <>
+ INTERNAL ONLY
+ <br />
+ The new TaxonomicFilterMenu. <br />
+ Try it out, leave feedback/wishlist!
+ <br />
+ Owned by <b>#platform-ux</b>
+ </>
+ }
+ >
+ <IconInfo className="size-4 text-accent bg-surface-primary" />
+ </Tooltip>
+ </div>
+ </div>
+ )}
+ />
+ ) : (
+ <TaxonomicAutocomplete.Root
+ key={`${filter.type}:${String(filter.id ?? '')}`}
+ triggerLabel="All events"
+ defaultSelected={
+ filter.id != null && filter.type
+ ? {
+ groupType:
+ filter.type === EntityTypes.ACTIONS
+ ? TaxonomicFilterGroupType.Actions
+ : TaxonomicFilterGroupType.Events,
+ value: value ?? null,
+ name: String(name ?? filter.id),
+ friendlyLabel: name ? String(name) : undefined,
+ }
+ : null
+ }
+ >
+ <TaxonomicAutocomplete.Popover>
+ <TaxonomicAutocomplete.Trigger>
+ {({ selected, label, open }) => (
+ <LemonButton
+ type="secondary"
+ fullWidth
+ data-attr={`series-parity-autocomplete-trigger-${index}`}
+ aria-expanded={open}
+ sideIcon={<IconChevronDown />}
+ >
+ {selected ? (
+ <EntityFilterInfo filter={filter} showIcon />
+ ) : (
+ <span className="text-secondary">{label}</span>
+ )}
+ </LemonButton>
+ )}
+ </TaxonomicAutocomplete.Trigger>
+ <TaxonomicAutocomplete.Content>
+ <TaxonomicAutocomplete.Header rootTitle="Pick event or action" />
+ <TaxonomicAutocomplete.RootView>
+ <div className="p-1">
+ <TaxonomicAutocomplete.Input />
+ </div>
+ <TaxonomicAutocomplete.Chips />
+ <TaxonomicAutocomplete.List />
+ </TaxonomicAutocomplete.RootView>
+ </TaxonomicAutocomplete.Content>
+ </TaxonomicAutocomplete.Popover>
+ </TaxonomicAutocomplete.Root>
+ )}
+ </TaxonomicFilterHeadless.Root>
+ </div>
+ )}
{customRowSuffix !== undefined && <>{suffix}</>}
{mathAvailability !== MathAvailability.None &&
mathAvailability !== MathAvailability.FunnelsOnly && (
diff --git a/frontend/src/styles/quill-bridge.scss b/frontend/src/styles/quill-bridge.scss
index 7efa6fba6d90..c32bebd1ee1a 100644
--- a/frontend/src/styles/quill-bridge.scss
+++ b/frontend/src/styles/quill-bridge.scss
@@ -27,6 +27,16 @@
* emits no rule for them and the elements render unstyled. We
* register them as plain CSS rules pointing at quill's tokens.
*
+ * - `[data-quill] [data-not-quill]` escape hatch: cancels the colour
+ * rebindings for nested non-quill subtrees so PostHog primitives
+ * rendered inside a quill panel (e.g. `DatabaseTablePreview`,
+ * `LemonSelect`, monaco) keep their original colours. CSS variable
+ * resolution is lazy at use site, so we can't snapshot the originals
+ * into an alias — the only working approach is to re-bind back to
+ * base.scss's underlying source-of-truth tokens. Mirror every entry
+ * in `[data-quill]` here, plus a `[theme="dark"]` variant for the
+ * dark-theme branches.
+ *
* Long-term plan: rename quill's colour tokens to `--quill-*` so the
* `[data-quill]` colour rebindings become unnecessary. Tracked separately.
* Until then, this file is the single integration seam — every new colour
@@ -74,12 +84,21 @@
--color-accent-active: var(--accent);
}
+/*
+ * Reset various annoying global styles from global styles.
+ */
+[data-quill] p,
+[data-quill] h2 {
+ margin-bottom: 0;
+}
+
/*
* Override #2: register the quill-only utilities PostHog's compiler skipped.
* Scoped to `[data-quill]` so they don't pollute the rest of the app.
* Specificity (0,2,0) beats Tailwind's plain class (0,1,0), so these always
* win inside the subtree even if PostHog later adds a same-named class.
*/
+
[data-quill] .bg-background {
background-color: var(--background);
}
@@ -182,3 +201,56 @@
[data-quill] .ring-destructive\/20 {
--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent);
}
+
+/*
+ * ---- [data-not-quill] escape hatch ---------------------------------------
+ *
+ * When non-quill PostHog content is rendered inside a quill subtree (e.g.
+ * the DataWarehouseTablePreview, LemonSelect, monaco, or any legacy
+ * component), wrap it in `data-not-quill` to restore PostHog's colour
+ * system inside that subtree.
+ *
+ * Specificity (0,2,0) of `[data-quill] [data-not-quill]` beats `[data-quill]`
+ * (0,1,0), so these rebindings always win for nested content. The values
+ * mirror what base.scss sets at `:root` / `[theme="dark"]` — duplicating
+ * them is unfortunate but lazy CSS variable evaluation makes a snapshot
+ * impossible.
+ */
+[data-quill] [data-not-quill] {
+ --muted-3000: var(--muted-3000-light);
+ --color-bg-primary: var(--color-posthog-3000-50);
+ --color-bg-surface-primary: var(--color-white);
+ --color-bg-surface-secondary: var(--color-posthog-3000-100);
+ --color-bg-surface-tertiary: var(--color-posthog-3000-150);
+ --color-text-primary: var(--color-neutral-950);
+ --color-text-secondary: var(--color-neutral-750);
+ --color-border-primary: var(--color-posthog-3000-200);
+ --color-border-secondary: var(--color-posthog-3000-400);
+ --color-accent: hsl(
+ var(--color-brand-primary-hue),
+ var(--color-brand-primary-saturation),
+ var(--color-brand-primary-lightness)
+ );
+ --color-accent-hover: hsl(
+ var(--color-brand-primary-hue),
+ var(--color-brand-primary-saturation),
+ calc(var(--color-brand-primary-lightness) + 10%)
+ );
+ --color-accent-active: hsl(
+ var(--color-brand-primary-hue),
+ var(--color-brand-primary-saturation),
+ calc(var(--color-brand-primary-lightness) + 15%)
+ );
+}
+
+[theme='dark'] [data-quill] [data-not-quill] {
+ --muted-3000: var(--muted-3000-dark);
+ --color-bg-primary: var(--color-neutral-cool-950);
+ --color-bg-surface-primary: var(--color-neutral-cool-850);
+ --color-bg-surface-secondary: var(--color-neutral-cool-900);
+ --color-bg-surface-tertiary: var(--color-neutral-cool-950);
+ --color-text-primary: var(--color-neutral-100);
+ --color-text-secondary: var(--color-neutral-350);
+ --color-border-primary: var(--color-neutral-cool-800);
+ --color-border-secondary: var(--color-neutral-cool-600);
+}
diff --git a/packages/quill/packages/primitives/src/dialog.css b/packages/quill/packages/primitives/src/dialog.css
index 2153504d692f..4ada5e7ba511 100644
--- a/packages/quill/packages/primitives/src/dialog.css
+++ b/packages/quill/packages/primitives/src/dialog.css
@@ -20,11 +20,28 @@
}
.quill-dialog__content {
+ /*
+ * Distance from the top of the viewport. Extracted into a CSS
+ * variable so `top` and `max-height` can stay in lockstep — the
+ * dialog can always reserve a symmetric `1rem` margin at the
+ * bottom regardless of viewport height.
+ */
+ --quill-dialog-top-gap: max(1rem, 10vh + 1.25rem * var(--nested-dialogs, 0));
+
position: fixed;
inset-inline-start: 50%;
- top: calc(max(1rem, 10vh + 1.25rem * var(--nested-dialogs, 0)));
+ top: var(--quill-dialog-top-gap);
width: 100%;
max-width: calc(100vw - 3rem);
+
+ /*
+ * Bound height to viewport so the footer is always pinned and
+ * visible, even on short windows. Pairs with the
+ * `grid-template-rows` rule below — the body row absorbs all
+ * leftover height as the only `1fr` track and scrolls
+ * internally instead of pushing the footer off-screen.
+ */
+ max-height: calc(100dvh - var(--quill-dialog-top-gap) - 1rem);
overflow: hidden;
font-size: var(--text-xs, 0.75rem);
line-height: 1.625;
@@ -46,6 +63,39 @@
translate: -50% 0;
}
+ /*
+ * When the dialog has a `DialogBody`, lock the grid into three rows
+ * and let only the body absorb leftover height. `minmax(0, 1fr)` is
+ * the load-bearing piece — a bare `1fr` track has implicit
+ * `min-height: min-content` and won't shrink past its child, which
+ * would push the footer past the viewport on short windows. Scoping
+ * via `:has([data-slot='dialog-body'])` leaves dialogs without a
+ * body unaffected (their rows stay `auto`).
+ */
+ .quill-dialog__content:has([data-slot='dialog-body']) {
+ grid-template-rows: auto minmax(0, 1fr) auto;
+ }
+
+ /*
+ * Width variants — opt-in via the `size` prop on `<DialogContent>`.
+ * Defaults stay at the existing ~24rem clamp from the
+ * `@media (min-width: 640px)` rule below, so existing dialogs
+ * render unchanged.
+ *
+ * - `data-size='wide'` — clamps to ~72rem (1152px), shrinks
+ * proportionally below; intended for dialogs that embed wide
+ * content like data tables or side-by-side editors.
+ * - `data-size='full'` — drops the desktop clamp entirely and
+ * grows to `calc(100vw - 3rem)`; for true full-bleed dialogs.
+ */
+ .quill-dialog__content[data-size='wide'] {
+ max-width: min(72rem, calc(100vw - 3rem));
+ }
+
+ .quill-dialog__content[data-size='full'] {
+ max-width: calc(100vw - 3rem);
+ }
+
[dir='rtl'] .quill-dialog__content {
translate: 50% 0;
}
@@ -82,15 +132,44 @@
}
.quill-dialog__body {
+ /*
+ * `min-height: 0` lets the body shrink past its content's min
+ * size in the dialog grid (otherwise the `minmax(0, 1fr)` row
+ * still ends up at `min-content` because of the body's own
+ * implicit min-height). Combined with `overflow: auto` (or the
+ * inner ScrollArea viewport when the body defaults to a
+ * ScrollArea), this is what makes long content scroll inside
+ * the dialog instead of stretching it past the viewport.
+ */
+ min-height: 0;
padding-inline: 1rem;
}
+ /*
+ * Plain (non-ScrollArea) body becomes the scroll container itself.
+ * `DialogBody` defaults to a ScrollArea wrapper (see `dialog.tsx`)
+ * so this branch covers consumers who explicitly opt out via
+ * `<DialogBody render={<div/>} />`.
+ */
+ .quill-dialog__body:not([data-component='scroll-area']) {
+ overflow: auto;
+ }
+
+ /*
+ * ScrollArea variant — the default. Shift padding off the root
+ * (which contains the scrollbar) onto the viewport so content has
+ * 1rem of inline padding inside the scrollable region while the
+ * scrollbar sits flush against the body edge. `padding-block: 1rem`
+ * gives breathing room above and below the scrolled content;
+ * scroll shadows still hug the row edges.
+ */
.quill-dialog__body[data-component='scroll-area'] {
- margin-block: -1rem;
+ padding-inline: 0;
}
.quill-dialog__body[data-component='scroll-area'] > [data-slot='scroll-area-viewport'] {
padding-block: 1rem;
+ padding-inline: 1rem;
}
.quill-dialog__title {
diff --git a/packages/quill/packages/primitives/src/dialog.tsx b/packages/quill/packages/primitives/src/dialog.tsx
index f19ed7671b7f..c6e433bf3083 100644
--- a/packages/quill/packages/primitives/src/dialog.tsx
+++ b/packages/quill/packages/primitives/src/dialog.tsx
@@ -7,6 +7,7 @@ import * as React from 'react'
import { Button } from './button'
import './dialog.css'
import { cn } from './lib/utils'
+import { ScrollArea } from './scroll-area'
/** Note: if you're nesting dialogs, in order for you to click the overlay to close it, you must pass 'mounted: true' to the nested dialog*/
function Dialog({ ...props }: DialogPrimitive.Root.Props): React.ReactElement {
@@ -42,10 +43,21 @@ function DialogContent({
children,
showCloseButton = true,
nested = false,
+ size,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
nested?: boolean
+ /**
+ * Width variant. Defaults to the standard ~24rem dialog width
+ * (Quill's existing media-query clamp at ≥640px viewports).
+ * - `'wide'`: clamps to `min(72rem, calc(100vw - 3rem))` for
+ * content that needs horizontal breathing room (data tables,
+ * side-by-side editors, etc.).
+ * - `'full'`: drops the desktop clamp entirely and grows to
+ * `calc(100vw - 3rem)`.
+ */
+ size?: 'wide' | 'full'
}): React.ReactElement {
return (
<DialogPortal>
@@ -54,6 +66,7 @@ function DialogContent({
data-quill
data-quill-portal="modal-content"
data-slot="dialog-content"
+ data-size={size}
className={cn('quill-dialog__content grid gap-4', className)}
{...props}
>
@@ -98,16 +111,40 @@ function DialogFooter({
)
}
-function DialogBody({ className, render, ...props }: useRender.ComponentProps<'div'>): React.ReactElement {
+function DialogBody({
+ className,
+ render,
+ children,
+ ...props
+}: useRender.ComponentProps<'div'>): React.ReactElement {
+ /*
+ * Default render = `<ScrollArea>` so consumers get scroll shadows
+ * (and edge-overflow data attrs) for free. The scroll-area-aware
+ * branches in `dialog.css` (`[data-component='scroll-area']`) take
+ * care of moving padding into the viewport so content doesn't ride
+ * against the scrollbar.
+ *
+ * Consumers can override with `<DialogBody render={<div />}>` for
+ * a plain non-scrolling body, or `<DialogBody render={<ScrollArea
+ * scrollShadows={false} />}>` to tweak the scroll-area config.
+ *
+ * `useRender` is called unconditionally — when no consumer render
+ * is provided we substitute a `<ScrollArea>` template so the hooks
+ * order stays stable (eslint-plugin-react-hooks would flag a
+ * conditional call otherwise, since `useRender` starts with `use`).
+ */
+ const effectiveRender =
+ render ?? <ScrollArea data-slot="dialog-body" className={cn('quill-dialog__body', className)} />
return useRender({
defaultTagName: 'div',
props: mergeProps<'div'>(
{
className: cn('quill-dialog__body', className),
+ children,
} as Omit<React.ComponentProps<'div'>, 'ref'>,
props
),
- render,
+ render: effectiveRender,
state: { slot: 'dialog-body' },
})
}
diff --git a/packages/quill/packages/primitives/src/index.ts b/packages/quill/packages/primitives/src/index.ts
index 170a6f1f4074..3239b37f243a 100644
--- a/packages/quill/packages/primitives/src/index.ts
+++ b/packages/quill/packages/primitives/src/index.ts
@@ -65,6 +65,7 @@ export {
} from './context-menu'
export {
Dialog,
+ DialogBody,
DialogClose,
DialogContent,
DialogDescription,
diff --git a/packages/quill/packages/primitives/src/popover.tsx b/packages/quill/packages/primitives/src/popover.tsx
index e3d2eef3f9d7..990713b47f68 100644
--- a/packages/quill/packages/primitives/src/popover.tsx
+++ b/packages/quill/packages/primitives/src/popover.tsx
@@ -18,11 +18,22 @@ function PopoverContent({
alignOffset = 0,
side = 'bottom',
sideOffset = 4,
+ container,
...props
}: PopoverPrimitive.Popup.Props &
- Pick<PopoverPrimitive.Positioner.Props, 'align' | 'alignOffset' | 'side' | 'sideOffset'>): React.ReactElement {
+ Pick<PopoverPrimitive.Positioner.Props, 'align' | 'alignOffset' | 'side' | 'sideOffset'> &
+ Pick<PopoverPrimitive.Portal.Props, 'container'>): React.ReactElement {
+ /*
+ * `container` opt-in lets consumers mount the popover inside a
+ * specific DOM subtree instead of `document.body`. Useful when
+ * popover content needs to inherit ancestor context that doesn't
+ * survive a portal jump — most notably CSS container queries
+ * (`@container/<name>`), which only follow DOM ancestors. Pass a
+ * ref to the container-query host and the portaled content can
+ * read its size as if it were a direct child.
+ */
return (
- <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Portal container={container}>
<PopoverPrimitive.Positioner
data-quill
data-quill-portal="popover"
diff --git a/packages/quill/packages/primitives/src/scroll-area.css b/packages/quill/packages/primitives/src/scroll-area.css
index 7240812c6a61..b886486fe440 100644
--- a/packages/quill/packages/primitives/src/scroll-area.css
+++ b/packages/quill/packages/primitives/src/scroll-area.css
@@ -71,6 +71,24 @@
opacity: 1;
}
+ /*
+ * Hide the scrollbar entirely when its axis has no overflow. base-ui
+ * always renders both Scrollbar elements; `data-overflow-{x,y}-{start,end}`
+ * lives on the Root and only appears when scroll is possible on that
+ * axis. Without these guards a content-fits-viewport region still shows
+ * a full-track stationary thumb on hover, which reads as "stale UI" to
+ * users. Hide outright when neither edge has overflow.
+ */
+ [data-component='scroll-area']:not([data-overflow-y-start], [data-overflow-y-end])
+ .quill-scroll-area__scrollbar[data-orientation='vertical'] {
+ display: none;
+ }
+
+ [data-component='scroll-area']:not([data-overflow-x-start], [data-overflow-x-end])
+ .quill-scroll-area__scrollbar[data-orientation='horizontal'] {
+ display: none;
+ }
+
/* Thumb */
.quill-scroll-area__thumb {
position: relative;
diff --git a/packages/quill/packages/primitives/src/scroll-area.tsx b/packages/quill/packages/primitives/src/scroll-area.tsx
index d2558908d4e8..bb1409cdb9d0 100644
--- a/packages/quill/packages/primitives/src/scroll-area.tsx
+++ b/packages/quill/packages/primitives/src/scroll-area.tsx
@@ -189,16 +189,27 @@ function ScrollArea({
hideScrollbars = false,
alwaysShowScrollbars = false,
showScrollToButton,
+ viewportClassName,
...props
}: ScrollAreaPrimitive.Root.Props & {
scrollShadows?: boolean
hideScrollbars?: boolean
alwaysShowScrollbars?: boolean
showScrollToButton?: ShowScrollToButton
+ viewportClassName?: string
}): React.ReactElement {
const viewportRef = React.useRef<HTMLDivElement | null>(null)
const edges = resolveEdges(showScrollToButton)
- if (process.env.NODE_ENV !== 'production' && hideScrollbars && alwaysShowScrollbars) {
+ // `typeof process` (vs `process.env.NODE_ENV` directly) avoids the
+ // `Cannot find name 'process'` TS error in builds without
+ // `@types/node`. Surfaced once `dialog.tsx` started importing
+ // `ScrollArea`, which dragged this file into Quill's typecheck.
+ if (
+ typeof process !== 'undefined' &&
+ process.env?.NODE_ENV !== 'production' &&
+ hideScrollbars &&
+ alwaysShowScrollbars
+ ) {
// eslint-disable-next-line no-console
console.warn(
'[ScrollArea] `hideScrollbars` and `alwaysShowScrollbars` are mutually exclusive; `alwaysShowScrollbars` will be ignored.'
@@ -217,7 +228,7 @@ function ScrollArea({
<ScrollAreaPrimitive.Viewport
ref={viewportRef}
data-slot="scroll-area-viewport"
- className="quill-scroll-area__viewport"
+ className={cn("quill-scroll-area__viewport", viewportClassName)}
>
{children}
</ScrollAreaPrimitive.Viewport>