:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(taxonomic-filter): promote committed selection to top of legacy lists (#69597)
Paul D'Ambra453e4fa49ca9
diff --git a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsxindex 71912bb3809f..ffc91de972f9 100644--- a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx@@ -464,7 +464,10 @@ export const InfiniteListRow = ({const normalizedValue = typeof itemValue === 'number' && typeof value === 'string' ? Number(value) : value- const isSelected = listGroupType === groupType && itemValue === normalizedValue+ // On the aggregated Suggested filters tab, a row's own group (via `itemGroup`) is the+ // source group it was promoted from, not `listGroupType` — compare against that so a+ // cross-group promoted row still gets the selected treatment.+ const isSelected = (itemGroup?.type ?? listGroupType) === groupType && itemValue === normalizedValueconst isHighlighted = rowIndex === highlightedIndex && isActiveTabdiff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.tsindex 1c14002973ae..f6ab5c16d1b3 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts@@ -1176,6 +1176,163 @@ describe('infiniteListLogic', () => {)})+ describe('committed selection promotion', () => {+ beforeEach(() => {+ localStorage.clear()+ })++ afterEach(() => {+ localStorage.clear()+ })++ const mountSuggestedList = (props: Record<string, any>): ReturnType<typeof infiniteListLogic.build> =>+ logicWith({+ listGroupType: TaxonomicFilterGroupType.SuggestedFilters,+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.SuggestedFilters],+ ...props,+ })++ it('floats the selected value above the group list when idle, without displacing a leading catch-all row', async () => {+ logic = logicWith({ value: 'search term', groupType: TaxonomicFilterGroupType.Events })+ await expectLogic(logic).toDispatchActions(['loadRemoteItemsSuccess'])+ expect((logic.values.results[0] as { name?: string })?.name).toBe('All events')+ expect((logic.values.results[1] as { name?: string })?.name).toBe('search term')+ })++ it('statically inserts the committed selection while its row is not yet loaded', async () => {+ logic = logicWith({ value: 'zzz custom event', groupType: TaxonomicFilterGroupType.Events })+ await expectLogic(logic).toDispatchActions(['loadRemoteItemsSuccess'])+ expect((logic.values.results[0] as { name?: string })?.name).toBe('All events')+ expect(logic.values.results[1]).toMatchObject({+ name: 'zzz custom event',+ group: TaxonomicFilterGroupType.Events,+ })+ // the synthetic is counted so the windowed loader's row math stays consistent:+ // 1 local ("All events") + 156 remote + 1 synthetic+ expect(logic.values.items.count).toBe(158)+ })++ it('hands off from the synthetic row to the real row once its page loads, without duplicating it', async () => {+ // 'misc-150-generated' sits past the first page (100 rows) of the 156-row mock list+ logic = logicWith({ value: 'misc-150-generated', groupType: TaxonomicFilterGroupType.Events })+ await expectLogic(logic).toDispatchActions(['loadRemoteItemsSuccess'])+ expect(logic.values.results[1]).toMatchObject({+ name: 'misc-150-generated',+ group: TaxonomicFilterGroupType.Events,+ })++ // scrolling to the hole after the loaded page must fetch the true remote offset+ // (display index minus local rows minus the synthetic), completing the list+ await expectLogic(logic, () =>+ logic.actions.onRowsRendered({ startIndex: 90, stopIndex: 110, overscanStopIndex: 130 })+ ).toDispatchActions(['loadRemoteItems', 'loadRemoteItemsSuccess'])++ const results = logic.values.results+ expect(logic.values.items.count).toBe(157)+ expect(results).toHaveLength(157)+ expect(results.every((item) => item != null)).toBe(true)+ // the real row (it has an id; the synthetic doesn't) floats, the synthetic is gone+ expect(results[1]).toMatchObject({ name: 'misc-150-generated', id: 'uuid-150-foobar' })+ expect(results.filter((item) => (item as { name?: string })?.name === 'misc-150-generated')).toHaveLength(1)+ })++ it('leaves relevance ordering alone while searching', async () => {+ logic = logicWith({ value: 'other event', groupType: TaxonomicFilterGroupType.Events })+ await expectLogic(logic).toDispatchActions(['loadRemoteItemsSuccess'])+ await expectLogic(logic, () => logic.actions.setSearchQuery('event')).toDispatchActions([+ 'loadRemoteItemsSuccess',+ ])+ const names = logic.values.results.map((item) => (item as { name?: string })?.name)+ expect(names).toContain('other event')+ expect(names.indexOf('other event')).toBeGreaterThan(0)+ })++ it('floats a matching recent to the top of the suggested list without duplicating it', async () => {+ const recentLogic = recentTaxonomicFiltersLogic.build()+ recentLogic.mount()+ recentLogic.actions.recordRecentFilter({+ groupType: TaxonomicFilterGroupType.Events,+ groupName: 'Events',+ value: 'event1',+ item: { name: 'event1' },+ })+ recentLogic.actions.recordRecentFilter({+ groupType: TaxonomicFilterGroupType.Events,+ groupName: 'Events',+ value: 'test event',+ item: { name: 'test event' },+ })++ const listLogic = mountSuggestedList({ value: 'event1', groupType: TaxonomicFilterGroupType.Events })+ await expectLogic(listLogic).toFinishAllListeners()++ const results = listLogic.values.results+ expect(hasRecentContext(results[0]) && results[0]._recentContext.sourceValue).toBe('event1')+ expect(results.filter((item) => (item as { name?: string })?.name === 'event1')).toHaveLength(1)+ })++ it.each([+ {+ description: 'default events group',+ taxonomicGroupTypes: undefined,+ value: '$pageview',+ groupType: TaxonomicFilterGroupType.Events,+ },+ {+ description: 'name-keyed property group, so the round-trip guard still passes',+ taxonomicGroupTypes: [+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.SuggestedFilters,+ ],+ value: '$browser',+ groupType: TaxonomicFilterGroupType.EventProperties,+ },+ ])(+ 'prepends a synthetic selected row keyed by the raw value when the selection is not visible ($description)',+ async ({ taxonomicGroupTypes, value, groupType }) => {+ const listLogic = mountSuggestedList(+ taxonomicGroupTypes ? { taxonomicGroupTypes, value, groupType } : { value, groupType }+ )+ await expectLogic(listLogic).toFinishAllListeners()+ expect(listLogic.values.results[0]).toMatchObject({ name: String(value), group: groupType })+ }+ )++ it('skips the synthetic row for id-keyed groups where only the raw id could render', async () => {+ const listLogic = mountSuggestedList({+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Cohorts, TaxonomicFilterGroupType.SuggestedFilters],+ value: 5,+ groupType: TaxonomicFilterGroupType.Cohorts,+ })+ await expectLogic(listLogic).toFinishAllListeners()+ expect(listLogic.values.results).toEqual([])+ })++ it('does not synthesize a row when groupType is the meta Suggested filters group itself', async () => {+ // Callers like ActionFilterRow open the popover with `groupType={SuggestedFilters}`+ // while `value` is the real committed event/action — that meta type must never be+ // treated as the selection's source group, or the synthetic row round-trips through+ // the wrong group and `onChange` can't map it back to a real entity type.+ const listLogic = mountSuggestedList({+ value: 'some_event',+ groupType: TaxonomicFilterGroupType.SuggestedFilters,+ })+ await expectLogic(listLogic).toFinishAllListeners()+ expect(listLogic.values.results.some((item) => (item as { name?: string })?.name === 'some_event')).toBe(+ false+ )+ })++ it('does not synthesize a blank row for an empty-string selection', async () => {+ // '' round-trips through `getValue` for name/value-keyed groups, so without the+ // empty-string guard a blank, clickable synthetic row would land at row 0 and+ // re-commit '' on click.+ const listLogic = mountSuggestedList({ value: '', groupType: TaxonomicFilterGroupType.Events })+ await expectLogic(listLogic).toFinishAllListeners()+ expect(listLogic.values.results.some((item) => (item as { value?: unknown })?.value === '')).toBe(false)+ })+ })+describe('contextFilteredRecentItems', () => {// Generic wrapper around hasRecentContext so .filter() preserves the input type// (the production type guard uses `unknown` which TS can't narrow through Array.filter).diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.tsindex 1d46b55b9186..52e0c9d5a70e 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts@@ -30,6 +30,7 @@ import {TaxonomicDefinitionTypes,TaxonomicFilterGroup,TaxonomicFilterGroupType,+ TaxonomicFilterValue,} from 'lib/components/TaxonomicFilter/types'import {buildUrlContainsShortcut,@@ -42,6 +43,7 @@ import {pinnedSourceKey,recentSourceKey,} from 'lib/components/TaxonomicFilter/utils/floatRecentPinned'+import { floatToFront } from 'lib/components/TaxonomicFilter/utils/floatToFront'import { promoteMatchingProperties } from 'lib/components/TaxonomicFilter/utils/promoteProperties'import { FEATURE_FLAGS } from 'lib/constants'import { createFuse } from 'lib/utils/fuseSearch'@@ -120,6 +122,14 @@ export interface RowInfo {*/export const NO_ITEM_SELECTED = -1+// Data-warehouse tabs keep their own committed-selection affordance (the pinned,+// auto-expanded row via `getInitialPinnedRowIndex`), so they are excluded from+// the generic selection-promotion below.+const DATA_WAREHOUSE_GROUP_TYPES: TaxonomicFilterGroupType[] = [+ TaxonomicFilterGroupType.DataWarehouse,+ TaxonomicFilterGroupType.DataWarehouseSourceTables,+]+export function getInitialPinnedRowIndex({results,taxonomicGroups,@@ -137,15 +147,11 @@ export function getInitialPinnedRowIndex({value: string | number | null | undefinedisActiveTab: boolean}): number | null {- const dataWarehouseGroupTypes: TaxonomicFilterGroupType[] = [- TaxonomicFilterGroupType.DataWarehouse,- TaxonomicFilterGroupType.DataWarehouseSourceTables,- ]if (!isActiveTab ||- !dataWarehouseGroupTypes.includes(listGroupType) ||+ !DATA_WAREHOUSE_GROUP_TYPES.includes(listGroupType) ||groupType === undefined ||- !dataWarehouseGroupTypes.includes(groupType) ||+ !DATA_WAREHOUSE_GROUP_TYPES.includes(groupType) ||value == null) {return null@@ -987,6 +993,22 @@ export const infiniteListLogic = kea<infiniteListLogicType>([})},],+ // The list's own group plus the committed selection, bundled into one input so+ // `items` stays within kea's 16-entry `SelectorTuple` cap (every extra input on+ // `items` also lengthens typegen for downstream logics, per the note on+ // `dedupedTopMatches`).+ selectionPromotionContext: [+ (s) => [s.group, s.groupType, s.value],+ (+ group,+ groupType,+ value+ ): {+ group: TaxonomicFilterGroup | undefined+ groupType: TaxonomicFilterGroupType | undefined+ value: TaxonomicFilterValue | undefined+ } => ({ group, groupType, value }),+ ],items: [(s) => [s.remoteItems,@@ -1002,6 +1024,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([s.isSoleSubstantiveGroup,s.soleGroupHasGetValue,s.taxonomicGroups,+ s.selectionPromotionContext,(_, props: InfiniteListLogicProps) => props.collapseUrlsToContainsRow,],(@@ -1018,8 +1041,10 @@ export const infiniteListLogic = kea<infiniteListLogicType>([isSoleSubstantiveGroup,soleGroupHasGetValue,taxonomicGroups,+ selectionPromotionContext,collapseUrlsToContainsRow) => {+ const { group, groupType, value } = selectionPromotionContext// Collapse URL groups to a single "URL contains <query>" shortcut row// (mirrors the rebuild menu's `COLLAPSED_TO_CONTAINS_ROW`). Only once// the remote fetch for the *current* query has returned at least one@@ -1034,6 +1059,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([const results = hasMatch ? [buildUrlContainsShortcut(trimmed, listGroupType)] : []return {results,+ syntheticSelectedCount: 0,count: results.length,searchQuery: remoteItems.searchQuery,queryChanged: remoteItems.queryChanged,@@ -1100,6 +1126,117 @@ export const infiniteListLogic = kea<infiniteListLogicType>([} else {orderedBase = combinedResults}+ // Mirrors the rebuild menu's Combobox idle promotion: with no search query,+ // the committed selection leads the list so the user can see at a glance+ // what is currently picked — floated in place when the real row is loaded,+ // otherwise statically inserted as a synthetic row (the selection is known+ // at open; there's no need to wait for the loader). A leading null-valued+ // catch-all row (e.g. "All events") keeps its place, per the invariant in+ // floatRecentPinned.ts — so the selection targets index 1 when one is+ // present. While searching, relevance wins.+ let syntheticSelectedCount = 0+ if (+ !searchQuery &&+ value != null &&+ // An empty string is not a real committed selection: it round-trips through+ // `getValue` for name/value-keyed groups and would otherwise float a blank,+ // clickable synthetic row that re-commits `''` on click. `0`/`false` are kept.+ value !== '' &&+ groupType &&+ !META_GROUP_TYPES.has(groupType) &&+ !DATA_WAREHOUSE_GROUP_TYPES.includes(groupType)+ ) {+ const selectionKey = groupItemKey(groupType, value)+ // A leading catch-all row (e.g. "All events") is a real, non-recent/pinned+ // group option whose `getValue` resolves to `null` — not merely a recent/+ // pinned row whose stripped shape happens to leave `getValue` undefined.+ const leadingItem = orderedBase[0]+ const leadingCatchAllOffset =+ leadingItem != null &&+ !isSkeletonItem(leadingItem) &&+ !hasRecentContext(leadingItem) &&+ !hasPinnedContext(leadingItem) &&+ getItemGroup(leadingItem, taxonomicGroups, group)?.getValue?.(leadingItem) === null+ ? 1+ : 0+ // The synthetic stand-in for a selection whose real row isn't loaded —+ // shaped like a top match, so `getItemGroup` resolves its source group.+ // Only usable when the source group round-trips it back to the committed+ // value: id-keyed groups (actions, cohorts) read `.id`, which the+ // `{ name, value, group }` shape lacks, so `getValue` returns `undefined`+ // and the round-trip fails — keeping their raw ids out of the list, which+ // is the intent. `name` stays the raw key, matching how real rows in+ // name/value-keyed groups are shaped: it round-trips through `getValue`,+ // and consumers that persist `item.name` verbatim don't get a friendly+ // label baked in. Renderers already prettify raw keys at render time.+ const sourceGroup = taxonomicGroups.find((g: TaxonomicFilterGroup) => g.type === groupType)+ const synthetic = {+ name: String(value),+ value,+ group: groupType,+ } as unknown as TaxonomicDefinitionTypes+ const syntheticRoundTrips = sourceGroup?.getValue?.(synthetic) === value+ const insertSynthetic = (list: typeof orderedBase): typeof orderedBase =>+ leadingCatchAllOffset > 0 ? [list[0], synthetic, ...list.slice(1)] : [synthetic, ...list]+ if (isSuggested) {+ // The aggregated list is fully client-side (recents/pinned prefixes),+ // so both floating and prepending are safe here.+ const selectedIndex = orderedBase.findIndex((item) => {+ if (item == null || isSkeletonItem(item)) {+ return false+ }+ if (recentSourceKey(item) === selectionKey || pinnedSourceKey(item) === selectionKey) {+ return true+ }+ const itemGroup = getItemGroup(item, taxonomicGroups, group)+ return (+ groupItemKey(itemGroup?.type ?? listGroupType, itemGroup?.getValue?.(item) ?? null) ===+ selectionKey+ )+ })+ if (selectedIndex >= 0) {+ orderedBase = floatToFront(orderedBase, selectedIndex, leadingCatchAllOffset)+ } else if (syntheticRoundTrips) {+ orderedBase = insertSynthetic(orderedBase)+ syntheticSelectedCount = 1+ }+ } else if (groupType === listGroupType && group?.getValue) {+ const getValue = group.getValue+ const selectedIndex = orderedBase.findIndex(+ (item) => item != null && !isSkeletonItem(item) && getValue(item) === value+ )+ if (selectedIndex === -1) {+ // The selection isn't among the loaded rows (first page still in+ // flight, or paginated past it) — insert the synthetic stand-in+ // rather than waiting for the loader. Once the page carrying the+ // real row lands, the `findIndex` above starts matching, the+ // synthetic drops out, and the float below takes over: the loaded+ // copy is the dedupe. The loader's display-index -> remote-offset+ // mapping stays exact because `onRowsRendered` subtracts+ // `syntheticSelectedCount` alongside `localItems.count`.+ if (syntheticRoundTrips) {+ orderedBase = insertSynthetic(orderedBase)+ syntheticSelectedCount = 1+ }+ } else {+ // Floating shifts every row above the selection down by one, so it+ // is only safe when those rows are all loaded — a hole changing+ // display position would desync the windowed loader's+ // display-index -> remote-offset mapping.+ const rowsAboveSelectionLoaded = (): boolean => {+ for (let i = 0; i < selectedIndex; i++) {+ if (orderedBase[i] == null || isSkeletonItem(orderedBase[i])) {+ return false+ }+ }+ return true+ }+ if (selectedIndex > leadingCatchAllOffset && rowsAboveSelectionLoaded()) {+ orderedBase = floatToFront(orderedBase, selectedIndex, leadingCatchAllOffset)+ }+ }+ }+ }// The "URL contains <query>" shortcut leads the aggregated SuggestedFilters list —// ahead of recents/pinned/top-matches — so a URL search surfaces the contains// suggestion first. Everything else keeps its existing order.@@ -1107,7 +1244,9 @@ export const infiniteListLogic = kea<infiniteListLogicType>([const orderedResults = shortcutItems.length ? [...shortcutItems, ...otherItems] : orderedBasereturn {results: orderedResults,+ syntheticSelectedCount,count:+ syntheticSelectedCount +keywordShortcutItems.length +recentPrefix.length +pinnedPrefix.length +@@ -1211,7 +1350,11 @@ export const infiniteListLogic = kea<infiniteListLogicType>([}}if (loadFrom !== null) {- const offset = (loadFrom || startIndex) - values.localItems.count+ // The synthetic selected row (when present) sits before the remote block,+ // so it shifts every remote row's display index by one — subtract it along+ // with the local rows to recover the true remote offset.+ const offset =+ (loadFrom || startIndex) - values.localItems.count - (values.items.syntheticSelectedCount ?? 0)actions.loadRemoteItems({ offset, limit: values.limit })}}diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsxindex 797fcab346bd..9b6f75abed12 100644--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx@@ -54,6 +54,7 @@ import {partitionContainsShortcuts,urlContainsRowLabel,} from '../utils/collapsedContainsRow'+import { floatToFront } from '../utils/floatToFront'import { promoteMatchingBy } from '../utils/promoteProperties'import { MenuFilterHeader } from './Header'import { MatchedValueBadge } from './MatchedValueBadge'@@ -153,15 +154,6 @@ function entryMatchesSelection(entry: MenuFilterEntry, selected: MenuFilterEntryreturn entryValueMatchesSelection(entry, selected) || entryLabelMatchesSelection(entry, selected)}-/** Move the element at `index` to the front, preserving the order of the rest.- * No-op when `index <= 0` (already first, or not found via `findIndex` -> -1). */-function floatToFront<T>(list: T[], index: number): T[] {- if (index <= 0) {- return list- }- return [list[index], ...list.slice(0, index), ...list.slice(index + 1)]-}-function fuseMatchEntries(entries: MenuFilterEntry[], query: string): MenuFilterEntry[] {if (entries.length === 0) {return []diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/floatToFront.ts b/frontend/src/lib/components/TaxonomicFilter/utils/floatToFront.tsnew file mode 100644index 000000000000..5180624276e2--- /dev/null+++ b/frontend/src/lib/components/TaxonomicFilter/utils/floatToFront.ts@@ -0,0 +1,11 @@+/** Move the element at `index` to `offset` (0 by default, or 1 to preserve a leading+ * catch-all row), preserving the order of everything else.+ * No-op when `index <= offset` (already in place, or not found via `findIndex` -> -1).+ * Shared by the rebuild menu's `Combobox` and the legacy `infiniteListLogic`+ * for the committed-selection promotion; callers choose the offset per surface. */+export function floatToFront<T>(list: T[], index: number, offset = 0): T[] {+ if (index <= offset) {+ return list+ }+ return [...list.slice(0, offset), list[index], ...list.slice(offset, index), ...list.slice(index + 1)]+}