All files / app/src/shared/lib/react-query select-with-query.tsx

88.48% Statements 123/139
81.57% Branches 31/38
25% Functions 2/8
88.48% Lines 123/139

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 1841x               1x                                                     1x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x   140x 140x 59x 63x     63x     63x 59x   140x 140x   140x   140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 39x 37x 37x 37x 37x 140x 140x 140x 140x 140x 140x   140x 140x 140x 140x 140x 140x 22x 90x 140x 140x 90x 90x 90x 90x 90x 140x 140x   140x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x   140x               140x 90x 140x   140x 90x       140x   140x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 111x 111x 111x 111x 111x 111x 111x 59x 59x 111x 111x 111x 111x 111x 111x       140x  
import { CollectionResponse, CustomSelectOption, Nullable, SelectOption } from '@/shared/@types'
import { normalizeSelectOptions } from '@/shared/helpers'
import { SelectSearchProps, SelectSearch, Select, MultiSelect } from '@/shared/ui'
import { useState, useMemo, useCallback, useEffect } from 'react'
import { FieldError } from 'react-hook-form'
import { QueryParams, QueryWithCollectionResponse, DependentQueryWithCollectionResponse } from './factories'
import { debounce } from 'lodash'
 
const normalizeDependentEntityValue = (entity: string | CustomSelectOption) =>
  String((entity as CustomSelectOption)?.['@id'] || entity)?.replace?.(/\/\w+\//g, '')
type TransformLabel<R extends CollectionResponse> = (entity: R['hydra:member'][number]) => string
export interface SelectWithQueryProps<R extends CollectionResponse, P extends QueryParams<R>>
  extends Omit<SelectSearchProps, 'dependentField' | 'customSelectOptionValuekey'> {
  type?: 'select' | 'selectSearch' | 'multiSelect'
  subType?: 'text' | 'number'
  dependentEntities?: Record<string, string | CustomSelectOption | undefined | boolean>
  dependentEntityType?: 'id' | 'filter'
  labelKey?: string
  transformLabel?: TransformLabel<R>
  valueKey?: string
  params?: P
  value?: string | string[]
  error?: FieldError
  useQuery: QueryWithCollectionResponse<R, P> | DependentQueryWithCollectionResponse<R, P>
  onChangeWithOptions?: (options?: Nullable<SelectOption | SelectOption[]>) => void
  additionalFields?: string[]
  validate?: (item: R['hydra:member'][number]) => boolean
  disableOnEmptyOptions?: boolean
  isLoading?: boolean
  loadingOnMount?: boolean
  disableIfEmptyDependentEntities?: boolean
  isApplySingleOption?: boolean
  isRefreshWithReset?: boolean
}
 
export const SelectWithQuery = <R extends CollectionResponse, P extends QueryParams<R>>({
  type = 'selectSearch',
  subType = 'text',
  dependentEntities,
  dependentEntityType,
  labelKey = 'name',
  valueKey = '@id',
  transformLabel,
  params = {} as P,
  source,
  error,
  useQuery,
  onChangeWithOptions,
  additionalFields,
  validate,
  disableOnEmptyOptions,
  isLoading,
  loadingOnMount = true,
  isApplySingleOption,
  disableIfEmptyDependentEntities = true,
  isRefreshWithReset,
  ...rest
}: SelectWithQueryProps<R, P>) => {
  const [searchValue, setSearchValue] = useState('')
  const [isNeedLoading, setIsNeedLoading] = useState(() => loadingOnMount)
  const [singleOption, setSingleOption] = useState<Nullable<string>>(null)
 
  const dependentEntitiesIds =
    dependentEntities &&
    Object.values(dependentEntities).reduce<string[]>((acc, entity) => {
      if (entity && typeof entity !== 'boolean') {
        acc.push(normalizeDependentEntityValue(entity))
      }
      if (typeof entity === 'boolean') {
        acc.push(String(entity))
      }
      return acc
    }, [])
 
  const debouncedOnSearch = useCallback(debounce(setSearchValue, 300), [])
  const transoformLabelFn = useCallback(transformLabel as TransformLabel<R>, [])
 
  const isSelectSearch = type === 'selectSearch'
 
  const disabled =
    ((dependentEntitiesIds && !dependentEntitiesIds.length) || rest.disabled) && disableIfEmptyDependentEntities
  const queryParams = {
    enabled: !disabled && isNeedLoading,
    keepPreviousData: true,
    refetchOnMount: false,
    retry: 3,
    ...params,
    filters: {
      ...((isSelectSearch || type === 'multiSelect') && { [labelKey]: searchValue }),
      ...(dependentEntityType === 'filter' &&
        dependentEntities &&
        Object.keys(dependentEntities).reduce(
          (acc, key, index) => ({ ...acc, [key]: dependentEntitiesIds?.[index] }),
          {}
        )),
      page: 1,
      itemsPerPage: 100,
      ...params.filters,
    },
    key: ['refetch-manualy', dependentEntitiesIds],
  }
 
  const {
    data,
    isLoading: isOptionLoading,
    isRefetching,
    refetch,
  } = dependentEntityType === 'id'
    ? (useQuery as DependentQueryWithCollectionResponse<R, P>)(dependentEntitiesIds?.[0] || '', queryParams)
    : (useQuery as QueryWithCollectionResponse<R, P>)(queryParams)
  const options = useMemo(
    () =>
      normalizeSelectOptions(
        data?.['hydra:member'],
        { labelKey: transoformLabelFn || labelKey, valueKey, validate },
        additionalFields
      ),
    [data, labelKey, valueKey, transoformLabelFn, validate]
  )
 
  const getSelectProps = (error?: FieldError) => ({
    options,
    isLoading: isLoading || isOptionLoading || isRefetching,
    inputProps: {
      ...rest.inputProps,
      error,
      type: subType,
      ...(dependentEntitiesIds?.length && { resetTrigger: JSON.stringify(dependentEntitiesIds) }),
    },
    disabled: (disableOnEmptyOptions && !options.length) || disabled,
  })
 
  const onChange = (value?: Nullable<string | number> | Nullable<string[]>) => {
    if (onChangeWithOptions) {
      type === 'multiSelect' && Array.isArray(value)
        ? onChangeWithOptions(value.map((item: string) => options.find(option => option.id === item) as SelectOption))
        : onChangeWithOptions(value === null ? value : options.find(option => option.id === value))
    }
    rest.onChange?.(value as string)
  }
  useEffect(() => {
    isApplySingleOption && setIsNeedLoading(true)
  }, [])
 
  useEffect(() => {
    if (isApplySingleOption && options.length === 1) {
      if (options[0]?.id !== singleOption) onChange(options[0]?.id)
      setSingleOption(options[0]?.id)
    }
  }, [data])
 
  if (type === 'multiSelect') {
    return (
      <MultiSelect
        {...getSelectProps(error)}
        {...rest}
        defaultValue={rest.value}
        onChange={onChange}
        onOpen={() => setIsNeedLoading(true)}
        value={rest.value as string[]}
        onCustomSearch={debouncedOnSearch}
      />
    )
  }
  return isSelectSearch ? (
    <SelectSearch
      {...getSelectProps(error)}
      {...rest}
      customSelectOptionValuekey={labelKey}
      source={source}
      {...(dependentEntities && {
        dependentField: dependentEntities,
      })}
      onSearch={debouncedOnSearch}
      onChange={value => onChange(value as Nullable<string>)}
      onOpen={() => setIsNeedLoading(true)}
      value={rest.value as string}
      {...(isRefreshWithReset && { onCustomReset: () => refetch() })}
    />
  ) : (
    <Select {...getSelectProps(error)} {...rest} onChange={onChange} />
  )
}