Skip to content

Commit

Permalink
fixup! core: refacto combo box
Browse files Browse the repository at this point in the history
  • Loading branch information
clarani committed Jan 7, 2025
1 parent 32086fd commit d9834ae
Showing 1 changed file with 17 additions and 20 deletions.
37 changes: 17 additions & 20 deletions ui-core/src/components/inputs/ComboBox/useDefaultComboBox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,25 @@ const defaultFilterSuggestions = <T>(
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 = <T>(suggestions: T[], getSuggestionLabel: (suggestion: T) => string) => {
Expand Down

0 comments on commit d9834ae

Please sign in to comment.