braid-design-system
Version:
Themeable design system for the SEEK Group
61 lines (60 loc) • 2 kB
JavaScript
import assert from "assert";
import { highlightSuggestions } from "./Autosuggest.mjs";
function matchSuggestion(suggestion, query) {
const highlights = highlightSuggestions(
suggestion.label ?? suggestion.text,
query
);
return highlights.length ? {
...suggestion,
highlights
} : null;
}
function filterSuggestions(...args) {
assert(
[1, 2].includes(args.length),
`Invalid number of arguments passed to "filterSuggestions". Expected 1 or 2, got ${args.length}`
);
if (args.length === 1) {
return (inputValue) => filter(args[0], inputValue);
} else if (args.length === 2) {
return filter(args[0], args[1]);
}
function filter(suggestions, inputValue) {
assert(
typeof inputValue === "string" || typeof inputValue === "object" && inputValue !== null && "text" in inputValue,
'The second argument to "filterSuggestions" must be a string or an Autosuggest value object, e.g. { text: "Hello world" }'
);
const query = (typeof inputValue === "string" ? inputValue : inputValue.text).trim();
if (query === "") {
return suggestions;
}
const filteredSuggestions = [];
suggestions.forEach((suggestion) => {
if ("suggestions" in suggestion) {
const filteredGroupSuggestions = [];
suggestion.suggestions.forEach((groupSuggestion) => {
const filteredSuggestion = matchSuggestion(groupSuggestion, query);
if (filteredSuggestion) {
filteredGroupSuggestions.push(filteredSuggestion);
}
});
if (filteredGroupSuggestions.length) {
filteredSuggestions.push({
...suggestion,
suggestions: filteredGroupSuggestions
});
}
} else {
const filteredSuggestion = matchSuggestion(suggestion, query);
if (filteredSuggestion) {
filteredSuggestions.push(filteredSuggestion);
}
}
});
return filteredSuggestions;
}
}
export {
filterSuggestions
};