From d9834ae5ed0bb06b72ddb16d2d865505e31f5fcb Mon Sep 17 00:00:00 2001 From: Clara Ni Date: Tue, 7 Jan 2025 18:39:33 +0100 Subject: [PATCH] fixup! core: refacto combo box --- .../inputs/ComboBox/useDefaultComboBox.ts | 37 +++++++++---------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/ui-core/src/components/inputs/ComboBox/useDefaultComboBox.ts b/ui-core/src/components/inputs/ComboBox/useDefaultComboBox.ts index 0faf9819a..6832ea466 100644 --- a/ui-core/src/components/inputs/ComboBox/useDefaultComboBox.ts +++ b/ui-core/src/components/inputs/ComboBox/useDefaultComboBox.ts @@ -12,28 +12,25 @@ const defaultFilterSuggestions = ( return suggestions; } - const { startingWithInput, containingInput } = suggestions.reduce<{ - startingWithInput: T[]; - containingInput: T[]; - }>( - (acc, suggestion) => { - const suggestionLabel = normalizeString(getSuggestionLabel(suggestion).toLowerCase()); - if (suggestionLabel.startsWith(input)) { - acc.startingWithInput.push(suggestion); - return acc; - } - if (suggestionLabel.includes(input)) { - acc.containingInput.push(suggestion); - } - return acc; - }, - { - startingWithInput: [], - containingInput: [], + const getSuggestionScore = (suggestion: T) => { + const suggestionLabel = normalizeString(getSuggestionLabel(suggestion).toLowerCase()); + if (suggestionLabel.startsWith(input)) { + return 2; } - ); + if (suggestionLabel.includes(input)) { + return 1; + } + return 0; + }; - return [...startingWithInput, ...containingInput]; + return suggestions + .map((suggestion) => ({ + suggestion, + score: getSuggestionScore(suggestion), + })) + .filter(({ score }) => score > 0) + .sort(({ score: scoreA }, { score: scoreB }) => scoreB - scoreA) + .map(({ suggestion }) => suggestion); }; const useDefaultComboBox = (suggestions: T[], getSuggestionLabel: (suggestion: T) => string) => {