All files / components/relations-list index.tsx

100% Statements 26/26
100% Branches 16/16
100% Functions 9/9
100% Lines 24/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                          4x       6x   6x 5x 9x   9x   9x   9x       6x 1x   6x 5x   5x 5x       6x 5x     6x           9x   8x 10x   8x 8x   8x       8x                          
import { useEffect, useState, useMemo } from 'react';
 
import { CardList, CardListProps, RelationsListFilter } from 'components';
import { events } from 'app';
 
import { Entities, Entity, Events } from 'types';
import * as S from './styles';
 
export type RelationsListProps = {
  relations?: CardListProps['items'];
  filter?: boolean;
};
 
const RelationsList = ({
  relations = [],
  filter = true,
}: RelationsListProps) => {
  const [filterBy, setFilterBy] = useState('');
 
  const entities = useMemo(() => {
    return relations.reduce((obj, item) => {
      const key = item.entity;
 
      const entities = obj[key] || [];
 
      obj[key] = [...entities, item];
 
      return obj;
    }, {} as Record<Entities, (Entity & { empty?: boolean })[]>);
  }, []);
 
  const handleFilter = (event: CustomEvent<string>) =>
    setFilterBy(event.detail);
 
  useEffect(() => {
    events.on(Events.RELATIONS_FILTER, handleFilter);
 
    return () => {
      events.off(Events.RELATIONS_FILTER, handleFilter);
    };
  }, []);
 
  useEffect(() => {
    events.relations['set.options'](Object.keys(entities));
  }, [entities, filter]);
 
  return relations.length ? (
    <S.Container>
      {filter && <RelationsListFilter />}
 
      <S.Wrapper>
        {Object.entries(entities).map(([key, items]) => {
          if (!!filterBy && key !== filterBy) return null;
 
          const total = items.length;
          const emptyCount = items.filter(item => !!item.empty).length;
 
          const hasEmpty = !!emptyCount;
          const finded = items.length - emptyCount;
 
          const label = `${key} (${
            hasEmpty && finded ? `${finded}/` : ''
          }${total})`;
 
          return (
            <S.Box key={key}>
              <S.Label>{label}</S.Label>
              <CardList items={items} />
            </S.Box>
          );
        })}
      </S.Wrapper>
    </S.Container>
  ) : null;
};
 
export { RelationsList };