Skip to content

Commit

Permalink
Fixed issue where onFocus and onBlur broke internals of Autocomplete (#…
Browse files Browse the repository at this point in the history
…2999)

- Fixed it in a generic way so it affects all on[Something] events
  • Loading branch information
bjartebore authored Aug 11, 2023
1 parent 4b5bd80 commit f6d0922
Showing 1 changed file with 43 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@ import {
useCallback,
ChangeEvent,
ReactNode,
EventHandler,
SyntheticEvent,
DOMAttributes,
} from 'react'
import {
useCombobox,
UseComboboxProps,
useMultipleSelection,
UseMultipleSelectionProps,
} from 'downshift'
import { pickBy, mergeWith } from 'ramda'
import { useVirtualizer } from '@tanstack/react-virtual'
import styled, { ThemeProvider, css } from 'styled-components'
import { Button } from '../Button'
Expand Down Expand Up @@ -101,6 +105,31 @@ const findIndex: IndexFinderType = ({
return index
}

const isEvent = (val: unknown, key: string) =>
/^on[A-Z](.*)/.test(key) && typeof val === 'function'

function mergeEventsFromRight(
props1: DOMAttributes<unknown>,
props2: DOMAttributes<unknown>,
) {
const events1: Partial<DOMAttributes<unknown>> = pickBy(isEvent, props1)
const events2: Partial<DOMAttributes<unknown>> = pickBy(isEvent, props2)

return mergeWith(
(
event1: EventHandler<SyntheticEvent<unknown>>,
event2: EventHandler<SyntheticEvent<unknown>>,
): EventHandler<SyntheticEvent<unknown>> => {
return (...args) => {
event1(...args)
event2(...args)
}
},
events1,
events2,
) as Partial<DOMAttributes<unknown>>
}

const findNextIndex: IndexFinderType = ({
index,
optionDisabled,
Expand Down Expand Up @@ -672,6 +701,18 @@ function AutocompleteInner<T>(
</div>
)

const inputProps = getInputProps(
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
getDropdownProps({
preventKeyAction: multiple ? isOpen : undefined,
disabled,
ref: refs.setReference,
onChange: (e: ChangeEvent<HTMLInputElement>) =>
setTypedInputValue(e?.currentTarget?.value),
}),
)
const consolidatedEvents = mergeEventsFromRight(other, inputProps)

return (
<ThemeProvider theme={token}>
<Container className={className} style={style} ref={ref}>
Expand All @@ -684,16 +725,7 @@ function AutocompleteInner<T>(

<Container>
<Input
{...getInputProps(
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
getDropdownProps({
preventKeyAction: multiple ? isOpen : undefined,
disabled,
ref: refs.setReference,
onChange: (e: ChangeEvent<HTMLInputElement>) =>
setTypedInputValue(e?.currentTarget?.value),
}),
)}
{...inputProps}
placeholder={placeholderText}
readOnly={readOnly}
rightAdornmentsWidth={hideClearButton ? 24 + 8 : 24 * 2 + 8}
Expand Down Expand Up @@ -728,6 +760,7 @@ function AutocompleteInner<T>(
</>
}
{...other}
{...consolidatedEvents}
/>
</Container>
{disablePortal || inDialog ? (
Expand Down

0 comments on commit f6d0922

Please sign in to comment.