Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Autocomplete): dont put text cursor to the end on every change event #1968

Merged
merged 1 commit into from
Mar 23, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions packages/components/autocomplete/src/Autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,23 @@ function _Autocomplete<ItemType>(
const [inputValue, setInputValue] = useState(defaultValue);

const handleInputValueChange = useCallback(
(value) => {
(value: string) => {
setInputValue(value);

onInputValueChange?.(value);
},
[onInputValueChange],
);

// Handle manually to avoid a jumping cursor, see https://github.com/downshift-js/downshift/issues/1108#issuecomment-842407759
const handleNativeChangeEvent = useCallback(
(event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const value = event.target.value;
handleInputValueChange(value);
},
[handleInputValueChange],
);

const flattenItems = isUsingGroups(isGrouped, items)
? items.reduce(
(acc: ItemType[], group: GroupType) => [...acc, ...group.options],
Expand All @@ -185,8 +194,10 @@ function _Autocomplete<ItemType>(
items: flattenItems,
inputValue,
itemToString,
onInputValueChange: ({ inputValue }) => {
handleInputValueChange(inputValue);
onInputValueChange: ({ type, inputValue }) => {
if (type !== '__input_change__') {
handleInputValueChange(inputValue);
}
},
onStateChange: ({ type, selectedItem }) => {
switch (type) {
Expand Down Expand Up @@ -249,6 +260,10 @@ function _Autocomplete<ItemType>(
ref={mergeRefs(inputProps.ref, inputRef)}
testId="cf-autocomplete-input"
placeholder={placeholder}
onChange={(event) => {
inputProps.onChange(event);
handleNativeChangeEvent(event);
}}
/>
<IconButton
{...toggleProps}
Expand Down