2024-04-10 14:27:22 -04:00
|
|
|
import { useMemo, useState } from 'react';
|
|
|
|
|
import { matchSorter } from 'match-sorter';
|
2024-05-07 13:13:55 -04:00
|
|
|
import type { OptionWithIcon, MentionOption } from '~/common';
|
2024-04-10 14:27:22 -04:00
|
|
|
|
|
|
|
|
export default function useCombobox({
|
|
|
|
|
value,
|
|
|
|
|
options,
|
|
|
|
|
}: {
|
|
|
|
|
value: string;
|
2024-05-07 13:13:55 -04:00
|
|
|
options: Array<OptionWithIcon | MentionOption>;
|
2024-04-10 14:27:22 -04:00
|
|
|
}) {
|
|
|
|
|
const [open, setOpen] = useState(false);
|
|
|
|
|
const [searchValue, setSearchValue] = useState('');
|
|
|
|
|
|
|
|
|
|
const matches = useMemo(() => {
|
|
|
|
|
if (!searchValue) {
|
|
|
|
|
return options;
|
|
|
|
|
}
|
|
|
|
|
const keys = ['label', 'value'];
|
|
|
|
|
const matches = matchSorter(options, searchValue, { keys });
|
|
|
|
|
// Radix Select does not work if we don't render the selected item, so we
|
|
|
|
|
// make sure to include it in the list of matches.
|
|
|
|
|
const selectedItem = options.find((currentItem) => currentItem.value === value);
|
|
|
|
|
if (selectedItem && !matches.includes(selectedItem)) {
|
|
|
|
|
matches.push(selectedItem);
|
|
|
|
|
}
|
|
|
|
|
return matches;
|
|
|
|
|
}, [searchValue, value, options]);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
open,
|
|
|
|
|
setOpen,
|
|
|
|
|
searchValue,
|
|
|
|
|
setSearchValue,
|
|
|
|
|
matches,
|
|
|
|
|
};
|
|
|
|
|
}
|