All files / src/pages UserProfilePage.tsx

91.22% Statements 52/57
77.5% Branches 31/40
66.66% Functions 8/12
100% Lines 51/51

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 166 167 168                1x 33x 33x 33x 33x   33x   33x 13x 10x       33x 2x   2x 2x 2x 1x 1x   1x 1x 1x 1x   1x 1x 1x       33x   1x     33x 3x 3x   2x 2x 2x 2x 1x 1x   1x 1x 1x   1x 1x 1x   2x       33x 1x     32x 1x     31x 1x     30x                                                                                     2x                     1x                   3x                                          
// src/pages/UserProfilePage.tsx
import React, { useState, useEffect, useRef } from 'react';
import * as apiClient from '../services/apiClient';
import { logger } from '../services/logger.client';
import { notifySuccess, notifyError } from '../services/notificationService';
import { AchievementsList } from '../components/AchievementsList';
import { useUserProfileData } from '../hooks/useUserProfileData';
 
const UserProfilePage: React.FC = () => {
  const { profile, setProfile, achievements, isLoading, error } = useUserProfileData();
  const [isEditingName, setIsEditingName] = useState(false);
  const [editingName, setEditingName] = useState('');
  const [isUploading, setIsUploading] = useState(false);
 
  const fileInputRef = useRef<HTMLInputElement>(null);
 
  useEffect(() => {
    if (profile) {
      setEditingName(profile.full_name || '');
    }
  }, [profile]);
 
  const handleSaveName = async () => {
    Iif (!profile) return;
 
    try {
      const response = await apiClient.updateUserProfile({ full_name: editingName });
      if (!response.ok) {
        const errorData = await response.json().catch(() => null); // Gracefully handle non-JSON responses
        throw new Error(errorData?.message || 'Failed to update name.');
      }
      const updatedProfile = await response.json();
      setProfile((prevProfile) => (prevProfile ? { ...prevProfile, ...updatedProfile } : null));
      notifySuccess('Name updated successfully!');
      setIsEditingName(false);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred.';
      notifyError(errorMessage);
      logger.error({ err }, 'Error saving user name:');
    }
  };
 
  const handleAvatarClick = () => {
    // Programmatically click the hidden file input
    fileInputRef.current?.click();
  };
 
  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
 
    setIsUploading(true);
    try {
      const response = await apiClient.uploadAvatar(file);
      if (!response.ok) {
        const errorData = await response.json().catch(() => null); // Gracefully handle non-JSON responses
        throw new Error(errorData?.message || 'Failed to upload avatar.');
      }
      const updatedProfile = await response.json();
      setProfile((prevProfile) => (prevProfile ? { ...prevProfile, ...updatedProfile } : null));
      notifySuccess('Avatar updated successfully!');
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'An unknown error occurred.';
      notifyError(errorMessage);
      logger.error({ err }, 'Error uploading avatar:');
    } finally {
      setIsUploading(false);
    }
  };
 
  if (isLoading) {
    return <div className="p-6 text-center">Loading profile...</div>;
  }
 
  if (error) {
    return <div className="p-6 text-center text-red-500">Error: {error}</div>;
  }
 
  if (!profile) {
    return <div className="p-6 text-center">Could not load user profile.</div>;
  }
 
  return (
    <div className="p-4 md:p-8 max-w-4xl mx-auto">
      {/* Profile Header */}
      <div className="flex items-center space-x-6 mb-8">
        <div className="relative group">
          <img
            src={
              profile.avatar_url ||
              `https://api.dicebear.com/8.x/initials/svg?seed=${profile.full_name || profile.user.email}`
            }
            alt="User Avatar"
            className="w-24 h-24 rounded-full object-cover shadow-lg cursor-pointer transition-opacity group-hover:opacity-70"
            onClick={handleAvatarClick}
          />
          <div
            className="absolute inset-0 bg-black bg-opacity-50 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
            onClick={handleAvatarClick}
          >
            <span className="text-white text-sm font-semibold">Change</span>
          </div>
          {isUploading && (
            <div
              data-testid="avatar-upload-spinner"
              className="absolute inset-0 bg-black bg-opacity-70 rounded-full flex items-center justify-center"
            >
              <div className="w-8 h-8 border-4 border-t-transparent border-white rounded-full animate-spin"></div>
            </div>
          )}
        </div>
        <input
          type="file"
          ref={fileInputRef}
          onChange={handleFileChange}
          className="hidden"
          data-testid="avatar-file-input"
          accept="image/png, image/jpeg, image/gif"
        />
        <div>
          {isEditingName ? (
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={editingName}
                onChange={(e) => setEditingName(e.target.value)}
                className="text-3xl font-bold p-1 border rounded dark:bg-gray-700 dark:border-gray-600"
                autoFocus
              />
              <button
                onClick={handleSaveName}
                className="bg-green-500 hover:bg-green-600 text-white font-bold py-1 px-3 rounded"
              >
                Save
              </button>
              <button
                onClick={() => setIsEditingName(false)}
                className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-1 px-3 rounded"
              >
                Cancel
              </button>
            </div>
          ) : (
            <div className="flex items-center gap-4">
              <h1 className="text-3xl font-bold">{profile.full_name || 'User Profile'}</h1>
              <button
                onClick={() => setIsEditingName(true)}
                className="text-sm text-blue-500 hover:underline"
              >
                Edit
              </button>
            </div>
          )}
          <p className="text-gray-500 dark:text-gray-400">{profile.user.email}</p>
          <div className="mt-2 bg-blue-100 text-blue-800 text-lg font-bold px-4 py-1 rounded-full inline-block">
            {profile.points} Points
          </div>
        </div>
      </div>
 
      {/* Achievements Section */}
      <AchievementsList achievements={achievements} />
    </div>
  );
};
 
export default UserProfilePage;