Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Cmd K to sort results based on relevance score (#52211)

Joshen Lim17582d837359
diff --git a/packages/ui-patterns/package.json b/packages/ui-patterns/package.json
index 71d033ec65c..81374ef8de4 100644
--- a/packages/ui-patterns/package.json
+++ b/packages/ui-patterns/package.json
@@ -159,6 +159,10 @@
"import": "./src/CommandMenu/api/TextHighlighter.tsx",
"types": "./src/CommandMenu/api/TextHighlighter.tsx"
},
+ "./CommandMenu/api/commandScore": {
+ "import": "./src/CommandMenu/api/commandScore.ts",
+ "types": "./src/CommandMenu/api/commandScore.ts"
+ },
"./CommandMenu/api/hooks/commandsHooks": {
"import": "./src/CommandMenu/api/hooks/commandsHooks.ts",
"types": "./src/CommandMenu/api/hooks/commandsHooks.ts"
@@ -195,6 +199,10 @@
"import": "./src/CommandMenu/api/hooks/viewHooks.ts",
"types": "./src/CommandMenu/api/hooks/viewHooks.ts"
},
+ "./CommandMenu/api/sortSectionsByRelevance": {
+ "import": "./src/CommandMenu/api/sortSectionsByRelevance.ts",
+ "types": "./src/CommandMenu/api/sortSectionsByRelevance.ts"
+ },
"./CommandMenu/api/types": {
"import": "./src/CommandMenu/api/types.ts",
"types": "./src/CommandMenu/api/types.ts"
diff --git a/packages/ui-patterns/src/CommandMenu/api/CommandMenuList.tsx b/packages/ui-patterns/src/CommandMenu/api/CommandMenuList.tsx
index ad7265f6a31..29fa4c0dc4a 100644
--- a/packages/ui-patterns/src/CommandMenu/api/CommandMenuList.tsx
+++ b/packages/ui-patterns/src/CommandMenu/api/CommandMenuList.tsx
@@ -8,6 +8,7 @@ import { CommandMenuGroup } from '../internal/CommandMenuGroup'
import { CommandMenuItem } from '../internal/CommandMenuItem'
import { useCommands } from './hooks/commandsHooks'
import { useQuery } from './hooks/queryHooks'
+import { sortSectionsByRelevance } from './sortSectionsByRelevance'
import { TextHighlighter } from './TextHighlighter'
const CommandMenuList = forwardRef<
@@ -32,7 +33,7 @@ const CommandMenuList = forwardRef<
{...props}
>
<CommandMenuEmpty listRef={innerRef}>No results found.</CommandMenuEmpty>
- {commandSections.map((section) => {
+ {sortSectionsByRelevance(commandSections, query).map((section) => {
if (section.commands.every((command) => command.defaultHidden) && !query) return null
return (
diff --git a/packages/ui-patterns/src/CommandMenu/api/commandScore.ts b/packages/ui-patterns/src/CommandMenu/api/commandScore.ts
new file mode 100644
index 00000000000..970510b0dc9
--- /dev/null
+++ b/packages/ui-patterns/src/CommandMenu/api/commandScore.ts
@@ -0,0 +1,106 @@
+/**
+ * Fuzzy match scorer. This is the same algorithm cmdk uses internally to
+ * filter items (a port of https://github.com/superhuman/command-score, MIT),
+ * which cmdk doesn't export. Keeping it identical means a section's rank here
+ * agrees with which of its items cmdk considers a match.
+ */
+const SCORE_CONTINUE_MATCH = 1
+const SCORE_SPACE_WORD_JUMP = 0.9
+const SCORE_NON_SPACE_WORD_JUMP = 0.8
+const SCORE_CHARACTER_JUMP = 0.17
+const SCORE_TRANSPOSITION = 0.1
+const PENALTY_SKIPPED = 0.999
+const PENALTY_CASE_MISMATCH = 0.9999
+const PENALTY_NOT_COMPLETE = 0.99
+
+const IS_GAP_REGEXP = /[\\/_+.#"@[({&]/
+const COUNT_GAPS_REGEXP = /[\\/_+.#"@[({&]/g
+const IS_SPACE_REGEXP = /[\s-]/
+const COUNT_SPACE_REGEXP = /[\s-]/g
+
+function scoreInner(
+ string: string,
+ abbreviation: string,
+ lowerString: string,
+ lowerAbbreviation: string,
+ stringIndex: number,
+ abbreviationIndex: number,
+ memo: Record<string, number>
+): number {
+ if (abbreviationIndex === abbreviation.length) {
+ return stringIndex === string.length ? SCORE_CONTINUE_MATCH : PENALTY_NOT_COMPLETE
+ }
+
+ const memoKey = `${stringIndex},${abbreviationIndex}`
+ if (memo[memoKey] !== undefined) return memo[memoKey]
+
+ const abbreviationChar = lowerAbbreviation.charAt(abbreviationIndex)
+ let index = lowerString.indexOf(abbreviationChar, stringIndex)
+ let highScore = 0
+
+ while (index >= 0) {
+ let score = scoreInner(
+ string,
+ abbreviation,
+ lowerString,
+ lowerAbbreviation,
+ index + 1,
+ abbreviationIndex + 1,
+ memo
+ )
+
+ if (score > highScore) {
+ if (index === stringIndex) {
+ score *= SCORE_CONTINUE_MATCH
+ } else if (IS_GAP_REGEXP.test(string.charAt(index - 1))) {
+ score *= SCORE_NON_SPACE_WORD_JUMP
+ const wordBreaks = string.slice(stringIndex, index - 1).match(COUNT_GAPS_REGEXP)
+ if (wordBreaks && stringIndex > 0) score *= Math.pow(PENALTY_SKIPPED, wordBreaks.length)
+ } else if (IS_SPACE_REGEXP.test(string.charAt(index - 1))) {
+ score *= SCORE_SPACE_WORD_JUMP
+ const spaceBreaks = string.slice(stringIndex, index - 1).match(COUNT_SPACE_REGEXP)
+ if (spaceBreaks && stringIndex > 0) score *= Math.pow(PENALTY_SKIPPED, spaceBreaks.length)
+ } else {
+ score *= SCORE_CHARACTER_JUMP
+ if (stringIndex > 0) score *= Math.pow(PENALTY_SKIPPED, index - stringIndex)
+ }
+
+ if (string.charAt(index) !== abbreviation.charAt(abbreviationIndex)) {
+ score *= PENALTY_CASE_MISMATCH
+ }
+ }
+
+ if (
+ (score < SCORE_TRANSPOSITION &&
+ lowerString.charAt(index - 1) === lowerAbbreviation.charAt(abbreviationIndex + 1)) ||
+ (lowerAbbreviation.charAt(abbreviationIndex + 1) ===
+ lowerAbbreviation.charAt(abbreviationIndex) &&
+ lowerString.charAt(index - 1) !== lowerAbbreviation.charAt(abbreviationIndex))
+ ) {
+ const transposedScore = scoreInner(
+ string,
+ abbreviation,
+ lowerString,
+ lowerAbbreviation,
+ index + 1,
+ abbreviationIndex + 2,
+ memo
+ )
+ if (transposedScore * SCORE_TRANSPOSITION > score) {
+ score = transposedScore * SCORE_TRANSPOSITION
+ }
+ }
+
+ if (score > highScore) highScore = score
+ index = lowerString.indexOf(abbreviationChar, index + 1)
+ }
+
+ memo[memoKey] = highScore
+ return highScore
+}
+
+const normalize = (str: string) => str.toLowerCase().replace(/[\s-]/g, ' ')
+
+export function commandScore(string: string, abbreviation: string): number {
+ return scoreInner(string, abbreviation, normalize(string), normalize(abbreviation), 0, 0, {})
+}
diff --git a/packages/ui-patterns/src/CommandMenu/api/sortSectionsByRelevance.test.ts b/packages/ui-patterns/src/CommandMenu/api/sortSectionsByRelevance.test.ts
new file mode 100644
index 00000000000..453dc596845
--- /dev/null
+++ b/packages/ui-patterns/src/CommandMenu/api/sortSectionsByRelevance.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest'
+
+import type { ICommandSection } from '../internal/types'
+import { sortSectionsByRelevance } from './sortSectionsByRelevance'
+
+const section = (id: string, ...names: string[]): ICommandSection => ({
+ id,
+ name: id,
+ commands: names.map((name) => ({ id: name, name, action: () => {} })),
+})
+
+const ids = (sections: readonly ICommandSection[]) => sections.map((s) => s.id)
+
+describe('sortSectionsByRelevance', () => {
+ it('puts the section with the best matching command first', () => {
+ const sections = [
+ section('actions', 'Configure organization...', 'Switch project...'),
+ section('database', 'View and create functions'),
+ section('integrations', 'View and manage your Cron Jobs'),
+ ]
+
+ expect(ids(sortSectionsByRelevance(sections, 'cron'))[0]).toBe('integrations')
+ })
+
+ it('keeps the registered order when there is no query or nothing separates the sections', () => {
+ const sections = [section('a', 'Alpha'), section('b', 'Beta')]
+
+ expect(ids(sortSectionsByRelevance(sections, ''))).toEqual(['a', 'b'])
+ expect(ids(sortSectionsByRelevance(sections, 'zzz'))).toEqual(['a', 'b'])
+ })
+})
diff --git a/packages/ui-patterns/src/CommandMenu/api/sortSectionsByRelevance.ts b/packages/ui-patterns/src/CommandMenu/api/sortSectionsByRelevance.ts
new file mode 100644
index 00000000000..a7e30f8ce00
--- /dev/null
+++ b/packages/ui-patterns/src/CommandMenu/api/sortSectionsByRelevance.ts
@@ -0,0 +1,26 @@
+import { commandScore } from './commandScore'
+
+/**
+ * cmdk is meant to reorder groups by their best matching item while searching,
+ * but its lookup of the group element fails, so groups stay in registration
+ * order. Do it here instead. The sort is stable, so sections with equal scores
+ * keep their registered (priority) order.
+ */
+export function sortSectionsByRelevance<
+ T extends { commands: readonly { name: string; value?: string }[] },
+>(sections: readonly T[], query: string): readonly T[] {
+ const search = query.trim()
+ if (!search) return sections
+
+ const bestScore = (section: T) =>
+ section.commands.reduce(
+ (best, command) =>
+ Math.max(best, commandScore((command.value ?? command.name).trim(), search)),
+ 0
+ )
+
+ return sections
+ .map((section) => ({ section, score: bestScore(section) }))
+ .sort((a, b) => b.score - a.score)
+ .map(({ section }) => section)
+}