Use creatable autocomplete, to select or create a new playlist

This commit is contained in:
Deluan
2020-05-25 14:50:46 -04:00
committed by Deluan Quintão
parent 23bd5e1131
commit 6db63e4dfc
14 changed files with 287 additions and 319 deletions
+96
View File
@@ -0,0 +1,96 @@
/* eslint-disable no-use-before-define */
import React from 'react'
import TextField from '@material-ui/core/TextField'
import Autocomplete, {
createFilterOptions,
} from '@material-ui/lab/Autocomplete'
import { useGetList, useTranslate } from 'react-admin'
import PropTypes from 'prop-types'
const filter = createFilterOptions()
const SelectPlaylistInput = ({ onChange }) => {
const translate = useTranslate()
const { ids, data, loaded } = useGetList(
'playlist',
{ page: 1, perPage: -1 },
{ field: 'name', order: 'ASC' },
{}
)
if (!loaded) {
return null
}
const options = ids.map((id) => data[id])
const handleOnChange = (event, newValue) => {
if (newValue == null) {
onChange({})
} else if (typeof newValue === 'string') {
onChange({
name: newValue,
})
} else if (newValue && newValue.inputValue) {
// Create a new value from the user input
onChange({
name: newValue.inputValue,
})
} else {
onChange(newValue)
}
}
return (
<Autocomplete
onChange={handleOnChange}
filterOptions={(options, params) => {
const filtered = filter(options, params)
// Suggest the creation of a new value
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
name: `Add "${params.inputValue}"`,
})
}
return filtered
}}
clearOnBlur
handleHomeEndKeys
openOnFocus
selectOnFocus
id="select-playlist-input"
options={options}
getOptionLabel={(option) => {
// Value selected with enter, right from the input
if (typeof option === 'string') {
return option
}
// Add "xxx" option created dynamically
if (option.inputValue) {
return option.inputValue
}
// Regular option
return option.name
}}
renderOption={(option) => option.name}
style={{ width: 300 }}
freeSolo
renderInput={(params) => (
<TextField
autoFocus
{...params}
label={translate('resources.playlist.fields.name')}
/>
)}
/>
)
}
SelectPlaylistInput.propTypes = {
onChange: PropTypes.func.isRequired,
}
export default SelectPlaylistInput