aboutsummaryrefslogtreecommitdiffstats
path: root/src/views/components/AutocompleteSelect.jsx
blob: 7708214da643c27116b05f9ef95d743c9cfacc67 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import Add from '@mui/icons-material/Add'
import Autocomplete, { createFilterOptions } from '@mui/joy/Autocomplete'
import AutocompleteOption from '@mui/joy/AutocompleteOption'
import FormControl from '@mui/joy/FormControl'
import ListItemDecorator from '@mui/joy/ListItemDecorator'
import * as React from 'react'

const filter = createFilterOptions()

export default function FreeSoloCreateOption({ options, onSelectChange }) {
  React.useEffect(() => {
    setValue(options)
  }, [options])

  const [value, setValue] = React.useState([])
  const [selectOptions, setSelectOptions] = React.useState(
    options ? options : [],
  )
  return (
    <FormControl id='free-solo-with-text-demo'>
      <Autocomplete
        value={value}
        multiple
        size='lg'
        on
        onChange={(event, newValue) => {
          if (typeof newValue === 'string') {
            setValue({
              title: newValue,
            })
          } else if (newValue && newValue.inputValue) {
            // Create a new value from the user input
            setValue({
              title: newValue.inputValue,
            })
          } else {
            setValue(newValue)
          }
          onSelectChange(newValue)
        }}
        filterOptions={(options, params) => {
          const filtered = filter(options, params)

          const { inputValue } = params
          // Suggest the creation of a new value
          const isExisting = options.some(option => inputValue === option.title)
          if (inputValue !== '' && !isExisting) {
            filtered.push({
              inputValue,
              title: `Add "${inputValue}"`,
            })
          }

          return filtered
        }}
        selectOnFocus
        clearOnBlur
        handleHomeEndKeys
        // freeSolo
        options={selectOptions}
        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.title
        }}
        renderOption={(props, option) => (
          <AutocompleteOption {...props}>
            {option.title?.startsWith('Add "') && (
              <ListItemDecorator>
                <Add />
              </ListItemDecorator>
            )}

            {option.title ? option.title : option}
          </AutocompleteOption>
        )}
      />
    </FormControl>
  )
}