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(taxonomic-filter): recents-first default surface in the rebuild (#61636)

Paul D'Ambra3ff1cecde940
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 9472a724f113..d89efe6119ac 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2036,18 +2036,6 @@ 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.7ee4e2e398582c0a43df30fc5738a25f1f678890451f84355cf1805b752e4e9c.Ogf0s8VYncQihGnhKcrpJ9PMNPJLuVHePrtF9vPnwr8
- filters-taxonomic-filter-headless--events-and-actions--light:
- hash: v1.k794b7964.ce3a0d38f4b056cfc367ad8d4ab31ddaa09ed6a693172e2358ad1b7a5c02a6a0.JjZmgPTyGsUU421vtc0Baxzi_hyU9JsYKenH9X1dW9U
- filters-taxonomic-filter-headless--properties--dark:
- hash: v1.k794b7964.4ee695e5751c6f73e9742ab0cfeecf61b5adfe829cf3a0d49ab2877cae8b212f.jPN9l5TDgLRy9NzHenXHCU903UDg8-GdeGpf4PXt7aA
- filters-taxonomic-filter-headless--properties--light:
- hash: v1.k794b7964.bd715b36b456df8730e934366a35faed4556dffa881456db1272e2804047a036.IH74-bf3miZ6nC3E0bqbzIb0km4fBh97_2XubTpcmns
- filters-taxonomic-filter-headless--suggested-filters-with-recents--dark:
- hash: v1.k794b7964.bde87b20067d3a4ab3089ea62acfd9095b3be42275f60a37b5c50fff74cea6a7.wXHAM_8ewbUHxsuzWBDuotzkgYbpE0a0fJ64zGDlAqk
- filters-taxonomic-filter-headless--suggested-filters-with-recents--light:
- hash: v1.k794b7964.9e94f0bc20ace724f4984c77cc1c1ef818b64f708ab972b8bc2e0afcbc2bc8a0.d4EvG3smS4PHr1VMeIS3JNPMEu5tDCJXbVJhb7rnzeU
filters-taxonomic-filter-menu-rebuild--data-warehouse-config--dark:
hash: v1.k794b7964.c09183f21589b0f11a3013a6e359d23c8d5b17b1e6ed61476ba45da75bcdc73f.tzexSMIoGf0LgGmzdG3-O0g7vd9Isx6MRQ_TWltg4Fo
filters-taxonomic-filter-menu-rebuild--data-warehouse-config--light:
diff --git a/frontend/src/lib/components/TaxonomicFilter/headless/TaxonomicFilterHeadless.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/headless/TaxonomicFilterHeadless.stories.tsx
deleted file mode 100644
index 0b5b5dd34cfc..000000000000
--- a/frontend/src/lib/components/TaxonomicFilter/headless/TaxonomicFilterHeadless.stories.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-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 { __clearTaxonomicResourceCache } from '../hooks/useTaxonomicResource'
-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_MENU_REBUILD` 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 {
- useState(() => {
- __clearTaxonomicResourceCache()
- return null
- })
- 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/hooks/useTaxonomicFilter.test.tsx b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx
index 4f1d71776f62..3529841f3fe8 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.test.tsx
@@ -38,7 +38,7 @@ describe('useTaxonomicFilter', () => {
afterEach(() => cleanup())
- it('exposes groups in the consumer-requested order, with Recent + Pinned auto-injected', () => {
+ it('exposes groups in the consumer-requested order, with Recent/Pinned auto-injected', () => {
const { result } = renderHook(
() =>
useTaxonomicFilter({
@@ -50,8 +50,7 @@ describe('useTaxonomicFilter', () => {
}),
{ wrapper }
)
- // Recent + Pinned auto-inject at the start (no other meta groups
- // requested, so they go in at index 0).
+ // Recent + Pinned auto-inject at the start; SuggestedFilters is NOT auto-injected.
expect(result.current.groupTypes).toEqual([
TaxonomicFilterGroupType.RecentFilters,
TaxonomicFilterGroupType.PinnedFilters,
@@ -62,6 +61,50 @@ describe('useTaxonomicFilter', () => {
expect(result.current.groups.map((g) => g.type)).toEqual(result.current.groupTypes)
})
+ it.each([
+ {
+ name: 'never auto-injects SuggestedFilters for a multi-content picker',
+ requested: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.PersonProperties],
+ },
+ {
+ name: 'never auto-injects SuggestedFilters for a single content group',
+ requested: [TaxonomicFilterGroupType.Events],
+ },
+ {
+ name: 'never auto-injects SuggestedFilters for a meta-only picker',
+ requested: [TaxonomicFilterGroupType.HogQLExpression],
+ },
+ {
+ name: 'never auto-injects SuggestedFilters when a mutually-exclusive pair collapses',
+ requested: [TaxonomicFilterGroupType.PageviewUrls, TaxonomicFilterGroupType.PageviewEvents],
+ },
+ ])('$name', ({ requested }) => {
+ const { result } = renderHook(() => useTaxonomicFilter({ taxonomicGroupTypes: requested }), { wrapper })
+ expect(result.current.groupTypes).not.toContain(TaxonomicFilterGroupType.SuggestedFilters)
+ })
+
+ it('initial groupType prop is respected', () => {
+ const { result } = renderHook(
+ () =>
+ useTaxonomicFilter({
+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.PersonProperties],
+ groupType: TaxonomicFilterGroupType.Events,
+ }),
+ { wrapper }
+ )
+ expect(result.current.groupTypes).not.toContain(TaxonomicFilterGroupType.SuggestedFilters)
+ expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Events)
+ })
+
+ it('defaults to the first non-meta group when SuggestedFilters is not present', () => {
+ const { result } = renderHook(
+ () => useTaxonomicFilter({ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events] }),
+ { wrapper }
+ )
+ expect(result.current.groupTypes).not.toContain(TaxonomicFilterGroupType.SuggestedFilters)
+ expect(result.current.activeGroupType).toBe(TaxonomicFilterGroupType.Events)
+ })
+
it('defaults activeGroupType to props.groupType when valid', () => {
const { result } = renderHook(
() =>
@@ -291,7 +334,7 @@ describe('useTaxonomicFilter', () => {
expect(onChange).toHaveBeenCalledWith(eventsGroup, 'pageview', fakeItem)
})
- it('searchPlaceholder composes label fragments from groups (incl. auto-injected Recent + Pinned)', () => {
+ it('searchPlaceholder composes label fragments from content groups only (Recent + Pinned excluded)', () => {
const { result } = renderHook(
() =>
useTaxonomicFilter({
diff --git a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
index 131931ca549f..ac1888dfcadd 100644
--- a/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/hooks/useTaxonomicFilter.ts
@@ -161,8 +161,7 @@ function indexAfterLastMetaGroup(filtered: TaxonomicFilterGroupType[]): number {
* 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)
+ * 3. Auto-injecting Recent/Pinned meta tabs when available.
* 4. Promoting shortcut groups (PageviewUrls / Screens / EmailAddresses
* / Elements when `$autocapture` is in `eventNames`) to right after
* the meta block.
@@ -197,7 +196,7 @@ function resolveTaxonomicGroupTypes(
}
const filtered = requested.filter((t) => !excluded.has(t) && available.has(t))
- // 2. Auto-inject Recent / Pinned (Suggested stays opt-in)
+ // 2. Auto-inject Recent/Pinned meta tabs when available and not already present.
for (const metaType of AUTO_INJECT_META_GROUPS) {
if (available.has(metaType) && !filtered.includes(metaType)) {
filtered.splice(indexAfterLastMetaGroup(filtered), 0, metaType)
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
index 9431e4f4c8aa..edd5e09c2cb7 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.test.tsx
@@ -1,6 +1,7 @@
import '@testing-library/jest-dom'
import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { Provider } from 'kea'
import { useState } from 'react'
@@ -52,7 +53,46 @@ function renderCombobox(): ReturnType<typeof render> {
)
}
-describe('MenuFilterCombobox loading vs empty state', () => {
+function makeEntry(groupType: TaxonomicFilterGroupType, name: string, groupName: string): any {
+ return {
+ item: { name },
+ group: { type: groupType, name: groupName, getName: (t: any) => t?.name, getValue: (t: any) => t?.name },
+ name,
+ }
+}
+
+function renderAll(options: {
+ groupTypes: TaxonomicFilterGroupType[]
+ recentEntries?: any[]
+ pinnedEntries?: any[]
+ searchQuery?: string
+}): ReturnType<typeof render> {
+ return render(
+ <Provider>
+ <TaxonomicFilterHeadless.Root
+ taxonomicGroupTypes={options.groupTypes}
+ onChange={jest.fn()}
+ searchQuery={options.searchQuery ?? ''}
+ >
+ <MenuFilterCombobox
+ drillTo="all"
+ recentEntries={options.recentEntries}
+ pinnedEntries={options.pinnedEntries}
+ onCommit={jest.fn()}
+ onBack={jest.fn()}
+ />
+ </TaxonomicFilterHeadless.Root>
+ </Provider>
+ )
+}
+
+function rowTexts(): string[] {
+ return Array.from(document.querySelectorAll('[data-slot="taxonomic-filter-menu-row"]')).map(
+ (el) => el.textContent ?? ''
+ )
+}
+
+describe('MenuFilterCombobox', () => {
beforeEach(() => {
__clearTaxonomicResourceCache()
apiGet.mockReset()
@@ -231,4 +271,134 @@ describe('MenuFilterCombobox loading vs empty state', () => {
// The crucial assertion — no additional fetch fired for the typed query.
expect(cohortCalls).toBe(1)
})
+
+ it('leads the "All" surface with recents then pinned, above the content rows', async () => {
+ apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.EventProperties],
+ recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'my_recent_event', 'Events')],
+ pinnedEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, 'my_pinned_prop', 'Event properties')],
+ })
+
+ await waitFor(() => expect(rowTexts().some((t) => t.includes('autocapture'))).toBe(true))
+ const rows = rowTexts()
+ // Fixed, learnable order: recent first, pinned second, content after.
+ expect(rows[0]).toContain('my_recent_event')
+ expect(rows[1]).toContain('my_pinned_prop')
+ const recentIdx = rows.findIndex((t) => t.includes('my_recent_event'))
+ const contentIdx = rows.findIndex((t) => t.includes('autocapture'))
+ expect(contentIdx).toBeGreaterThan(recentIdx)
+ })
+
+ it('shows a recent that is also in the catalog only once (deduped from content)', async () => {
+ apiGet.mockResolvedValue({ results: [{ id: 1, name: 'pageview' }], count: 1 })
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events],
+ recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'pageview', 'Events')],
+ })
+
+ await waitFor(() => expect(screen.getAllByText('pageview').length).toBeGreaterThan(0))
+ const pageviewRows = rowTexts().filter((t) => t.includes('pageview'))
+ expect(pageviewRows).toHaveLength(1)
+ })
+
+ it('floats $email to the top of the content when searching "email"', async () => {
+ apiGet.mockImplementation((url: string) => {
+ if (url.includes('property_definitions')) {
+ return Promise.resolve({
+ results: [
+ { id: 1, name: 'other_prop' },
+ { id: 2, name: '$email' },
+ ],
+ count: 2,
+ })
+ }
+ return Promise.resolve({ results: [], count: 0 })
+ })
+
+ renderAll({ groupTypes: [TaxonomicFilterGroupType.EventProperties], searchQuery: 'email' })
+
+ await waitFor(() => expect(screen.getByText('other_prop')).toBeInTheDocument())
+ const rows = rowTexts()
+ const emailIdx = rows.findIndex((t) => t.includes('$email'))
+ const otherIdx = rows.findIndex((t) => t.includes('other_prop'))
+ expect(emailIdx).toBeGreaterThanOrEqual(0)
+ expect(emailIdx).toBeLessThan(otherIdx)
+ })
+
+ it('drops the recents/pinned prefix once the query no longer matches them', async () => {
+ apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events],
+ recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'my_recent_event', 'Events')],
+ searchQuery: 'zzz_no_match',
+ })
+
+ await waitFor(() => expect(screen.getAllByText('autocapture').length).toBeGreaterThan(0))
+ // The recent does not match the query, so it must not lead the list.
+ expect(screen.queryByText('my_recent_event')).not.toBeInTheDocument()
+ })
+
+ it('tags recents and pinned rows with their source recency', async () => {
+ apiGet.mockResolvedValue({ results: [{ id: 1, name: 'autocapture' }], count: 1 })
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events],
+ recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'my_recent_event', 'Events')],
+ pinnedEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, 'my_pinned_prop', 'Event properties')],
+ })
+
+ await waitFor(() => expect(rowTexts().some((t) => t.includes('autocapture'))).toBe(true))
+ const rows = rowTexts()
+ // Recency shows as a right-side badge ("Recent" / "Pinned"); the source
+ // group still reads as the row's category label.
+ const recentRow = rows.find((t) => t.includes('my_recent_event'))
+ const pinnedRow = rows.find((t) => t.includes('my_pinned_prop'))
+ expect(recentRow).toContain('Recent')
+ expect(recentRow).toContain('Events')
+ expect(pinnedRow).toContain('Pinned')
+ expect(pinnedRow).toContain('Event properties')
+ })
+
+ it('recent leads the list at row 0 even when content also matches the search query', async () => {
+ // Endpoint returns a row that matches the same query as the recent.
+ apiGet.mockImplementation((url: string) => {
+ if (url.includes('event_definitions') || url.includes('property_definitions')) {
+ return Promise.resolve({
+ results: [{ id: 1, name: 'signup' }],
+ count: 1,
+ })
+ }
+ return Promise.resolve({ results: [], count: 0 })
+ })
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events],
+ recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'signup', 'Events')],
+ searchQuery: 'signup',
+ })
+
+ await waitFor(() => expect(rowTexts().some((t) => t.includes('signup'))).toBe(true))
+ // The recent prefix must still be at index 0 — it leads even when
+ // the content list also matches the query.
+ expect(rowTexts()[0]).toContain('signup')
+ })
+
+ it('exposes Recent and Pinned as category options in the dropdown', async () => {
+ const user = userEvent.setup()
+ apiGet.mockResolvedValue({ results: [], count: 0 })
+
+ renderAll({
+ groupTypes: [TaxonomicFilterGroupType.Events],
+ recentEntries: [makeEntry(TaxonomicFilterGroupType.Events, 'r', 'Events')],
+ pinnedEntries: [makeEntry(TaxonomicFilterGroupType.EventProperties, 'p', 'Event properties')],
+ })
+
+ await user.click(screen.getByRole('combobox', { name: 'Filter category' }))
+ expect(await screen.findByRole('option', { name: 'Recent' })).toBeInTheDocument()
+ expect(screen.getByRole('option', { name: 'Pinned' })).toBeInTheDocument()
+ })
})
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
index 99fc94231ff2..6131a951aee1 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/Combobox.tsx
@@ -15,8 +15,9 @@ import { useValues } from 'kea'
import posthog from 'posthog-js'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { IconCheck, IconChevronRight } from '@posthog/icons'
+import { IconCheck, IconChevronRight, IconClock, IconPinFilled } from '@posthog/icons'
import {
+ Badge,
cn,
InputGroup,
InputGroupAddon,
@@ -41,6 +42,7 @@ import { getCoreFilterDefinition } from '~/taxonomy/helpers'
import { useTaxonomicFilterContext } from '../headless/context'
import { useGroupList } from '../hooks/useGroupList'
import { TaxonomicDefinitionTypes, TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'
+import { promoteMatchingBy } from '../utils/promoteProperties'
import { MenuFilterHeader } from './Header'
import { PreviewPane } from './PreviewPane'
import { CommitFn, DrillCategory, MenuFilterEntry } from './types'
@@ -62,25 +64,52 @@ const HIDDEN_FROM_CHIPS: ReadonlySet<TaxonomicFilterGroupType> = new Set([
// 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.
+ // recents/pinned now lead the "All" surface directly.
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.
+ // (Recent / Pinned entries with chevrons) and lead the "All" surface;
+ // DataWarehouse + HogQL expression have their own dedicated panels —
+ // none of them belong in the in-combobox chip row.
TaxonomicFilterGroupType.RecentFilters,
TaxonomicFilterGroupType.PinnedFilters,
TaxonomicFilterGroupType.DataWarehouse,
TaxonomicFilterGroupType.HogQLExpression,
])
+/** How many recents and pinned each lead the default "All" surface, matching
+ * the pill variant's top-3 face. */
+const RECENT_PINNED_PREFIX_LIMIT = 3
+
+/** 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)}`
+}
+
+/** 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)}`
+}
+
+function fuseMatchEntries(entries: MenuFilterEntry[], query: string): MenuFilterEntry[] {
+ if (entries.length === 0) {
+ return []
+ }
+ return createFuse(entries, FUSE_OPTIONS as Parameters<typeof createFuse<MenuFilterEntry>>[1])
+ .search(query)
+ .map((r) => r.item)
+}
+
export interface MenuFilterComboboxProps {
drillTo: DrillCategory
/** Pre-resolved entries for `drillTo='recent' | 'pinned'`. Skips fetching. */
drillItems?: MenuFilterEntry[]
- /** 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[]
+ /** Recents/pinned (each resolved to its source group). Lead the default
+ * "All" surface: top-3 of each when idle, query matches when searching. */
+ recentEntries?: MenuFilterEntry[]
+ pinnedEntries?: MenuFilterEntry[]
placeholder?: string
onCommit: CommitFn
onBack: () => void
@@ -93,7 +122,8 @@ export interface MenuFilterComboboxProps {
export function MenuFilterCombobox({
drillTo,
drillItems,
- suggestedItems,
+ recentEntries,
+ pinnedEntries,
placeholder,
onCommit,
onBack,
@@ -129,14 +159,13 @@ export function MenuFilterCombobox({
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.
+ // 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
}
- const value = selectedEntry.group.getValue?.(selectedEntry.item) ?? selectedEntry.name
- return `menu-filter-row-${selectedEntry.group.type}-${String(value)}`
+ return rowDomId(selectedEntry)
}, [selectedEntry])
// Scroll the selected row into view after the list mounts. Polls a few
@@ -187,16 +216,22 @@ export function MenuFilterCombobox({
// Ordered category list — drives the category dropdown and Tab cycling
// (kept in sync so the dropdown trigger reflects the active scope).
+ // Recent / Pinned lead the content categories (when present) so they're
+ // navigable from the combobox the way the pill variant's category column
+ // exposes them, not only via the outer dropdown menu.
const categoryOptions = useMemo<{ value: DrillCategory; label: string }[]>(() => {
const opts: { value: DrillCategory; label: string }[] = [{ value: 'all', label: 'All' }]
- if (suggestedItems && suggestedItems.length > 0) {
- opts.push({ value: 'suggested', label: 'Suggested' })
+ if (recentEntries && recentEntries.length > 0) {
+ opts.push({ value: 'recent', label: 'Recent' })
+ }
+ if (pinnedEntries && pinnedEntries.length > 0) {
+ opts.push({ value: 'pinned', label: 'Pinned' })
}
for (const g of visibleChipGroups) {
opts.push({ value: g.type, label: g.name })
}
return opts
- }, [suggestedItems, visibleChipGroups])
+ }, [recentEntries, pinnedEntries, visibleChipGroups])
// Resolve which groups feed the visible list, based on the active chip
// (or the drill scope when chips are hidden).
@@ -205,8 +240,8 @@ export function MenuFilterCombobox({
if (scope === 'all') {
return visibleChipGroups
}
- if (scope === 'recent' || scope === 'pinned' || scope === 'suggested') {
- return [] // items come from `drillItems` / `suggestedItems`
+ if (scope === 'recent' || scope === 'pinned') {
+ return [] // items come from `drillItems`
}
const g = groups.find((gr) => gr.type === scope)
return g ? [g] : []
@@ -221,16 +256,21 @@ export function MenuFilterCombobox({
const { surveyQuestionLabels } = useValues(surveyQuestionLabelsLogic)
// Indexed entries — flat list across all visible groups (or
- // pre-resolved `drillItems` for recent/pinned, or pre-merged
- // `suggestedItems` for the Suggested chip / drill).
+ // pre-resolved `drillItems` for recent/pinned).
const indexed = useMemo<MenuFilterEntry[]>(() => {
const scope = showChips ? activeChip : drillTo
- if (scope === 'suggested' && suggestedItems) {
- return suggestedItems
- }
if (drillItems) {
return drillItems
}
+ // Recent / Pinned scopes selected from the combobox dropdown read the
+ // pre-resolved entries directly (the outer menu drill passes the same
+ // lists via `drillItems`).
+ if (scope === 'recent') {
+ return recentEntries ?? []
+ }
+ if (scope === 'pinned') {
+ return pinnedEntries ?? []
+ }
const merged: MenuFilterEntry[] = []
for (const group of targetGroups) {
const items = itemsByType[group.type] ?? []
@@ -251,12 +291,9 @@ export function MenuFilterCombobox({
// 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'
+ // `recent`/`pinned` scopes already returned above, so the only
+ // mixed scope left here is `all`.
+ const fitsScope = scope === 'all' || scope === selectedEntry.group.type
if (fitsScope) {
// Stringify both sides so a synthetic `selected` shimmed in
// by callers like `TaxonomicPopoverMenu` (where the value
@@ -284,7 +321,8 @@ export function MenuFilterCombobox({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
drillItems,
- suggestedItems,
+ recentEntries,
+ pinnedEntries,
targetGroups,
itemsByType,
selectedEntry,
@@ -294,6 +332,44 @@ export function MenuFilterCombobox({
surveyQuestionLabels,
])
+ // Recents + pinned that lead the default "All" surface (fixed order:
+ // recents, then pinned). Idle shows the top-3 of each; searching shows the
+ // query matches. Computed outside `filtered` so the endpoint-passthrough
+ // there can't re-introduce a non-matching endpoint-backed recent.
+ const recentsPinnedPrefix = useMemo<MenuFilterEntry[]>(() => {
+ const scope = showChips ? activeChip : drillTo
+ if (scope !== 'all') {
+ return []
+ }
+ const recents = recentEntries ?? []
+ const pinned = pinnedEntries ?? []
+ const q = searchQuery.trim()
+ const recentSegment = q ? fuseMatchEntries(recents, q) : recents.slice(0, RECENT_PINNED_PREFIX_LIMIT)
+ const recentSegmentKeys = new Set(recentSegment.map(entryKey))
+ const pinnedPool = (q ? fuseMatchEntries(pinned, q) : pinned).filter((e) => !recentSegmentKeys.has(entryKey(e)))
+ const pinnedSegment = q ? pinnedPool : pinnedPool.slice(0, RECENT_PINNED_PREFIX_LIMIT)
+ return [...recentSegment, ...pinnedSegment]
+ }, [showChips, activeChip, drillTo, recentEntries, pinnedEntries, searchQuery])
+
+ // Recency lookup so any row that is one of the user's recents/pinned gets a
+ // "- recent" / "- pinned" tag on its category label, wherever it appears
+ // (matching the pill variant's per-row source tags).
+ const recentKeys = useMemo(() => new Set((recentEntries ?? []).map(entryKey)), [recentEntries])
+ const pinnedKeys = useMemo(() => new Set((pinnedEntries ?? []).map(entryKey)), [pinnedEntries])
+ const recencyForEntry = useCallback(
+ (entry: MenuFilterEntry): 'recent' | 'pinned' | null => {
+ const key = entryKey(entry)
+ if (recentKeys.has(key)) {
+ return 'recent'
+ }
+ if (pinnedKeys.has(key)) {
+ return 'pinned'
+ }
+ return null
+ },
+ [recentKeys, pinnedKeys]
+ )
+
const filtered = useMemo<MenuFilterEntry[]>(() => {
const q = searchQuery.trim()
let base: MenuFilterEntry[]
@@ -327,16 +403,25 @@ export function MenuFilterCombobox({
// 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
- )
+ const idx = base.findIndex((e) => rowDomId(e) === selectedRowId)
if (idx > 0) {
- return [base[idx], ...base.slice(0, idx), ...base.slice(idx + 1)]
+ base = [base[idx], ...base.slice(0, idx), ...base.slice(idx + 1)]
}
}
+ // Default "All" surface leads with recents/pinned (fixed order), then
+ // the cross-tab content with `email`/`url` promotion. Recents/pinned
+ // stay above the content rows so users can learn the order.
+ const scope = showChips ? activeChip : drillTo
+ if (scope === 'all') {
+ const prefixKeys = new Set(recentsPinnedPrefix.map(entryKey))
+ const content = prefixKeys.size > 0 ? base.filter((e) => !prefixKeys.has(entryKey(e))) : base
+ return [
+ ...recentsPinnedPrefix,
+ ...promoteMatchingBy(content, searchQuery, (e) => (e.item as { name?: string }).name ?? e.name),
+ ]
+ }
return base
- }, [indexed, searchQuery, selectedRowId])
+ }, [indexed, searchQuery, selectedRowId, recentsPinnedPrefix, showChips, activeChip, drillTo])
// Active-chip-aware placeholder. When the user has narrowed to a
// specific category, use that group's `searchPlaceholder` so the
@@ -346,7 +431,7 @@ export function MenuFilterCombobox({
if (activeChip === 'all') {
return placeholder ?? 'Search…'
}
- if (activeChip === 'recent' || activeChip === 'pinned' || activeChip === 'suggested') {
+ if (activeChip === 'recent' || activeChip === 'pinned') {
return placeholder ?? 'Search…'
}
const group = groups.find((g) => g.type === activeChip)
@@ -357,8 +442,8 @@ export function MenuFilterCombobox({
// True while any visible group is fetching its first page (or refetching
// with no kept-previous-data) — drives the skeleton fallback so the user
// doesn't see "No X found" before the request resolves. Drilled
- // scopes that read from pre-resolved `drillItems` / `suggestedItems`
- // never fetch and stay at `false`.
+ // scopes that read from pre-resolved `drillItems` never fetch and stay at
+ // `false`.
const isAnyLoading = useMemo(() => {
if (drillItems) {
return false
@@ -419,9 +504,7 @@ export function MenuFilterCombobox({
? 'Recent'
: drillTo === 'pinned'
? 'Pinned'
- : drillTo === 'suggested'
- ? 'Suggested'
- : (groups.find((g) => g.type === drillTo)?.name ?? 'Filter'))
+ : (groups.find((g) => g.type === drillTo)?.name ?? 'Filter'))
const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {
if (e.key === 'Escape') {
@@ -587,14 +670,21 @@ export function MenuFilterCombobox({
{(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).
+ // Show the category label on mixed-group views (All,
+ // Recent, Pinned) — those mix items from multiple
+ // categories so the label disambiguates. Drilled-to-
+ // one-group views skip it (the panel header / chip
+ // already names the category).
showCategory={
- activeChip === 'all' || drillTo === 'recent' || drillTo === 'pinned'
+ activeChip === 'all' ||
+ activeChip === 'recent' ||
+ activeChip === 'pinned' ||
+ drillTo === 'recent' ||
+ drillTo === 'pinned'
}
+ // Tag rows that are one of the user's recents/pinned so
+ // they read e.g. "Events - recent".
+ recency={recencyForEntry(entry)}
// DWH rows open the column-config
// form, not a final selection —
// signal that with a chevron.
@@ -622,6 +712,8 @@ interface RowProps {
entry: MenuFilterEntry
/** Render the category label (mixed-group views always; drilled views skip it since the panel header already names the group). */
showCategory: boolean
+ /** When the row is one of the user's recents/pinned, append the source tag (e.g. "Events - recent"). */
+ recency?: 'recent' | 'pinned' | null
/** Show a trailing chevron when click drills to another panel (DWH config). */
opensSubmenu?: boolean
/** DOM id of the currently-selected row (for the trailing checkmark). */
@@ -653,10 +745,9 @@ function resolveRowCells(entry: MenuFilterEntry): { name: string; value?: string
return { name: entry.name, category: entry.group.name }
}
-function Row({ entry, showCategory, opensSubmenu, selectedRowId, onCommit }: RowProps): JSX.Element {
- const { item, group } = entry
+function Row({ entry, showCategory, recency, opensSubmenu, selectedRowId, onCommit }: RowProps): JSX.Element {
const { name, value, category } = resolveRowCells(entry)
- const stableId = `menu-filter-row-${group.type}-${String(group.getValue?.(item) ?? entry.name)}`
+ const stableId = rowDomId(entry)
const isSelected = selectedRowId === stableId
return (
<Autocomplete.Item
@@ -695,6 +786,12 @@ function Row({ entry, showCategory, opensSubmenu, selectedRowId, onCommit }: Row
</span>
{showCategory && <MenuLabel className="text-tertiary/50 text-xxs p-0 mt-px">{category}</MenuLabel>}
</div>
+ {recency && (
+ <Badge variant="default" className="gap-1 shrink-0">
+ {recency === 'recent' ? <IconClock className="size-3" /> : <IconPinFilled className="size-3" />}
+ {recency === 'recent' ? 'Recent' : 'Pinned'}
+ </Badge>
+ )}
<VerificationBadge entry={entry} />
{isSelected && <IconCheck className="size-3.5 text-foreground shrink-0" />}
{opensSubmenu && <IconChevronRight className="size-3.5 text-tertiary shrink-0" />}
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx
index cc43d89c547a..4f2942adef16 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.stories.tsx
@@ -8,6 +8,7 @@ import { actionsModel } from '~/models/actionsModel'
import { TaxonomicFilterHeadless } from '../headless'
import { DataWarehousePopoverField, TaxonomicFilterGroup, TaxonomicFilterGroupType } from '../types'
+import { MenuFilterCombobox } from './Combobox'
import { MenuFilterDwhConfig } from './DwhFlow'
import { TaxonomicFilterMenu } from './TaxonomicFilterMenu'
import { MenuFilterEntry } from './types'
@@ -299,3 +300,68 @@ export const DataWarehouseConfig: Story = {
},
},
}
+
+// ---- Default "All" surface with recents/pinned --------------------------
+// Renders the combobox directly on the `all` scope so the recents-first
+// default surface is the initial snapshot (no click-through the dropdown
+// menu first). Recents/pinned are synthesized so the order is deterministic.
+
+function recentPinnedEntry(groupType: TaxonomicFilterGroupType, name: string, groupName: string): MenuFilterEntry {
+ return {
+ item: { name } as never,
+ group: {
+ type: groupType,
+ name: groupName,
+ getName: (t: any) => t?.name,
+ getValue: (t: any) => t?.name,
+ } as unknown as TaxonomicFilterGroup,
+ name,
+ }
+}
+
+function DefaultSurfaceContainer(): JSX.Element {
+ useMountedLogic(actionsModel)
+ const recentEntries = [
+ recentPinnedEntry(TaxonomicFilterGroupType.Events, 'signed up', 'Events'),
+ recentPinnedEntry(TaxonomicFilterGroupType.EventProperties, 'plan', 'Event properties'),
+ ]
+ const pinnedEntries = [recentPinnedEntry(TaxonomicFilterGroupType.EventProperties, 'industry', 'Event properties')]
+ return (
+ <div className="flex flex-col gap-3 max-w-2xl">
+ <TaxonomicFilterHeadless.Root
+ bindRootProps={false}
+ taxonomicGroupTypes={[
+ TaxonomicFilterGroupType.Events,
+ TaxonomicFilterGroupType.Actions,
+ TaxonomicFilterGroupType.EventProperties,
+ ]}
+ >
+ <div className="border rounded overflow-hidden flex flex-col w-[720px] h-[480px] bg-surface-primary">
+ <MenuFilterCombobox
+ drillTo="all"
+ recentEntries={recentEntries}
+ pinnedEntries={pinnedEntries}
+ onCommit={() => {}}
+ onBack={() => {}}
+ />
+ </div>
+ </TaxonomicFilterHeadless.Root>
+ </div>
+ )
+}
+
+export const DefaultSurfaceWithRecents: Story = {
+ // Excluded from the snapshot/flake gate: the combobox autofocuses, fetches
+ // content lists, and the preview pane loads definition metadata async, so
+ // the render isn't pixel-stable across runs. Kept for the Storybook demo;
+ // the recents-first behaviour is covered by RTL in Combobox.test.tsx.
+ tags: ['test-skip'],
+ render: () => <DefaultSurfaceContainer />,
+ parameters: {
+ docs: {
+ description: {
+ story: 'The default "All" surface staff land on, brought in line with the pill variant: recents lead, then pinned, then the cross-tab content in fixed (learnable) order. Recent/pinned rows are tagged with their source (e.g. "Events - recent"), and the category dropdown exposes Recent and Pinned alongside the content categories so they stay navigable.',
+ },
+ },
+ },
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx
index 6321334dda6b..2aa3103a6258 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/TaxonomicFilterMenu.tsx
@@ -243,29 +243,6 @@ export function TaxonomicFilterMenu({
() => 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)
@@ -479,14 +456,12 @@ export function TaxonomicFilterMenu({
? recentEntries
: state.drillTo === 'pinned'
? pinnedEntries
- : state.drillTo === 'suggested'
- ? suggestedEntries
- : undefined
+ : undefined
}
- // Always pass `suggestedItems` so the chip
- // works in 'all' mode too (without forcing a
- // drill via the dropdown menu).
- suggestedItems={suggestedEntries}
+ // Recents/pinned lead the default "All" surface
+ // (fixed order: recents, then pinned).
+ recentEntries={recentEntries}
+ pinnedEntries={pinnedEntries}
placeholder={placeholder ?? inputProps.placeholder}
// Only override the default "Choose filter"
// header when on the All chip — drilled views
diff --git a/frontend/src/lib/components/TaxonomicFilter/menu/types.ts b/frontend/src/lib/components/TaxonomicFilter/menu/types.ts
index 13898914cf5c..4667c7789627 100644
--- a/frontend/src/lib/components/TaxonomicFilter/menu/types.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/menu/types.ts
@@ -18,11 +18,8 @@ export interface MenuFilterEntry {
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
+/** Synthetic categories the combobox panel can be drilled into. */
+export type DrillCategory = 'all' | 'recent' | 'pinned' | TaxonomicFilterGroupType
/** Top-level state machine. One union type, one transition per action. */
export type MenuFilterState =
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts b/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts
index 8429f70fe567..41f5cb553066 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/promoteProperties.ts
@@ -7,42 +7,54 @@ export const PROMOTED_PROPERTIES_BY_SEARCH_TERM: Record<string, string[]> = {
}
/**
- * If the search query matches a promoted property's search terms, move that property
- * to the top of results so users find it quickly.
+ * Generic promotion helper: partitions `items` so any item whose name (as
+ * returned by `getName`) appears in `PROMOTED_PROPERTIES_BY_SEARCH_TERM` for
+ * the given `searchQuery` floats to the front. Returns `items` unchanged when
+ * the query is empty, there are no promoted names for the query, or nothing in
+ * the list matches the promoted set.
*/
-export function promoteMatchingProperties<T extends TaxonomicDefinitionTypes | SkeletonItem>(
- results: T[],
- searchQuery: string
-): T[] {
- if (!searchQuery) {
- return results
- }
-
+export function promoteMatchingBy<T>(items: T[], searchQuery: string, getName: (item: T) => string | undefined): T[] {
const query = searchQuery.toLowerCase().trim()
- const promotedPropertyNames = PROMOTED_PROPERTIES_BY_SEARCH_TERM[query]
- if (!promotedPropertyNames?.length) {
- return results
+ if (!query) {
+ return items
}
-
- const promotedPropertyNameSet = new Set(promotedPropertyNames)
+ const promotedNames = PROMOTED_PROPERTIES_BY_SEARCH_TERM[query]
+ if (!promotedNames?.length) {
+ return items
+ }
+ const promotedSet = new Set(promotedNames)
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)) {
+ for (const item of items) {
+ const name = getName(item)
+ if (name && promotedSet.has(name)) {
promoted.push(item)
} else {
rest.push(item)
}
}
+ return promoted.length > 0 ? [...promoted, ...rest] : items
+}
- return promoted.length > 0 ? [...promoted, ...rest] : results
+/**
+ * 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
+ }
+ return promoteMatchingBy(
+ results.filter((item): item is T => !!item),
+ searchQuery,
+ (item) => {
+ if (isSkeletonItem(item)) {
+ return undefined
+ }
+ return 'name' in item ? (item as { name?: string }).name : undefined
+ }
+ )
}