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: give content match a lower score #4499

Merged
merged 2 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions apps/core/src/components/pure/cmdk/data.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ export const pageToCommand = (
};
};

const contentMatchedMagicString = '__$$content_matched$$__';

export const usePageCommands = () => {
// todo: considering collections for searching pages
// const { savedCollections } = useCollectionManager(currentCollectionsAtom);
Expand Down Expand Up @@ -221,7 +223,7 @@ export const usePageCommands = () => {

if (pageIds.includes(page.id)) {
// hack to make the page always showing in the search result
command.value += query;
command.value += contentMatchedMagicString;
}

return command;
Expand Down Expand Up @@ -372,11 +374,24 @@ export const useCMDKCommandGroups = () => {

export const customCommandFilter = (value: string, search: string) => {
// strip off the part between __>>> and <<<__
const label = value.replace(
let label = value.replace(
new RegExp(valueWrapperStart + '.*' + valueWrapperEnd, 'g'),
''
);
return commandScore(label, search);

const pageContentMatched = label.includes(contentMatchedMagicString);
if (pageContentMatched) {
label = label.replace(contentMatchedMagicString, '');
}

const originalScore = commandScore(label, search);

// if the command has matched the content but not the label,
// we should give it a higher score, but not too high
if (originalScore < 0.01 && pageContentMatched) {
return 0.3;
}
return originalScore;
};

export const useCommandFilteredStatus = (
Expand Down
4 changes: 2 additions & 2 deletions packages/cmdk/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -365,8 +365,8 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>(
// Sort the items
getValidItems()
.sort((a, b) => {
const valueA = a.getAttribute(VALUE_ATTR);
const valueB = b.getAttribute(VALUE_ATTR);
const valueA = a.getAttribute('id');
const valueB = b.getAttribute('id');
return (scores.get(valueB) ?? 0) - (scores.get(valueA) ?? 0);
})
.forEach(item => {
Expand Down
Loading