All files / src/components/PopoverMultiSelect index.tsx

0% Statements 0/23
0% Branches 0/4
0% Functions 0/8
0% Lines 0/21

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                                                                                                                               
import React, { useState } from 'react';
import { ListItemText } from '@mui/material';
import { DropdownItem } from '../types';
import Icon from '../Icon/Icon';
import './styles.scss';
import Popover, { Section } from '../PopoverMenu/Popover';
 
export type PopoverMultiSelectProps = {
  anchorElement: HTMLElement | null;
  initialSelection: any[];
  menuAlign?: 'left' | 'center' | 'right';
  onChange: (selection: any[]) => void;
  sections: Section[];
  setAnchorElement: (anchorEl: HTMLElement | null) => void;
};
 
export default function PopoverMultiSelect(props: PopoverMultiSelectProps): JSX.Element {
  const { anchorElement, initialSelection, menuAlign, onChange, sections, setAnchorElement } = props;
  const [selection, setSelection] = useState(initialSelection);
  const addToSelection = (value: DropdownItem) => {
    const newSelection = [...selection];
    newSelection.push(value);
    setSelection(newSelection);
    onChange(newSelection);
  };
  const removeFromSelection = (index: number) => {
    const newSelection = [...selection];
    newSelection.splice(index, 1);
    setSelection(newSelection);
    onChange(newSelection);
  };
 
  const iconSpacer = () => {
    return <div className='popover-multi-select__checkmark-spacer' />;
  };
 
  return (
    <Popover
      sections={sections}
      handleClick={(item) => {
        const itemIndex = selection.findIndex((s) => s === item.value);
        if (itemIndex >= 0) {
          removeFromSelection(itemIndex);
        } else {
          addToSelection(item.value);
        }
      }}
      anchorElement={anchorElement}
      setAnchorElement={setAnchorElement}
      itemRenderer={(item) => {
        const selected = selection.find((s) => s === item.value);
 
        return (
          <>
            {selected ? <Icon name='checkmark' className='popover-multi-select__checkmark-selection' /> : iconSpacer()}
            <ListItemText>{item.label}</ListItemText>
          </>
        );
      }}
      menuAlign={menuAlign}
    />
  );
}