From eb728f7ef2968f56671c25bcf1e9a2a4575138c9 Mon Sep 17 00:00:00 2001 From: Peng Xiao Date: Tue, 26 Sep 2023 11:15:40 +0800 Subject: [PATCH] fix: give content match a lower score (#4499) --- apps/core/src/components/pure/cmdk/data.tsx | 21 ++++++++++++++++++--- packages/cmdk/src/index.tsx | 4 ++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/apps/core/src/components/pure/cmdk/data.tsx b/apps/core/src/components/pure/cmdk/data.tsx index 094239a4fa..00dbcc86cf 100644 --- a/apps/core/src/components/pure/cmdk/data.tsx +++ b/apps/core/src/components/pure/cmdk/data.tsx @@ -176,6 +176,8 @@ export const pageToCommand = ( }; }; +const contentMatchedMagicString = '__$$content_matched$$__'; + export const usePageCommands = () => { // todo: considering collections for searching pages // const { savedCollections } = useCollectionManager(currentCollectionsAtom); @@ -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; @@ -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 = ( diff --git a/packages/cmdk/src/index.tsx b/packages/cmdk/src/index.tsx index 3a330dcd37..34f09cf5ee 100644 --- a/packages/cmdk/src/index.tsx +++ b/packages/cmdk/src/index.tsx @@ -365,8 +365,8 @@ const Command = React.forwardRef( // 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 => {