select-user-checkbox.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { useTranslation } from 'react-i18next'
  2. import type { User } from '../../../../../../types/group-management/user'
  3. import { useGroupMembersContext } from '../../context/group-members-context'
  4. import { useCallback } from 'react'
  5. import OLFormCheckbox from '@/features/ui/components/ol/ol-form-checkbox'
  6. type ManagedUsersSelectUserCheckboxProps = {
  7. user: User
  8. }
  9. export default function SelectUserCheckbox({
  10. user,
  11. }: ManagedUsersSelectUserCheckboxProps) {
  12. const { t } = useTranslation()
  13. const { users, selectedUsers, selectUser, unselectUser } =
  14. useGroupMembersContext()
  15. const handleSelectUser = useCallback(
  16. (event: React.ChangeEvent<HTMLInputElement>, user: User) => {
  17. if (event.target.checked) {
  18. selectUser(user)
  19. } else {
  20. unselectUser(user)
  21. }
  22. },
  23. [selectUser, unselectUser]
  24. )
  25. // Pending: user.enrollment will be `undefined`
  26. // Non managed: user.enrollment will be an empty object
  27. const nonManagedUsers = users.filter(user => !user.enrollment?.managedBy)
  28. // Hide the entire `td` (entire column) if no more users available to be click
  29. // because all users are currently managed
  30. if (nonManagedUsers.length === 0) {
  31. return null
  32. }
  33. const selected = selectedUsers.includes(user)
  34. return (
  35. <td className="cell-checkbox">
  36. {/* the next check will hide the `checkbox` but still show the `th` */}
  37. {user.enrollment?.managedBy ? null : (
  38. <OLFormCheckbox
  39. autoComplete="off"
  40. checked={selected}
  41. onChange={e => handleSelectUser(e, user)}
  42. aria-label={t('select_user')}
  43. data-testid="select-single-checkbox"
  44. />
  45. )}
  46. </td>
  47. )
  48. }