From 4f6c0de5796bd665e3aacb26f5057bef6d61d5de Mon Sep 17 00:00:00 2001 From: Ian Bolton Date: Mon, 11 Mar 2024 17:08:19 -0400 Subject: [PATCH] :bug: Filter pre-existing selections from options Signed-off-by: Ian Bolton --- client/src/app/components/Autocomplete.tsx | 33 ++++++++++++---------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/client/src/app/components/Autocomplete.tsx b/client/src/app/components/Autocomplete.tsx index d06dfd130d..eebfcbbb9f 100644 --- a/client/src/app/components/Autocomplete.tsx +++ b/client/src/app/components/Autocomplete.tsx @@ -80,22 +80,21 @@ export const Autocomplete: React.FC = ({ }, [options, selections]); const filteredOptions = useMemo(() => { - // No input so do not filter! - if (!inputValue) { - return options; - } - - // filter to choose options that are 1. NOT selected, and 2. include the inputValue - return options.filter( - ({ id, name }) => - selections.findIndex((s) => s.id === id) === -1 && - toString(name).toLowerCase().includes(inputValue.toLocaleLowerCase()) - ); + const lowerInputValue = inputValue.toLowerCase(); + return options.filter((option) => { + const optionNameLower = toString(option.name).toLowerCase(); + const isNotSelected = !selections.some( + (selection) => selection.id === option.id + ); + const matchesInputValue = optionNameLower.includes(lowerInputValue); + return isNotSelected && matchesInputValue; + }); }, [options, selections, inputValue]); /** callback for removing a selection */ const deleteSelectionByItemId = (idToDelete: number) => { - onChange(selections.filter(({ id }) => id !== idToDelete)); + const updatedSelections = selections.filter(({ id }) => id !== idToDelete); + onChange(updatedSelections); }; /** lookup the option matching the itemId and add as a selection */ @@ -192,9 +191,13 @@ export const Autocomplete: React.FC = ({ return; } - event.stopPropagation(); - focusTextInput(true); - addSelectionByItemId(itemId); + const newSelection = options.find((option) => option.id === itemId); + if (newSelection) { + const updatedSelections = [...selections, newSelection].filter(Boolean); + onChange(updatedSelections); + setInputValue(""); + setMenuIsOpen(false); + } }; /** close the menu when a click occurs outside of the menu or text input group */