Fix wrong score calculation with leading/trailing white space on search string #347
+3
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 aCommand.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 thescore
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).