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

78.33% Statements 47/60
52.38% Branches 11/21
66.66% Functions 16/24
81.81% Lines 45/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         1x           1x 10x     1x             10x         10x 10x   10x 10x   10x 10x     10x 10x       10x 10x               10x 1x 1x     10x 1x 1x   1x 1x     10x 1x     10x       10x               10x   10x 10x   4x   4x 7x 5x           2x 2x 2x 2x   2x 1x     1x         10x 7x     10x                                      
import { useCallback, useEffect, useMemo, useState } from 'react';
 
import { SharedEmployee } from '@repo/hooks/userQueries';
 
import { mapSelectedEmployees } from '@repo/utils/user';
 
import {
  useReallocationV2ActionsSelector,
  useReallocationV2StateSelector,
} from '../../ReallocationV2/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 } = useReallocationV2StateSelector(state => ({
    form: state.form,
    isSearchOpen: state.isSearchOpen,
  }));
 
  const toggleObserver = useReallocationV2ActionsSelector(
    actions => actions.toggleObserver,
  );
  const toggleSearch = useReallocationV2ActionsSelector(
    actions => actions.toggleSearch,
  );
  const closeSearch = useReallocationV2ActionsSelector(
    actions => actions.closeSearch,
  );
 
  const [searchValue, setSearchValue] = useState('');
  const [availableObservers, setAvailableObservers] = useState<string[]>(
    mergeUniqueIds(form.observers, defaultObservers),
  );
 
  useEffect(() => {
    Iif (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,
    },
  };
};