All files / app/src/shared/ui/select-multi select-multi.tsx

67.1% Statements 153/228
89.65% Branches 26/29
25% Functions 4/16
67.1% Lines 153/228

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 2951x                                                                                               1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x   32x 32x 32x 19x 32x   32x 19x 32x   32x                                                                   32x           32x 32x 27x 27x 27x 32x 32x 32x                                     32x 38x 14x 10x 4x 4x 4x 4x 14x 38x   32x 32x 32x 32x 32x     32x 9x 9x 32x     32x 32x 32x 32x 32x 32x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x   38x 38x 38x   38x 38x 38x   32x 38x 38x 38x 38x 38x 38x 38x         38x 38x 38x 38x 2x 2x                       2x 2x 2x 2x 2x 2x   2x 2x 2x   2x   38x   32x   32x 6x 6x 6x 21x 8x 38x 38x 38x 38x 38x 38x 38x 38x         38x 38x 38x 38x 8x   13x 13x 13x   32x   32x  
import { useEffect, useMemo, useRef, useState } from 'react'
import Select, { Option, SelectProps as RcSelectProps } from 'rc-select'
import { Input, Button } from '@tmk/ui-kit'
import ArrowIcon from '@/shared/assets/icons/common/select-arrow.svg'
import cn from 'classnames'
import { httpClient, notify, useTranslate } from '@/shared/lib'
import { BaseEntity, CustomSelectOption, Nullable, SelectOption } from '@/shared/@types'
import Loading from '@/shared/assets/icons/common/loading.svg'
import { Checkbox } from '../checkbox'
import { InputProps } from '../input'
import AddIcon from '@/shared/assets/icons/common/add.svg'
import { ulid } from 'ulid'
import { AxiosError } from 'axios'
 
// eslint-disable-next-line
export interface SelectMultiSearchProps<T = Nullable<string | number>>
  extends Omit<RcSelectProps, 'value' | 'onChange' | 'onSelect'> {
  name: string
  label?: string
  value?: Nullable<string[]>
  disabled?: boolean
  options?: SelectOption[]
  inputProps?: Omit<InputProps, 'name'>
  isFilter?: boolean
  isSaved?: boolean
  className?: string
  isLoading?: boolean
  onChange?: (selected: Nullable<string[]>) => void
  onOpen?: () => void
  readOnly?: boolean
  optionsClassName?: string
  withOptionAddition?: boolean
  source?: string
  customSelectOptionValuekey?: string
  onAdd?: () => void
  onChangeWithOptions?: (options?: Nullable<MultiSelectOption[]>) => void
  onCustomSearch?: (value: string) => void
  dropDownClassName?: string
  defaultValues?: MultiSelectOption[]
}
 
export interface MultiSelectOption {
  id: string
  label: string
  disabled?: boolean | undefined
  checked?: boolean
}
 
