: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
fix(search): show each command k result once so row keys stay unique (#113887)
Adam Leith5a8964458767
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.test.tsnew file mode 100644index 000000000000..e98413bb7f3e--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts@@ -0,0 +1,74 @@+import { SearchItem } from 'lib/components/Search/searchItems'++import {+ CommandKMode,+ LocalLists,+ RECENTS_LIMIT,+ SectionsInput,+ buildSections,+ emptyRemoteSlots,+} from './commandKSections'+import { RESULTS_LIMIT } from './commandKSources'++const dashboard = (id: string, ref: string): SearchItem => ({+ id,+ name: `Dashboard ${ref}`,+ category: 'results',+ record: { type: 'dashboard', ref },+})++// Two file system entries point at dashboard 1, so its rows share a key.+const itemsWithRepeats = (count: number): SearchItem[] => [+ dashboard('entry-a', '1'),+ dashboard('entry-b', '1'),+ ...Array.from({ length: count }, (_, index) => dashboard(`entry-${index}`, String(index + 2))),+]++const emptyLocal = (): LocalLists => ({+ products: [],+ 'data-management': [],+ people: [],+ health: [],+ misc: [],+ settings: [],+ create: [],+ recents: [],+ starred: [],+})++const input = (mode: CommandKMode, overrides: Partial<SectionsInput>): SectionsInput => ({+ mode,+ context: mode === 'empty' ? { kind: 'empty' } : { kind: 'text', token: null },+ suggestions: null,+ local: emptyLocal(),+ remote: emptyRemoteSlots(),+ remoteQueries: {},+ localQuery: '',+ themeItem: null,+ askAiQuestion: '',+ ...overrides,+})++const remoteResults = (items: SearchItem[]): Partial<SectionsInput> => {+ const remote = emptyRemoteSlots()+ remote.results = { cache: { revenue: items }, displayedKey: 'revenue' }+ return { remote, remoteQueries: { results: 'revenue' } }+}++describe('buildSections', () => {+ test.each<[string, SectionsInput, string, number]>([+ ['remote results', input('search', remoteResults(itemsWithRepeats(RESULTS_LIMIT))), 'results', RESULTS_LIMIT],+ [+ 'recents',+ input('empty', { local: { ...emptyLocal(), recents: itemsWithRepeats(RECENTS_LIMIT) } }),+ 'recents',+ RECENTS_LIMIT,+ ],+ ])('shows an item once in %s, then fills up to the limit', (_, sectionsInput, sectionKey, limit) => {+ const section = buildSections(sectionsInput).find((candidate) => candidate.key === sectionKey)+ const keys = section?.rows.map((row) => row.key) ?? []+ expect(keys).toHaveLength(limit)+ expect(new Set(keys).size).toBe(limit)+ expect(keys[0]).toBe(`${sectionKey}/dashboard:1`)+ })+})diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.tsindex c6fecfe0c8f3..f2df122c4a43 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSections.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.ts@@ -81,8 +81,26 @@ const itemIdentity = (item: SearchItem): string => {return typeof type === 'string' && typeof ref === 'string' && ref ? `${type}:${ref}` : item.id}-const itemRows = (section: CommandKSectionKey, items: SearchItem[]): CommandKRow[] =>- items.map((item) => ({ kind: 'item', key: `${section}/${itemIdentity(item)}`, item, section }))+/**+ * The file system can hold more than one entry for the same object, so a list can repeat an item.+ * Row keys must be unique, because the highlight and the row DOM ids follow the key. Only the first+ * row for each key stays, and the limit applies after that.+ */+const itemRows = (section: CommandKSectionKey, items: SearchItem[], limit = Infinity): CommandKRow[] => {+ const rows: CommandKRow[] = []+ const seen = new Set<string>()+ for (const item of items) {+ if (rows.length >= limit) {+ break+ }+ const key = `${section}/${itemIdentity(item)}`+ if (!seen.has(key)) {+ seen.add(key)+ rows.push({ kind: 'item', key, item, section })+ }+ }+ return rows+}const readySection = (key: CommandKSectionKey, rows: CommandKRow[]): CommandKSection => ({key,@@ -108,12 +126,12 @@ function remoteSection(source: RemoteSource, slot: RemoteSlot, query: string): Cconst limit = source === 'results' ? RESULTS_LIMIT : SECONDARY_LIMITconst current = slot.cache[query]if (current) {- return current.length > 0 ? readySection(source, itemRows(source, current.slice(0, limit))) : null+ return current.length > 0 ? readySection(source, itemRows(source, current, limit)) : null}const displayed = slot.displayedKey !== null ? slot.cache[slot.displayedKey] : undefinedif (displayed) {return displayed.length > 0- ? { ...readySection(source, itemRows(source, displayed.slice(0, limit))), state: 'stale' }+ ? { ...readySection(source, itemRows(source, displayed, limit)), state: 'stale' }: null}return source === 'results' ? loadingSection(source) : null@@ -180,13 +198,13 @@ export interface SectionsInput {}const filterLocal = (source: LocalSource, items: SearchItem[], query: string): SearchItem[] =>- (source === 'create' ? filterNewItems(items, query) : filterSearchItems(items, query)).slice(0, SECONDARY_LIMIT)+ source === 'create' ? filterNewItems(items, query) : filterSearchItems(items, query)export function buildSections(input: SectionsInput): CommandKSection[] {const { mode, context, local, remote, remoteQueries, localQuery } = inputif (mode === 'empty') {return [- readySection('recents', itemRows('recents', local.recents.slice(0, RECENTS_LIMIT))),+ readySection('recents', itemRows('recents', local.recents, RECENTS_LIMIT)),readySection('starred', itemRows('starred', local.starred)),// Tab rows ("Dashboards / Templates") only appear for a search, as in the current palette.readySection(@@ -221,8 +239,11 @@ export function buildSections(input: SectionsInput): CommandKSection[] {if (mode !== 'value' && localQuery) {for (const source of LOCAL_SOURCES) {const filtered = filterLocal(source, local[source], localQuery)- const items = source === 'settings' && input.themeItem ? [input.themeItem, ...filtered] : filtered- sections.push(items.length > 0 ? readySection(source, itemRows(source, items)) : null)+ const themeItem = source === 'settings' ? input.themeItem : null+ const rows = themeItem+ ? itemRows(source, [themeItem, ...filtered], SECONDARY_LIMIT + 1)+ : itemRows(source, filtered, SECONDARY_LIMIT)+ sections.push(rows.length > 0 ? readySection(source, rows) : null)}}if (mode !== 'value') {