All files / src/components/MultiSelect index.tsx

73.07% Statements 19/26
52.27% Branches 23/44
90% Functions 9/10
70.83% Lines 17/24

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                                                                                                        5x   5x   5x 2x   2x         5x 3x         5x                           13x   5x   1x   1x         1x   5x                                                                     6x   6x 1x                                                  
import React, { useEffect, useState } from 'react';
import './styles.scss';
import IconTooltip from '../IconTooltip';
import { Box, SxProps, TooltipProps } from '@mui/material';
import Icon from '../Icon/Icon';
import PillList, { PillListItem } from '../PillList';
 
export type MultiSelectProps<K, V> = {
  className?: string;
  disabled?: boolean;
  fullWidth?: boolean;
  helperText?: string;
  errorText?: string;
  id?: string;
  label?: string;
  missingValuePlaceholder?: string;
  onAdd: (item: K) => void;
  onBlur?: () => void;
  onFocus?: () => void;
  onPillClick?: (item: K) => void;
  onRemove: (item: K) => void;
  options: Map<K, V>;
  optionsVisible?: boolean;
  pillListClassName?: string;
  placeHolder?: string;
  selectedOptions: K[];
  sx?: SxProps;
  tooltipTitle?: TooltipProps['title'];
  valueRenderer: (value: V) => string;
};
 
export default function MultiSelect<K, V>(props: MultiSelectProps<K, V>): JSX.Element {
  const {
    className,
    disabled,
    fullWidth,
    helperText,
    errorText,
    id,
    label,
    missingValuePlaceholder,
    onAdd,
    onRemove,
    onPillClick,
    options,
    optionsVisible,
    pillListClassName,
    placeHolder,
    selectedOptions,
    sx,
    tooltipTitle,
    valueRenderer,
  } = props;
 
  const [openedOptions, setOpenedOptions] = useState(false);
 
  const toggleOptions = () => {
    setOpenedOptions((isOpen) => !isOpen && !disabled);
 
    Iif (props.onFocus) {
      props.onFocus();
    }
  };
 
  useEffect(() => {
    Iif (optionsVisible !== undefined) {
      setOpenedOptions(optionsVisible);
    }
  }, [optionsVisible]);
 
  const onBlurHandler = (event: any) => {
    // In Chrome > 126, the onBlur event will fire even if you are clicking _within_ the focused element
    // If this is the case, we do not actually want to blur
    if (event.currentTarget.contains(event.relatedTarget)) {
      return;
    }
 
    setOpenedOptions(false);
 
    if (props.onBlur) {
      props.onBlur();
    }
  };
 
  const unselectedOptions = Array.from<K>(options.keys()).filter((key: K) => !selectedOptions.includes(key));
 
  const valuesPillData = selectedOptions
    .map((item) => {
      const value = options.get(item);
 
      return {
        id: item,
        value: value ? valueRenderer(value) : missingValuePlaceholder || '',
      };
    })
    .filter((data) => data.value) as PillListItem<K>[];
 
  return (
    <Box className={`multi-select ${className}`} sx={sx}>
      {label && (
        <label htmlFor={id} className='multi-select__label'>
          {label} {tooltipTitle && <IconTooltip title={tooltipTitle} />}
        </label>
      )}
      <div
        className={`multi-select__container ${fullWidth ? 'multi-select__container--fullWidth' : ''}`}
        onBlur={onBlurHandler}
        tabIndex={0}
      >
        <div
          id={id}
          className={`multi-select__values${disabled ? '--disabled' : ''}${openedOptions ? ' open' : ''}${
            errorText ? ' error' : ''
          }`}
          onClick={toggleOptions}
        >
          {selectedOptions.length > 0 ? (
            <PillList data={valuesPillData} onRemove={onRemove} onClick={onPillClick} className={pillListClassName} />
          ) : (
            <p className='multi-select__placeholder-text'>{placeHolder}</p>
          )}
          <div className={'multi-select__values__icon-button'} aria-label='show-options'>
            <Icon
              name={openedOptions ? 'chevronUp' : 'chevronDown'}
              className={`multi-select__values__icon-right${disabled ? '--disabled' : ''}`}
            />
          </div>
        </div>
        {options && unselectedOptions.length > 0 && openedOptions && (
          <div className='multi-select__options-container'>
            <ul className={'multi-select__options'}>
              {unselectedOptions.map((optionKey, index) => {
                const optionValue = options.get(optionKey);
 
                return (
                  <li key={index} className='select-value' onClick={() => onAdd(optionKey)}>
                    {optionValue ? valueRenderer(optionValue) : missingValuePlaceholder || ''}
                  </li>
                );
              })}
            </ul>
          </div>
        )}
      </div>
      {helperText && (
        <label htmlFor={id} className='multi-select__help-text'>
          {helperText}
        </label>
      )}
      {errorText && (
        <div className='multi-select__error'>
          <Icon name='error' className='multi-select__error-icon' />
          <label htmlFor={id} className='multi-select__error-text'>
            {errorText}
          </label>
        </div>
      )}
    </Box>
  );
}