All files / src/components/shared UserAutocomplete.tsx

3.33% Statements 1/30
0% Branches 0/29
0% Functions 0/13
3.7% Lines 1/27

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                                                                  4x                                                                                                                                                                                                                                                                      
/**
 * UserAutocomplete Component (Story 5.5)
 *
 * Autocomplete component for searching and selecting users
 * Features:
 * - Debounced search (300ms)
 * - Min 2 characters to trigger search
 * - Filter by role
 * - Display user name, email, and company
 * - Loading states
 * - Error handling
 */
 
import React, { useState, useCallback } from 'react';
import { Autocomplete, TextField, CircularProgress, Box, Typography } from '@mui/material';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { searchUsers } from '@/services/api/userManagementApi';
import { UserAvatar } from '@/components/shared/UserAvatar';
import type { UserSearchResponse } from '@/types/user.types';
import { useDebounce } from '@/hooks/useDebounce';
 
interface UserAutocompleteProps {
  value: UserSearchResponse | null;
  onChange: (user: UserSearchResponse | null) => void;
  error?: string;
  disabled?: boolean;
  label?: string;
  role?: string; // Filter by role (e.g., 'SPEAKER')
  inputRef?: React.Ref<HTMLInputElement>;
  'data-testid'?: string; // Test ID for E2E tests
}
 
export const UserAutocomplete: React.FC<UserAutocompleteProps> = ({
  value,
  onChange,
  error,
  disabled = false,
  label,
  role,
  inputRef,
  'data-testid': testId,
}) => {
  const { t } = useTranslation('common');
  const [inputValue, setInputValue] = useState('');
  const debouncedInputValue = useDebounce(inputValue, 300);
 
  // Sync inputValue when value prop changes
  React.useEffect(() => {
    if (value) {
      setInputValue(value.id); // id is the username
    } else {
      setInputValue('');
    }
  }, [value]);
 
  // Only search if input is at least 2 characters
  const isValueSelected = value && debouncedInputValue === value.id;
  const shouldSearch = debouncedInputValue.length >= 2 && !isValueSelected;
 
  // Query for user search
  const {
    data: users = [],
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['users', 'search', debouncedInputValue, role],
    queryFn: async () => {
      const allUsers = await searchUsers(debouncedInputValue, 20);
      // Filter by role if specified
      return role ? allUsers.filter((u) => u.roles?.includes(role)) : allUsers;
    },
    enabled: shouldSearch,
  });
 
  // Ensure selected value is always in options for MUI Autocomplete
  const optionsWithValue = React.useMemo(() => {
    if (!value) return users;
    // Check if value is already in users array
    const valueExists = users.some((u) => u.id === value.id);
    return valueExists ? users : [value, ...users];
  }, [users, value]);
 
  const handleInputChange = useCallback((_event: React.SyntheticEvent, newInputValue: string) => {
    setInputValue(newInputValue);
  }, []);
 
  return (
    <Autocomplete
      value={value}
      onChange={(_event, newValue) => {
        onChange(newValue);
      }}
      inputValue={inputValue}
      onInputChange={handleInputChange}
      options={optionsWithValue}
      getOptionLabel={(option) => option.id} // id is the username
      isOptionEqualToValue={(option, value) => option.id === value.id}
      disabled={disabled}
      loading={isLoading}
      filterOptions={(x) => x} // Server-side filtering
      noOptionsText={
        isError
          ? t('Error loading users')
          : inputValue.length < 2
            ? t('Type at least 2 characters')
            : role
              ? t(`No users found with role ${role}`)
              : t('No users found')
      }
      renderInput={(params) => (
        <TextField
          {...params}
          label={label || t('User')}
          error={!!error}
          helperText={error}
          inputRef={inputRef}
          inputProps={{
            ...params.inputProps,
            'data-testid': testId,
          }}
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {isLoading ? <CircularProgress color="inherit" size={20} /> : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      )}
      renderOption={(props, option) => {
        const { key, ...otherProps } = props;
        return (
          <Box component="li" key={key} {...otherProps} data-testid={`user-option-${option.id}`}>
            <UserAvatar
              firstName={option.firstName}
              lastName={option.lastName}
              company={option.companyId}
              profilePictureUrl={option.profilePictureUrl}
              size={32}
              showCompany={false}
            />
            <Box sx={{ ml: 1, flex: 1 }}>
              {option.email && (
                <Typography variant="body2" color="text.secondary">
                  {option.email}
                </Typography>
              )}
              {option.roles && option.roles.length > 0 && (
                <Typography variant="caption" color="text.secondary">
                  Role: {option.roles.join(', ')}
                </Typography>
              )}
            </Box>
          </Box>
        );
      }}
    />
  );
};
 
export default UserAutocomplete;