Skip to content

Commit

Permalink
🐛 Filter pre-existing selections from options
Browse files Browse the repository at this point in the history
Signed-off-by: Ian Bolton <[email protected]>
  • Loading branch information
ibolton336 committed Mar 11, 2024
1 parent ad90cd5 commit 4f6c0de
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions client/src/app/components/Autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,22 +80,21 @@ export const Autocomplete: React.FC<IAutocompleteProps> = ({
}, [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 */
Expand Down Expand Up @@ -192,9 +191,13 @@ export const Autocomplete: React.FC<IAutocompleteProps> = ({
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 */
Expand Down

0 comments on commit 4f6c0de

Please sign in to comment.