export const MultiSelect = <T extends Nullable<string | number | SelectOption[] | MultiSelectOption[]>>({
  name,
  label,
  isLoading,
  disabled,
  onChange,
  options = [],
  onOpen,
  className,
  inputProps,
  isFilter,
  isSaved,
  readOnly = true,
  optionsClassName,
  withOptionAddition,
  source,
  customSelectOptionValuekey = 'name',
  onAdd,
  onChangeWithOptions,
  value,
  onCustomSearch,
  dropDownClassName,
  dropdownStyle,
  defaultValues = [],
  ...rest
}: SelectMultiSearchProps<T>) => {
  const [menuIsOpen, setMenuIsOpen] = useState(false)
  const [searchValue, setSearchValue] = useState('')
  const [isAddMode, setIsAddMode] = useState(false)
  const [selectValue, setSelectValue] = useState<MultiSelectOption[]>(defaultValues)
  const inputRef = useRef<HTMLInputElement>(null)
  const [isCustomOptionLoading, setIsCustomOptionLoading] = useState(false)
  const [customSelectOptions, setCustomSelectOptions] = useState<SelectOption[]>([])
 
  const isAddInputTypeNumber = inputProps?.type === 'number'
  const { t } = useTranslate(['common'])
  useEffect(() => {
    if (menuIsOpen) onOpen?.()
  }, [menuIsOpen])
 
  useEffect(() => {
    isAddMode && inputRef.current?.focus()
  }, [isAddMode])
 
  const onSuccess = async () => {
    try {
      const selectedData = structuredClone(selectValue).filter(item => value?.includes(item.id))
      setIsCustomOptionLoading(true)
      const inputValue = isAddInputTypeNumber ? inputRef.current?.valueAsNumber : inputRef.current?.value
      const { data } = await httpClient<CustomSelectOption & BaseEntity, CustomSelectOption>({
        url: source,
        method: 'POST',
        data: {
          id: ulid(),
          [customSelectOptionValuekey]: inputValue || '',
        },
      })
      setCustomSelectOptions(prev => [
        ...prev,
        {
          id: data['@id'],
          label: String(inputValue),
        },
      ])
      onChange?.([...selectedData.map(item => item.id), data?.['@id']])
      onChangeWithOptions?.([...selectedData, { id: data?.['@id'], label: String(inputValue) }])
      setIsAddMode(false)
      setMenuIsOpen(false)
    } catch (error) {
      if ((error as AxiosError).response?.status === 422) {
        return notify(t('This value is already in use'), { status: 'error' })
      }
      return notify('Server error text', { status: 'error' })
    } finally {
      setIsCustomOptionLoading(false)
    }
  }
 
  const resetAllOptions = () => {
    onChange?.(null)
    onChangeWithOptions?.(null)
    setSelectValue([])
  }
 
  const summaryOptions = useMemo(
    () =>
      [...options, ...customSelectOptions].filter(
        (value, index, self) => self.findIndex(t => t.id === value.id) === index
      ),
    [options, customSelectOptions]
  )
  const handleChangeChecked = (data: string) => {
    setSelectValue(prev => {
      const selectedData = structuredClone(prev).filter(item => value?.includes(item.id))
      const itemIndex = prev.findIndex(item => item.id === data)
      if (itemIndex !== -1) {
        const newValue = selectedData.filter((item, index) => index !== itemIndex)
        onChange?.(newValue.map(item => item?.id))
        onChangeWithOptions?.(newValue)
        return newValue
      } else {
        const newItem = { id: data, label: summaryOptions?.find(option => option.id === data)?.label || '' }
        const newValue = [...selectedData, newItem]
        onChange?.(newValue.map(item => item?.id))
        onChangeWithOptions?.(newValue)
        return newValue
      }
    })
  }
 
  const getInputValue = () => {
    if (Array.isArray(value)) {
      return value.length < 1
        ? ''
        : value
            .map(item => options?.find(option => option.id === item)?.label)
            .slice(0, 2)
            .join(', ')
    }
  }
 
  return (
    <Select
      value={value || []}
      mode='multiple'
      onDropdownVisibleChange={open => {
        !isAddMode && setMenuIsOpen(open)
      }}
      {...(!onCustomSearch && {
        searchValue,
      })}
      onSelect={data => {
        handleChangeChecked(data)
      }}
      onDeselect={data => handleChangeChecked(data)}
      notFoundContent={<h6 className='text-center p-small text-gray'>{t('Not found')}</h6>}
      className='w-full'
      open={menuIsOpen}
      dropdownStyle={dropdownStyle}
      getRawInputElement={() => (
        <Input
          name={name}
          label={label}
          isSaved={isSaved}
          isLoading={isLoading}
          disabled={disabled}
          isDropdownOpen={menuIsOpen}
          reset={resetAllOptions}
          readOnly={readOnly}
          inputWrapperClassName={cn('hover:cursor-pointer !px-0 !py-0 h-10', { '!border-main': menuIsOpen })}
          inputClassName='truncate h-10 pl-2'
          value={getInputValue()}
          extraContent={
            <>
              <Button
                variant='icon'
                data-testid='select-search-dropdown-button'
                className='pr-4'
                disabled={disabled}
                onMouseDown={e => [e.stopPropagation(), setMenuIsOpen(prev => !prev)]}
              >
                <ArrowIcon className={cn('stroke-currentColor transition-transform', { 'rotate-180': menuIsOpen })} />
              </Button>
            </>
          }
          {...inputProps}
          className={className}
        />
      )}
      dropdownRender={menu => (
        <div className={cn('min-w-[200px]', dropDownClassName)}>
          <Input
            type='search'
            className='p-small'
            name={name + '-add-option'}
            isFilter
            onChange={e => {
              const value = e.target.value
              setSearchValue(value)
              onCustomSearch?.(value)
            }}
            label={t('Search')}
          />
          {menu}
          {withOptionAddition && (
            <div className='mt-2.5 p-small -mx-small -mb-small rounded-b-xl shadow-notification'>
              {isAddMode ? (
                <Input
                  ref={inputRef}
                  name={name + '-add-option'}
                  type={inputProps?.type}
                  label={t('Enter a value')}
                  isLoading={isCustomOptionLoading}
                  onSuccess={onSuccess}
                  reset={() => setIsAddMode(false)}
                  onKeyDown={e => e.key === 'Enter' && inputRef.current?.value && onSuccess()}
                />
              ) : (
                <Button
                  variant='text'
                  color='secondary'
                  onClick={() => (onAdd ? [onAdd(), setMenuIsOpen(false)] : setIsAddMode(true))}
                  className='px-5 py-3.5'
                  childrenClassName='flex items-center gap-small'
                >
                  <AddIcon className='stroke-currentColor' />
                  <h3> {t('Other')}</h3>{' '}
                </Button>
              )}
            </div>
          )}
        </div>
      )}
      {...rest}
    >
      {isLoading ? (
        <Option className='pointer-events-none'>
          <Loading className='h-[29px] fill-main mx-auto animate-spin' />
        </Option>
      ) : summaryOptions.length > 0 ? (
        summaryOptions.map(item => (
          <Option key={item.id} value={item.id}>
            <div className={cn('flex hover:cursor-pointer', optionsClassName)}>
              <Checkbox
                className='text-sm'
                name={item.label}
                value={item.label}
                checked={value?.includes(item?.id) || false}
                onChange={e => {
                  e.preventDefault()
                  e.stopPropagation()
                  handleChangeChecked(item.id)
                }}
              />
              <p className='text-main-regular max-h-10 line-clamp-2 self-center'>{item.label}</p>
            </div>
          </Option>
        ))
      ) : (
        <Option className='pointer-events-none'>
          <h4 className='!text-text-secondary pointer-events-none'>{t('EmptyRequest')}</h4>
        </Option>
      )}
    </Select>
  )
}