| 1 |
import ReactSelect from "react-select"; |
| 2 |
|
| 3 |
function getOptionValue(option) { |
| 4 |
if (option && typeof option === "object" && "value" in option) { |
| 5 |
return option.value; |
| 6 |
} |
| 7 |
|
| 8 |
return option; |
| 9 |
} |
| 10 |
|
| 11 |
function valuesMatch(firstValue, secondValue) { |
| 12 |
if (firstValue === null || firstValue === undefined) return false; |
| 13 |
if (secondValue === null || secondValue === undefined) return false; |
| 14 |
|
| 15 |
return String(firstValue) === String(secondValue); |
| 16 |
} |
| 17 |
|
| 18 |
function findSelectedOption(options, value) { |
| 19 |
const selectedValue = getOptionValue(value); |
| 20 |
|
| 21 |
return ( |
| 22 |
options.find((option) => valuesMatch(option.value, selectedValue)) || null |
| 23 |
); |
| 24 |
} |
| 25 |
|
| 26 |
function findSelectedOptions(options, values) { |
| 27 |
const selectedValues = Array.isArray(values) |
| 28 |
? values.map(getOptionValue) |
| 29 |
: []; |
| 30 |
|
| 31 |
return options.filter((option) => |
| 32 |
selectedValues.some((value) => valuesMatch(option.value, value)), |
| 33 |
); |
| 34 |
} |
| 35 |
|
| 36 |
export default function TagGroupsSelect({ |
| 37 |
className = "", |
| 38 |
closeOnSelect, |
| 39 |
multi = false, |
| 40 |
onChange, |
| 41 |
options = [], |
| 42 |
removeSelected, |
| 43 |
value, |
| 44 |
...props |
| 45 |
}) { |
| 46 |
const selectedValue = multi |
| 47 |
? findSelectedOptions(options, value) |
| 48 |
: findSelectedOption(options, value); |
| 49 |
|
| 50 |
const handleChange = (selection, actionMeta) => { |
| 51 |
if (multi) { |
| 52 |
onChange(selection || [], actionMeta); |
| 53 |
return; |
| 54 |
} |
| 55 |
|
| 56 |
if (selection) { |
| 57 |
onChange(selection, actionMeta); |
| 58 |
return; |
| 59 |
} |
| 60 |
|
| 61 |
onChange( |
| 62 |
{ |
| 63 |
label: "", |
| 64 |
value: typeof value === "number" ? -1 : "", |
| 65 |
}, |
| 66 |
actionMeta, |
| 67 |
); |
| 68 |
}; |
| 69 |
|
| 70 |
return ( |
| 71 |
<ReactSelect |
| 72 |
{...props} |
| 73 |
className={["tag-groups-select", className].filter(Boolean).join(" ")} |
| 74 |
closeMenuOnSelect={closeOnSelect === undefined ? !multi : closeOnSelect} |
| 75 |
hideSelected={removeSelected === undefined ? multi : removeSelected} |
| 76 |
isClearable={true} |
| 77 |
isMulti={multi} |
| 78 |
onChange={handleChange} |
| 79 |
options={options} |
| 80 |
value={selectedValue} |
| 81 |
/> |
| 82 |
); |
| 83 |
} |
| 84 |
|