import Avatar from "@components/ui/Avatar"; import Select from "@components/ui/form/Select"; import { CheckIcon, XIcon } from "@heroicons/react/outline"; import { useLocale } from "@lib/hooks/useLocale"; import React, { useEffect, useState } from "react"; import { MultiValue } from "react-select"; type CheckedSelectValue = { avatar: string; label: string; value: string; disabled?: boolean; }[]; export type CheckedSelectProps = { defaultValue?: CheckedSelectValue; placeholder?: string; name?: string; options: CheckedSelectValue; onChange: (options: CheckedSelectValue) => void; disabled: boolean; }; export const CheckedSelect = (props: CheckedSelectProps) => { const [selectedOptions, setSelectedOptions] = useState(props.defaultValue || []); const { t } = useLocale(); useEffect(() => { props.onChange(selectedOptions); }, [selectedOptions]); const options = props.options.map((option) => ({ ...option, disabled: !!selectedOptions.find((selectedOption) => selectedOption.value === option.value), })); const removeOption = (value: string) => setSelectedOptions(selectedOptions.filter((option) => option.value !== value)); const changeHandler = (selections: MultiValue) => selections.forEach((selected) => { if (selectedOptions.find((option) => option.value === selected.value)) { removeOption(selected.value); return; } setSelectedOptions(selectedOptions.concat(selected)); }); return ( <> styles={{ option: (styles, { isDisabled }) => ({ ...styles, backgroundColor: isDisabled ? "#F5F5F5" : "inherit", }), }} name={props.name} placeholder={props.placeholder || t("select")} isSearchable={false} formatOptionLabel={({ label, avatar, disabled }) => (
{label} {disabled && (
)}
)} options={options} isMulti // value={props.placeholder || t("select")} onChange={changeHandler} /> {selectedOptions.map((option) => (
{option.label} changeHandler([option])} className="float-right mt-0.5 h-5 w-5 cursor-pointer text-neutral-500" />
))} ); }; CheckedSelect.displayName = "CheckedSelect"; export default CheckedSelect;