File size: 2,363 Bytes
0bfe2e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
88
89
import React, { KeyboardEventHandler } from 'react';

import CreatableSelect from 'react-select/creatable';
import showToast from './Toasts';
import { selectStyles } from './MutliSelect';
import FakeSelect from './FakeSelect';

const components = {
  DropdownIndicator: null,
};

interface Option {
  readonly label: string;
  readonly value: string;
}

const createOption = (label: string) => ({
  label,
  value: label,
});

interface CreateableSelectProps {
  value: readonly Option[];
  setValue: React.Dispatch<React.SetStateAction<readonly Option[]>>;
}
const CreateableSelect: React.FC<CreateableSelectProps> = ({
  value,
  setValue,
}) => {
  const [inputValue, setInputValue] = React.useState('');
  const [isClient, setIsClient] = React.useState(false);

  React.useEffect(() => {
    setIsClient(true);
  }, []);

  const handleKeyDown: KeyboardEventHandler = (event) => {
    if (!inputValue) return;
    if (inputValue.length > 20) {
      showToast('Value is too long', 'error', 'longValue');
      setInputValue('');
    }
    switch (event.key) {
      case 'Enter':
      case 'Tab':
        const cleanedInputValue = inputValue;
        if (!cleanedInputValue.length) {
          showToast('Invalid value', 'error', 'invalidValue');
          return;
        }
        if (value.find((v) => v.label === cleanedInputValue)) {
          showToast('Value already exists', 'error', 'existingValue');
          return;
        }
        if (cleanedInputValue.length > 50) {
          showToast('Value is too long', 'error', 'longValue');
          return;
        }
        setValue((prev) => [...prev, createOption(cleanedInputValue)]);
        setInputValue('');
        event.preventDefault();
    }
  };

  return (
    <>
      {isClient ? (
        <CreatableSelect
          components={components}
          inputValue={inputValue}
          isClearable
          isMulti
          menuIsOpen={false}
          onChange={(newValue) => setValue(newValue as readonly Option[])}
          onInputChange={(newValue) => setInputValue(newValue)}
          onKeyDown={handleKeyDown}
          placeholder="Type something and press enter..."
          value={value}
          styles={selectStyles}
        />
      ) : (
        <FakeSelect innerText="Type something and press enter..." />
      )}
    </>
  );
};

export default CreateableSelect;