import { CheckIcon, XIcon } from "@heroicons/react/outline"; import React, { ForwardedRef, useEffect, useState } from "react"; import { useLocale } from "@lib/hooks/useLocale"; import Avatar from "@components/ui/Avatar"; import Select from "@components/ui/form/Select"; type CheckedSelectValue = { avatar: string; label: string; value: string; }[]; export type CheckedSelectProps = { defaultValue?: CheckedSelectValue; placeholder?: string; name?: string; options: CheckedSelectValue; onChange: (options: CheckedSelectValue) => void; disabled: boolean; }; export const CheckedSelect = React.forwardRef((props: CheckedSelectProps, ref: ForwardedRef) => { const [selectedOptions, setSelectedOptions] = useState(props.defaultValue || []); const { t } = useLocale(); useEffect(() => { props.onChange(selectedOptions); }, [selectedOptions]); const formatOptionLabel = ({ label, avatar, disabled }) => (
{label} {disabled && (
)}
); 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) => selections.forEach((selected) => { if (selectedOptions.find((option) => option.value === selected.value)) { removeOption(selected.value); return; } setSelectedOptions(selectedOptions.concat(selected)); }); return ( <>