All files / apps/reallocation/src/screens/ChooseObserver/hooks useObserverSelection.ts

100% Statements 60/60
85.71% Branches 18/21
100% Functions 24/24
100% Lines 55/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                      1x 4x 4x     1x 2x 1x       1x 25x     1x             21x         21x 21x   21x 21x   21x 21x     21x 21x       21x 19x 4x 4x 4x         21x 1x 1x     21x 2x 2x   2x 2x     21x 2x     21x 1x     21x   2x 2x         21x   21x 21x   4x   4x 7x 5x           2x 2x 2x 2x   2x 1x     1x         21x 18x     21x                                      
import { useCallback, useEffect, useMemo, useState } from 'react';
 
import { SharedEmployee } from '@repo/hooks/useUserQueries';
 
import { mapSelectedEmployees } from '@repo/utils/user';
 
import {
  useReallocationActionsSelector,
  useReallocationStateSelector,
} from '../../Reallocation/context';
 
const areSameIdList = (left: string[], right: string[]) => {
  if (left.length !== right.length) return false;
  return left.every((value, index) => value === right[index]);
};
 
const toggleIdInList = (items: string[], id: string) => {
  return items.includes(id)
    ? items.filter(item => item !== id)
    : [...items, id];
};
 
const mergeUniqueIds = (...groups: string[][]) => {
  return Array.from(new Set(groups.flat()));
};
 
export const useObserverSelection = ({
  employees,
  defaultObservers = [],
}: {
  employees: SharedEmployee[];
  defaultObservers?: string[];
}) => {
  const { form, isSearchOpen } = useReallocationStateSelector(state => ({
    form: state.form,
    isSearchOpen: state.isSearchOpen,
  }));
 
  const toggleObserver = useReallocationActionsSelector(
    actions => actions.toggleObserver,
  );
  const toggleSearch = useReallocationActionsSelector(
    actions => actions.toggleSearch,
  );
  const closeSearch = useReallocationActionsSelector(
    actions => actions.closeSearch,
  );
 
  const [searchValue, setSearchValue] = useState('');
  const [availableObservers, setAvailableObservers] = useState<string[]>(
    mergeUniqueIds(form.observers, defaultObservers),
  );
 
  useEffect(() => {
    if (defaultObservers.length > 0) {
      setAvailableObservers(prev => {
        const next = mergeUniqueIds(defaultObservers);
        return areSameIdList(prev, next) ? prev : next;
      });
    }
  }, [defaultObservers]);
 
  const openSearch = useCallback(() => {
    setSearchValue('');
    toggleSearch();
  }, [toggleSearch]);
 
  const syncAvailableSelections = useCallback(() => {
    setAvailableObservers(prev =>
      Array.from(new Set([...prev, ...form.observers])),
    );
    setSearchValue('');
    closeSearch();
  }, [closeSearch, form.observers]);
 
  const handleSearchComplete = useCallback(() => {
    syncAvailableSelections();
  }, [syncAvailableSelections]);
 
  const handleSubmitSearchInput = useCallback(() => {
    handleSearchComplete();
  }, [handleSearchComplete]);
 
  const handleToggleAvatarInSearchMode = useCallback(
    (id: string) => {
      setAvailableObservers(prev => toggleIdInList(prev, id));
      toggleObserver(id);
    },
    [toggleObserver],
  );
 
  const searchSelectedIds = form.observers;
 
  const employeesFormatted = useMemo(() => {
    if (!searchValue) return [];
 
    const normalizedSearch = searchValue.toLowerCase();
 
    return employees
      .filter(emp => emp.name?.toLowerCase().includes(normalizedSearch))
      .map(emp => ({
        id: emp.id || '',
        name: emp.name || '',
        uri: emp.avatar || '',
      }))
      .sort((left, right) => {
        const leftName = left.name.toLowerCase();
        const rightName = right.name.toLowerCase();
        const leftStarts = leftName.startsWith(normalizedSearch);
        const rightStarts = rightName.startsWith(normalizedSearch);
 
        if (leftStarts !== rightStarts) {
          return leftStarts ? -1 : 1;
        }
 
        return leftName.localeCompare(rightName);
      })
      .slice(0, 8);
  }, [employees, searchValue]);
 
  const observersFormatted = useMemo(() => {
    return mapSelectedEmployees(availableObservers, employees);
  }, [availableObservers, employees]);
 
  return {
    state: {
      form,
      isSearchOpen,
      searchValue,
      searchSelectedIds,
      employeesFormatted,
      observersFormatted,
    },
    actions: {
      setSearchValue,
      openSearch,
      handleSearchComplete,
      handleToggleAvatarInSearchMode,
      handleSubmitSearchInput,
      toggleObserver,
    },
  };
};