All files / components/MultiSelect index.tsx

85.71% Statements 48/56
65.07% Branches 41/63
92.3% Functions 12/13
85.45% Lines 47/55

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                  1x 1x   1x 5x   20x       5x                                                                                                   18x   18x 18x 18x 18x   18x 5x 5x       5x 5x 5x 5x 5x 5x   5x                 18x 6x   6x         18x 7x         26x 18x   18x 13x 9x     4x 4x 4x 4x 4x 4x     4x 4x 4x 4x       18x                           18x   1x   1x         1x   18x                                                                                                                                      
import React, { CSSProperties, type JSX, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
 
import { Box, SxProps, TooltipProps } from '@mui/material';
 
import Icon from '../Icon/Icon';
import IconTooltip from '../IconTooltip';
import PillList, { PillListItem } from '../PillList';
import './styles.scss';
 
const OPTIONS_MAX_HEIGHT = 140;
const VIEWPORT_MARGIN = 8;
 
const getVerticalFrameHeight = (element: HTMLElement) => {
  const style = getComputedStyle(element);
  const spacing = [style.paddingTop, style.paddingBottom, style.marginTop, style.marginBottom].reduce(
    (total, value) => total + (parseFloat(value) || 0),
    0
  );
 
  return element.offsetHeight - element.clientHeight + spacing;
};
 
export type MultiSelectProps<K, V> = {
  className?: string;
  disabled?: boolean;
  fullWidth?: boolean;
  helperText?: string;
  errorText?: string;
  fixedMenu?: boolean;
  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,
    fixedMenu,
    id,
    label,
    missingValuePlaceholder,
    onAdd,
    onRemove,
    onPillClick,
    options,
    optionsVisible,
    pillListClassName,
    placeHolder,
    selectedOptions,
    sx,
    tooltipTitle,
    valueRenderer,
  } = props;
 
  const [openedOptions, setOpenedOptions] = useState(false);
  const [fixedMenuStyle, setFixedMenuStyle] = useState<CSSProperties>();
  const optionsContainerRef = useRef<HTMLDivElement>(null);
  const optionsRef = useRef<HTMLUListElement>(null);
 
  const positionFixedMenu = useCallback(() => {
    const trigger = optionsContainerRef.current?.parentElement;
    Iif (!optionsContainerRef.current || !trigger) {
      return;
    }
 
    const { top, left, width } = optionsContainerRef.current.getBoundingClientRect();
    const triggerTop = trigger.getBoundingClientRect().top;
    const spaceBelow = window.innerHeight - top - VIEWPORT_MARGIN;
    const spaceAbove = triggerTop - VIEWPORT_MARGIN;
    const placeAbove = spaceBelow < OPTIONS_MAX_HEIGHT && spaceAbove > spaceBelow;
    const menuFrameHeight = optionsRef.current ? getVerticalFrameHeight(optionsRef.current) : 0;
 
    setFixedMenuStyle({
      position: 'fixed',
      left,
      width: width - 2,
      maxHeight: Math.max(0, Math.min(OPTIONS_MAX_HEIGHT, (placeAbove ? spaceAbove : spaceBelow) - menuFrameHeight)),
      ...(placeAbove ? { top: 'auto', bottom: window.innerHeight - triggerTop } : { top }),
    });
  }, []);
 
  const toggleOptions = () => {
    setOpenedOptions((isOpen) => !isOpen && !disabled);
 
    Iif (props.onFocus) {
      props.onFocus();
    }
  };
 
  useEffect(() => {
    Iif (optionsVisible !== undefined) {
      setOpenedOptions(optionsVisible);
    }
  }, [optionsVisible]);
 
  const unselectedOptions = Array.from<K>(options.keys()).filter((key: K) => !selectedOptions.includes(key));
  const optionsShown = options && unselectedOptions.length > 0 && openedOptions;
 
  useLayoutEffect(() => {
    if (!fixedMenu || !optionsShown) {
      return;
    }
 
    positionFixedMenu();
    window.addEventListener('scroll', positionFixedMenu, true);
    window.addEventListener('resize', positionFixedMenu);
    const triggerObserver = new ResizeObserver(positionFixedMenu);
    Eif (optionsContainerRef.current?.parentElement) {
      triggerObserver.observe(optionsContainerRef.current.parentElement);
    }
 
    return () => {
      window.removeEventListener('scroll', positionFixedMenu, true);
      window.removeEventListener('resize', positionFixedMenu);
      triggerObserver.disconnect();
    };
  }, [fixedMenu, optionsShown, positionFixedMenu]);
 
  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 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>
        {optionsShown && (
          <div className='multi-select__options-container' ref={optionsContainerRef}>
            <ul
              className={`multi-select__options${fixedMenu && fixedMenuStyle?.bottom !== undefined ? ' multi-select__options--above' : ''}`}
              ref={optionsRef}
              style={fixedMenu ? fixedMenuStyle : undefined}
            >
              {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>
  );
}