lamassu-server/new-lamassu-admin/src/components/inputs/base/Autocomplete.js
Liordino Neto 246f736fa8 feat: first field now autofocus when editing a row
fix: move the focus to the first editable element

fix: make the Autocomplete options popup on autoFocus

feat: allow saving on table only when changes occurred

fix: compare only the editing row instead of the entire list to decide
if the save method will be called
2020-09-02 13:06:00 +02:00

95 lines
2.1 KiB
JavaScript

import MAutocomplete from '@material-ui/lab/Autocomplete'
import sort from 'match-sorter'
import * as R from 'ramda'
import React from 'react'
import TextInput from './TextInput'
const Autocomplete = ({
limit = 5, // set limit = null for no limit
options,
label,
valueProp,
multiple,
onChange,
getLabel,
value: outsideValue,
error,
fullWidth,
textAlign,
size,
...props
}) => {
const mapFromValue = options => it => R.find(R.propEq(valueProp, it))(options)
const mapToValue = R.prop(valueProp)
const getValue = () => {
if (!valueProp) return outsideValue
const transform = multiple
? R.map(mapFromValue(options))
: mapFromValue(options)
return transform(outsideValue)
}
const value = getValue()
const innerOnChange = (evt, value) => {
if (!valueProp) return onChange(evt, value)
const rValue = multiple ? R.map(mapToValue)(value) : mapToValue(value)
onChange(evt, rValue)
}
const valueArray = () => (multiple ? value : [value])
const filter = (array, input) =>
sort(array, input, { keys: ['code', 'display'] })
const filterOptions = (array, { inputValue }) =>
R.union(
R.isEmpty(inputValue) ? valueArray() : [],
filter(array, inputValue)
).slice(
0,
R.defaultTo(undefined)(limit) &&
Math.max(limit, R.isEmpty(inputValue) ? valueArray().length : 0)
)
return (
<MAutocomplete
options={options}
multiple={multiple}
value={value}
onChange={innerOnChange}
getOptionLabel={getLabel}
forcePopupIcon={false}
filterOptions={filterOptions}
openOnFocus
autoHighlight
disableClearable
ChipProps={{ onDelete: null }}
blurOnSelect
clearOnEscape
getOptionSelected={R.eqProps(valueProp)}
{...props}
renderInput={params => {
return (
<TextInput
{...params}
label={label}
value={outsideValue}
error={error}
size={size}
fullWidth={fullWidth}
textAlign={textAlign}
{...props}
/>
)
}}
/>
)
}
export default Autocomplete