Skip to content

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

fix(insights): dedup selected event in rebuilt taxonomic menu (#63477)

Paul D'Ambraed7e7d4c540b
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
index c900d2eac890..de7b0b631e60 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
@@ -13,8 +13,9 @@ import { initKeaTests } from '~/test/init'
import { TaxonomicFilterHeadless } from '../headless'
import { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'
-import { TaxonomicFilterGroupType } from '../types'
+import { TaxonomicDefinitionTypes, TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'
import { MenuFilterCombobox, SEARCH_QUERY_DEBOUNCE_MS } from './Combobox'
+import { MenuFilterEntry } from './types'
jest.mock('~/queries/query', () => ({
performQuery: jest.fn(),
@@ -215,6 +216,141 @@ describe('MenuFilterCombobox', () => {
expect(rowsText).toContain('Power users')
})
+ // Mirrors the synthetic entry built by `TaxonomicPopoverMenu` for an
+ // already-selected event value (e.g. the trends series picker reopened on
+ // "Pageview"). `value` is whatever the call site threads through — the raw
+ // event key `$pageview` or, when `filter.name` holds the label, `Pageview`.
+ // getValue returns name-or-id just like the adapter.
+ function syntheticEventSelected(value: string): MenuFilterEntry {
+ return {
+ item: { id: value, name: value } as TaxonomicDefinitionTypes,
+ // Deliberate partial — only the three fields the menu reads from a
+ // synthetic selection. Cast (as the production adapter does) rather
+ // than populate the full group shape. The `MenuFilterEntry` return
+ // type is what keeps the entry contract compiler-checked.
+ group: {
+ type: TaxonomicFilterGroupType.Events,
+ getName: (t) => t?.name,
+ getValue: (t) => t?.name ?? t?.id,
+ } as TaxonomicFilterGroup,
+ name: value,
+ }
+ }
+
+ function renderEventsWithSelection(options: {
+ searchQuery?: string
+ selectedEntry?: MenuFilterEntry
+ }): ReturnType<typeof render> {
+ return render(
+ <Provider>
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}
+ onChange={jest.fn()}
+ searchQuery={options.searchQuery ?? ''}
+ >
+ <MenuFilterCombobox
+ drillTo="all"
+ selectedEntry={options.selectedEntry}
+ onCommit={jest.fn()}
+ onBack={jest.fn()}
+ />
+ </TaxonomicFilterHeadless.Root>
+ </Provider>
+ )
+ }
+
+ // The committed selection arrives as a synthetic entry whose value is
+ // either the raw event key (`$pageview`) or — when `ActionFilterRow` threads
+ // `filter.name` and that holds the display label — the friendly label
+ // (`Pageview`). Both must collapse onto the real endpoint row instead of
+ // stranding a placeholder beside it with a second checkmark and a blank
+ // preview.
+ it.each([
+ ['the raw key', '$pageview'],
+ ['the friendly label', 'Pageview'],
+ ])(
+ 'dedups the synthetic selected event against the real endpoint event when the value is %s',
+ async (_label, selectedValue) => {
+ apiGet.mockImplementation((url: string) => {
+ if (url.includes('event_definitions')) {
+ return Promise.resolve({
+ results: [
+ { id: 'def-1', name: '$pageview' },
+ { id: 'def-2', name: '$bot_pageview' },
+ ],
+ count: 2,
+ })
+ }
+ return Promise.resolve({ results: [], count: 0 })
+ })
+
+ renderEventsWithSelection({
+ searchQuery: 'pagev',
+ selectedEntry: syntheticEventSelected(selectedValue),
+ })
+
+ await waitFor(() => expect(rowTexts().some((t) => t.includes('$bot_pageview'))).toBe(true))
+ // Exactly one "Pageview" row…
+ const pageviewRows = rowTexts().filter((t) => t.includes('Pageview') && !t.includes('bot'))
+ expect(pageviewRows).toHaveLength(1)
+ // …and the surviving row is the real definition (carries the raw
+ // `$pageview` value), not the synthetic placeholder (which would render
+ // just the label with no raw value).
+ expect(pageviewRows[0]).toContain('$pageview')
+ // The selection resolves onto the real row so the checkmark + preview
+ // track it: the real row's DOM id must exist to be targeted.
+ expect(document.getElementById('menu-filter-row-events-$pageview')).toBeInTheDocument()
+ // …and the synthetic placeholder row — the one that carried the
+ // stray second checkmark in the bug — must not be rendered at all.
+ expect(document.getElementById('menu-filter-row-events-Pageview')).not.toBeInTheDocument()
+ // The preview pane picks up the real definition ("Sent as $pageview"),
+ // not the synthetic placeholder (which has no core definition and so
+ // renders neither a raw value nor a description).
+ const preview = document.querySelector('[data-slot="menu-filter-preview"]')
+ expect(preview?.textContent).toContain('Sent as')
+ expect(preview?.textContent).toContain('$pageview')
+ }
+ )
+
+ it('prefers an exact value match over the friendly-label heuristic when a custom event shares the label', async () => {
+ // A custom event literally named "Pageview" coexists with core
+ // "$pageview" (friendly label "Pageview"). A selection whose value is
+ // "Pageview" must resolve to the custom event (exact value match), not
+ // the core row it only label-matches — and both real rows stay (they're
+ // distinct definitions), with no synthetic placeholder.
+ apiGet.mockImplementation((url: string) => {
+ if (url.includes('event_definitions')) {
+ return Promise.resolve({
+ results: [
+ { id: 'def-core', name: '$pageview' },
+ { id: 'def-custom', name: 'Pageview' },
+ ],
+ count: 2,
+ })
+ }
+ return Promise.resolve({ results: [], count: 0 })
+ })
+
+ renderEventsWithSelection({
+ searchQuery: 'pagev',
+ selectedEntry: syntheticEventSelected('Pageview'),
+ })
+
+ await waitFor(() => expect(document.getElementById('menu-filter-row-events-Pageview')).toBeInTheDocument())
+ // Both distinct events render — the custom "Pageview" did not dedup the
+ // core "$pageview" away, and no synthetic placeholder was prepended.
+ expect(document.getElementById('menu-filter-row-events-$pageview')).toBeInTheDocument()
+ const rows = Array.from(document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]'))
+ expect(rows).toHaveLength(2)
+ // The persistent selected tint (`bg-(--fill-hover)`, a discrete class
+ // token distinct from the `data-selected:`-prefixed hover variant) lands
+ // on the exact-match custom event, not the label-match core row.
+ const customRow = document.getElementById('menu-filter-row-events-Pageview')
+ const coreRow = document.getElementById('menu-filter-row-events-$pageview')
+ expect(customRow?.classList.contains('bg-(--fill-hover)')).toBe(true)
+ expect(coreRow?.classList.contains('bg-(--fill-hover)')).toBe(false)
+ })
+
it('caches the cohorts first page and filters typed queries locally (no per-keystroke refetch)', async () => {
// Track every cohorts request — there must be exactly one even after
// typing, because client-side fuse takes over after the first page.
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
index 2cf8e87b62c4..e590d39b9202 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
@@ -95,21 +95,52 @@ const NO_ENTRIES: MenuFilterEntry[] = []
* legacy picker so the search telemetry is comparable across variants. */
export const SEARCH_QUERY_DEBOUNCE_MS = 500
+/** An entry's canonical value — what the dedup key, the DOM id, and the
+ * selection match all key off. They MUST agree (a row keyed one way but
+ * matched another is the bug class this file guards against), so they share
+ * this single derivation rather than repeating it. */
+function entryValue(entry: MenuFilterEntry): string {
+ return String(entry.group.getValue?.(entry.item) ?? entry.name)
+}
+
/** Identity for an entry's underlying definition — source group + value.
* Uses `::` as separator to serve as a dedup key (distinct from DOM ids). */
function entryKey(entry: MenuFilterEntry): string {
- return `${entry.group.type}::${String(entry.group.getValue?.(entry.item) ?? entry.name)}${
- entry.recentPropertyFilter ? '::full' : ''
- }`
+ return `${entry.group.type}::${entryValue(entry)}${entry.recentPropertyFilter ? '::full' : ''}`
}
/** Stable DOM id for a menu row — used for scroll-into-view, checkmark
* lookups, and `aria-activedescendant`. The format must be identical
* everywhere it is constructed. */
function rowDomId(entry: MenuFilterEntry): string {
- return `menu-filter-row-${entry.group.type}-${String(entry.group.getValue?.(entry.item) ?? entry.name)}${
- entry.recentPropertyFilter ? '-full' : ''
- }`
+ return `menu-filter-row-${entry.group.type}-${entryValue(entry)}${entry.recentPropertyFilter ? '-full' : ''}`
+}
+
+/** Exact match: the entry's canonical value equals the selection's. This is the
+ * authoritative match — when it holds, the two are the same definition. */
+function entryValueMatchesSelection(entry: MenuFilterEntry, selected: MenuFilterEntry): boolean {
+ return entry.group.type === selected.group.type && entryValue(entry) === entryValue(selected)
+}
+
+/** Heuristic match: the selection's stored value equals the entry's raw name or
+ * resolved friendly label. `ActionFilterRow` threads `filter.name`, which can
+ * be the friendly label (`Pageview`) rather than the raw key (`$pageview`), so
+ * a synthetic entry built from the label won't match the real row on value
+ * alone — this bridges that gap. Looser than the value match: a custom event
+ * literally named `Pageview` would label-match the core `$pageview` row, so
+ * callers must prefer `entryValueMatchesSelection` first (see `selectedRowId`). */
+function entryLabelMatchesSelection(entry: MenuFilterEntry, selected: MenuFilterEntry): boolean {
+ if (entry.group.type !== selected.group.type) {
+ return false
+ }
+ const target = entryValue(selected)
+ return entry.name === target || (entry.friendlyLabel != null && entry.friendlyLabel === target)
+}
+
+/** Either kind of match — used for dedup, where any real row representing the
+ * selection means we must not also prepend a synthetic placeholder. */
+function entryMatchesSelection(entry: MenuFilterEntry, selected: MenuFilterEntry): boolean {
+ return entryValueMatchesSelection(entry, selected) || entryLabelMatchesSelection(entry, selected)
}
function fuseMatchEntries(entries: MenuFilterEntry[], query: string): MenuFilterEntry[] {
@@ -222,48 +253,6 @@ export function MenuFilterCombobox({
includeStaleEventsRef.current = includeStaleEvents
}, [includeStaleEvents])
- // Stable DOM id for the selected row — derived via `rowDomId` to stay in
- // sync with `Row`'s `stableId` and the `filtered` selected-promotion logic.
- const selectedRowId = useMemo<string | null>(() => {
- if (!selectedEntry) {
- return null
- }
- return rowDomId(selectedEntry)
- }, [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 }))
}, [])
@@ -386,19 +375,13 @@ export function MenuFilterCombobox({
// mixed scope left here is `all`.
const fitsScope = scope === 'all' || scope === selectedEntry.group.type
if (fitsScope) {
- // Stringify both sides so a synthetic `selected` shimmed in
- // by callers like `TaxonomicPopoverMenu` (where the value
- // arrives as e.g. `'5'`) dedups against the real entry
- // returned by the endpoint (`cohort.id === 5`). Without this
- // coercion the two land side-by-side with two checkmarks —
- // the stableId path below already coerces, so matching here
- // keeps the prepend logic aligned with how rows are keyed.
- const selectedValue = String(selectedEntry.group.getValue?.(selectedEntry.item) ?? selectedEntry.name)
- const present = merged.some(
- (e) =>
- e.group.type === selectedEntry.group.type &&
- String(e.group.getValue?.(e.item) ?? e.name) === selectedValue
- )
+ // `entryMatchesSelection` reconciles a synthetic `selected`
+ // shimmed in by callers like `TaxonomicPopoverMenu` against the
+ // real endpoint row — by value (`cohort.id === 5` vs `'5'`) or
+ // by friendly label (a value of `Pageview` vs the real
+ // `$pageview` row). Only prepend the placeholder when the real
+ // row genuinely isn't loaded (paginated past it).
+ const present = merged.some((e) => entryMatchesSelection(e, selectedEntry))
if (!present) {
merged.unshift(selectedEntry)
}
@@ -424,6 +407,57 @@ export function MenuFilterCombobox({
surveyQuestionLabels,
])
+ // Stable DOM id for the selected row — drives `Row`'s checkmark, the
+ // scroll-into-view below, and the `filtered` idle-promotion. Resolve the
+ // committed selection to the real loaded row when one matches (the stored
+ // value may be a friendly label, not the row's raw value), so all three
+ // land on the canonical row rather than a synthetic placeholder. Falls back
+ // to the selection itself when the real row hasn't loaded (paginated past).
+ const selectedRowId = useMemo<string | null>(() => {
+ if (!selectedEntry) {
+ return null
+ }
+ // Prefer an exact value match over the label heuristic so a custom event
+ // sharing a core event's friendly label can't steal the selection.
+ const real =
+ indexed.find((e) => entryValueMatchesSelection(e, selectedEntry)) ??
+ indexed.find((e) => entryLabelMatchesSelection(e, selectedEntry))
+ return rowDomId(real ?? selectedEntry)
+ }, [indexed, selectedEntry])
+
+ // Scroll the selected row into view after the list mounts. Polls a few
+ // animation frames because rows render after the underlying group's
+ // items resolve (remote endpoints), so the element won't exist on the
+ // first paint. Stops as soon as the node appears or after ~10 frames.
+ useEffect(() => {
+ if (!selectedRowId) {
+ return
+ }
+ let cancelled = false
+ let attempts = 0
+ const tick = (): void => {
+ if (cancelled) {
+ return
+ }
+ const el = document.getElementById(selectedRowId)
+ if (el) {
+ // `center` keeps a comfortable buffer above + below the
+ // selected row so it never lands flush against the edge
+ // of the scroll viewport (where the scroll-to button or
+ // the scrollbar fade can obscure it).
+ el.scrollIntoView({ block: 'center' })
+ return
+ }
+ if (attempts++ < 10) {
+ requestAnimationFrame(tick)
+ }
+ }
+ tick()
+ return () => {
+ cancelled = true
+ }
+ }, [selectedRowId])
+
// Recents + pinned that lead the default "All" surface (fixed order:
// recents, then pinned). Idle shows the top-3 of each; searching shows the
// query matches. Computed outside `filtered` so the endpoint-passthrough