Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix wrong score calculation with leading/trailing white space on search string #347

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

pedroalmeida415
Copy link

@pedroalmeida415 pedroalmeida415 commented Mar 4, 2025

Description:

I'm using cmdk as a multi-selector with the option to create custom entries that are not listed. To do this, I'm simply rendering a Command.Item with the exact same key/value as the search string.

The problem is that, when the search contains a trailing space, e.g. "Test ", the score function doesn't match any items (likely because it's trying to match the exact string with the trailing space). What ends up happening is that all options get a score of 0 and what gets rendered is the <CommandEmpty/> component, even though I have an Item with the exact same value as the search.

Solution

This pull request includes a change to the cmdk/src/index.tsx file to fix the scoring function by trimming the search string before applying the filter. This ensures that any leading or trailing whitespace in the search string does not affect the scoring.

  • cmdk/src/index.tsx: Modified the score function to trim the search string before passing it to the filter function.

Current Behavior:
https://github.com/user-attachments/assets/397823b4-461f-4e69-9f92-a6a2368234f0

After fix:
https://github.com/user-attachments/assets/09e5792c-a57f-4a49-84bd-073de7274247

Edit:

The score algorithm also does not work well with whitespaces in-between words, so instead of just trimming the start/end, I'm applying a complete string sanitization to remove multiple space characters between words and then trimming the ends.

I know REGEXes are not the most performant option but since an item is supposed to be a menu item and not an entire essay, it gets the job done and there's no performance hit at all (~53 steps, 65μs).

Copy link

vercel bot commented Mar 4, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
cmdk-website ✅ Ready (Inspect) Visit Preview Mar 5, 2025 1:47am

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant