Skip to content

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).

@vercel
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

@jeffaburt
Copy link

image

I have a similar use case, what I did to work around the issue was set keywords={[search]}. Here's some extra context:

const CreateClientCommandGroup = () => {
  const search = useCommandState((state) => state.search);

  if (!search) {
    return null;
  }

  return (
    <CommandGroup>
      <CommandItem
        key={search}
        value={search}
        keywords={[search]}
        onSelect={() => {
          onCreateNew?.(search);
        }}
        className="font-medium"
      >
        + Create Client &ldquo;{search}&rdquo;
      </CommandItem>
    </CommandGroup>
  );
};

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.

2 participants