feat: avatar upload for profile/chats, fix session persistence on refresh

- Profile modal: upload/remove user avatar, edit name/bio/phone, change password
- Chat info panel: upload/remove chat photo (owner/admin only)
- Avatar component: render photo when available, fallback to initials
- Session fix: initialize Zustand store from localStorage to prevent redirect on refresh
- Backend: avatar upload endpoints for users and chats, migration adds avatar columns

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Ai
2026-05-22 11:55:11 +03:00
parent 01331d0263
commit 3f54dbf375
9 changed files with 421 additions and 45 deletions

View File

@@ -1,9 +1,11 @@
interface Props {
name: string;
color: string;
avatar?: string | null;
size?: 'sm' | 'md' | 'lg' | 'xl';
online?: boolean;
className?: string;
onClick?: () => void;
}
const sizes = {
@@ -13,21 +15,46 @@ const sizes = {
xl: 'w-16 h-16 text-xl',
};
export default function Avatar({ name, color, size = 'md', online, className = '' }: Props) {
const initials = name.split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase();
const dotSizes = {
sm: 'w-2.5 h-2.5',
md: 'w-3 h-3',
lg: 'w-3.5 h-3.5',
xl: 'w-4 h-4',
};
export default function Avatar({ name, color, avatar, size = 'md', online, className = '', onClick }: Props) {
const initials = name
? name.split(' ').map(w => w[0]).filter(Boolean).slice(0, 2).join('').toUpperCase()
: '?';
const apiBase = import.meta.env.VITE_API_URL || '';
// Prepend API base URL to relative paths
const avatarUrl = avatar
? (avatar.startsWith('http') ? avatar : `${apiBase}${avatar}`)
: null;
return (
<div className={`relative flex-shrink-0 ${className}`}>
<div
className={`${sizes[size]} rounded-full flex items-center justify-center font-semibold text-white select-none`}
style={{ backgroundColor: color }}
>
{initials}
</div>
<div className={`relative flex-shrink-0 ${className}`} onClick={onClick}>
{avatarUrl ? (
<img
src={avatarUrl}
alt={name}
className={`${sizes[size]} rounded-full object-cover`}
onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
/>
) : (
<div
className={`${sizes[size]} rounded-full flex items-center justify-center font-semibold text-white select-none`}
style={{ backgroundColor: color }}
>
{initials}
</div>
)}
{online !== undefined && (
<div className={`absolute bottom-0 right-0 rounded-full border-2 border-white ${
online ? 'bg-green-400' : 'bg-gray-300'
} ${size === 'sm' ? 'w-2.5 h-2.5' : 'w-3 h-3'}`} />
} ${dotSizes[size]}`} />
)}
</div>
);

View File

@@ -1,5 +1,5 @@
import { X, UserPlus, Crown, Shield, User, Trash2, Ban } from 'lucide-react';
import { useState, useEffect } from 'react';
import { X, UserPlus, Crown, Shield, User, Trash2, Ban, Camera } from 'lucide-react';
import { useState, useEffect, useRef } from 'react';
import { Chat, ChatMember } from '../types';
import Avatar from './Avatar';
import { useStore } from '../store';
@@ -19,6 +19,9 @@ export default function ChatInfoPanel({ chat, onClose, onRefresh }: Props) {
const [search, setSearch] = useState('');
const [title, setTitle] = useState(chat.title || '');
const [editing, setEditing] = useState(false);
const [chatAvatar, setChatAvatar] = useState(chat.avatar || null);
const [uploadingAvatar, setUploadingAvatar] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
const isOwnerOrAdmin = chat.myRole === 'owner' || chat.myRole === 'admin' || me?.isAdmin;
@@ -28,6 +31,32 @@ export default function ChatInfoPanel({ chat, onClose, onRefresh }: Props) {
}
}, [addMode]);
async function handleChatAvatarUpload(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
setUploadingAvatar(true);
const form = new FormData();
form.append('file', file);
try {
const { data } = await api.put(`/api/chats/${chat.id}/avatar`, form, {
headers: { 'Content-Type': 'multipart/form-data' }
});
setChatAvatar(data.avatar);
onRefresh();
} catch {
// silent
} finally {
setUploadingAvatar(false);
}
}
async function handleRemoveChatAvatar() {
await api.delete(`/api/chats/${chat.id}/avatar`);
setChatAvatar(null);
onRefresh();
}
async function saveTitle() {
await api.put(`/api/chats/${chat.id}`, { title });
setEditing(false);
@@ -84,7 +113,29 @@ export default function ChatInfoPanel({ chat, onClose, onRefresh }: Props) {
<div className="flex-1 overflow-y-auto">
{/* Avatar & Title */}
<div className="flex flex-col items-center py-6 px-4">
<Avatar name={chat.title} color={chat.avatarColor} size="xl" />
<div className="relative">
<Avatar name={chat.title} color={chat.avatarColor} avatar={chatAvatar} size="xl" />
{uploadingAvatar && (
<div className="absolute inset-0 bg-black/40 rounded-full flex items-center justify-center">
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
</div>
)}
{isOwnerOrAdmin && chat.type !== 'private' && (
<button
onClick={() => fileRef.current?.click()}
disabled={uploadingAvatar}
className="absolute bottom-0 right-0 w-7 h-7 bg-blue-500 hover:bg-blue-600 rounded-full flex items-center justify-center shadow"
>
<Camera className="w-3.5 h-3.5 text-white" />
</button>
)}
</div>
{isOwnerOrAdmin && chat.type !== 'private' && chatAvatar && (
<button onClick={handleRemoveChatAvatar} className="mt-1 text-xs text-red-400 hover:text-red-600">
Удалить фото
</button>
)}
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleChatAvatarUpload} />
<div className="mt-3 w-full">
{editing && chat.type !== 'private' ? (
<div className="flex gap-2">

View File

@@ -0,0 +1,206 @@
import { useState, useRef } from 'react';
import { X, Camera, Trash2, Save, Lock } from 'lucide-react';
import { useStore } from '../store';
import api from '../api/client';
import Avatar from './Avatar';
interface Props {
onClose: () => void;
}
export default function ProfileModal({ onClose }: Props) {
const { user, setUser } = useStore();
const [displayName, setDisplayName] = useState(user?.displayName || '');
const [bio, setBio] = useState(user?.bio || '');
const [phone, setPhone] = useState(user?.phone || '');
const [password, setPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [saving, setSaving] = useState(false);
const [uploadingAvatar, setUploadingAvatar] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const fileRef = useRef<HTMLInputElement>(null);
async function handleSave() {
setSaving(true);
setError('');
setSuccess('');
try {
const body: any = { displayName, bio, phone };
if (newPassword) {
if (!password) { setError('Введите текущий пароль'); setSaving(false); return; }
body.password = password;
body.newPassword = newPassword;
}
const { data } = await api.put('/api/auth/me', body);
setUser({ ...user!, ...data });
localStorage.setItem('jc_user', JSON.stringify({ ...user!, ...data }));
setPassword('');
setNewPassword('');
setSuccess('Сохранено');
setTimeout(() => setSuccess(''), 3000);
} catch (err: any) {
setError(err.response?.data?.error || 'Ошибка сохранения');
} finally {
setSaving(false);
}
}
async function handleAvatarUpload(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file) return;
e.target.value = '';
setUploadingAvatar(true);
const form = new FormData();
form.append('file', file);
try {
const { data } = await api.put('/api/auth/avatar', form, {
headers: { 'Content-Type': 'multipart/form-data' }
});
const updated = { ...user!, avatar: data.avatar };
setUser(updated);
localStorage.setItem('jc_user', JSON.stringify(updated));
} catch {
setError('Ошибка загрузки фото');
} finally {
setUploadingAvatar(false);
}
}
async function handleRemoveAvatar() {
if (!user?.avatar) return;
try {
await api.delete('/api/auth/avatar');
const updated = { ...user!, avatar: null };
setUser(updated);
localStorage.setItem('jc_user', JSON.stringify(updated));
} catch {
setError('Ошибка');
}
}
return (
<div className="fixed inset-0 bg-black/50 flex items-end sm:items-center justify-center z-50 p-0 sm:p-4">
<div className="bg-white rounded-t-2xl sm:rounded-2xl w-full sm:max-w-md max-h-[90vh] flex flex-col">
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<h2 className="font-semibold text-gray-900">Мой профиль</h2>
<button onClick={onClose} className="p-1 rounded-lg hover:bg-gray-100 text-gray-400">
<X className="w-5 h-5" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-5 space-y-5">
{/* Avatar */}
<div className="flex flex-col items-center gap-3">
<div className="relative">
<Avatar
name={user?.displayName || ''}
color={user?.avatarColor || '#3b82f6'}
avatar={user?.avatar}
size="xl"
/>
{uploadingAvatar && (
<div className="absolute inset-0 bg-black/40 rounded-full flex items-center justify-center">
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
</div>
)}
</div>
<div className="flex items-center gap-2">
<button
onClick={() => fileRef.current?.click()}
disabled={uploadingAvatar}
className="flex items-center gap-1.5 px-3 py-1.5 bg-blue-50 hover:bg-blue-100 text-blue-600 text-sm rounded-lg transition-colors"
>
<Camera className="w-4 h-4" />
Загрузить фото
</button>
{user?.avatar && (
<button
onClick={handleRemoveAvatar}
className="flex items-center gap-1.5 px-3 py-1.5 bg-red-50 hover:bg-red-100 text-red-600 text-sm rounded-lg transition-colors"
>
<Trash2 className="w-4 h-4" />
Удалить
</button>
)}
</div>
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleAvatarUpload} />
</div>
{/* Info */}
<div className="space-y-3">
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Логин</label>
<div className="px-3 py-2 bg-gray-50 rounded-xl text-sm text-gray-400">@{user?.username}</div>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Имя</label>
<input
value={displayName}
onChange={e => setDisplayName(e.target.value)}
className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
placeholder="Ваше имя"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">О себе</label>
<textarea
value={bio}
onChange={e => setBio(e.target.value)}
rows={2}
className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-200 resize-none"
placeholder="Расскажите о себе..."
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Телефон</label>
<input
value={phone}
onChange={e => setPhone(e.target.value)}
className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
placeholder="+7..."
/>
</div>
</div>
{/* Password */}
<div className="space-y-3 border-t border-gray-100 pt-4">
<div className="flex items-center gap-2 text-sm font-medium text-gray-600">
<Lock className="w-4 h-4" />
Сменить пароль
</div>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
placeholder="Текущий пароль"
/>
<input
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
placeholder="Новый пароль"
/>
</div>
{error && <p className="text-red-500 text-sm">{error}</p>}
{success && <p className="text-green-500 text-sm">{success}</p>}
</div>
<div className="p-4 border-t border-gray-100">
<button
onClick={handleSave}
disabled={saving}
className="w-full flex items-center justify-center gap-2 bg-blue-500 hover:bg-blue-600 disabled:opacity-50 text-white py-3 rounded-xl font-medium text-sm transition-colors"
>
<Save className="w-4 h-4" />
{saving ? 'Сохранение...' : 'Сохранить'}
</button>
</div>
</div>
</div>
);
}

View File

@@ -11,6 +11,7 @@ import ChatHeader from '../components/ChatHeader';
import ChatInfoPanel from '../components/ChatInfoPanel';
import NewChatModal from '../components/NewChatModal';
import AdminPanel from '../components/admin/AdminPanel';
import ProfileModal from '../components/ProfileModal';
import { usePushNotifications } from '../hooks/usePushNotifications';
import { Chat } from '../types';
@@ -21,6 +22,7 @@ export default function MainLayout() {
const [showNew, setShowNew] = useState(false);
const [showAdmin, setShowAdmin] = useState(false);
const [showInfo, setShowInfo] = useState(false);
const [showProfile, setShowProfile] = useState(false);
const [mobileChatOpen, setMobileChatOpen] = useState(false);
const [fullChat, setFullChat] = useState<Chat | null>(null);
@@ -91,7 +93,8 @@ export default function MainLayout() {
{/* Sidebar Header */}
<div className="px-4 py-3 border-b border-gray-100">
<div className="flex items-center gap-3 mb-3">
<Avatar name={user?.displayName || ''} color={user?.avatarColor || '#3b82f6'} size="sm" />
<Avatar name={user?.displayName || ''} color={user?.avatarColor || '#3b82f6'} avatar={user?.avatar} size="sm"
onClick={() => setShowProfile(true)} className="cursor-pointer" />
<div className="flex-1 min-w-0">
<div className="font-semibold text-gray-900 text-sm truncate">{user?.displayName}</div>
<div className="flex items-center gap-1 text-xs text-gray-400">
@@ -108,6 +111,10 @@ export default function MainLayout() {
<Shield className="w-4 h-4" />
</button>
)}
<button onClick={() => setShowProfile(true)}
className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-400 hover:text-gray-600" title="Профиль">
<Settings className="w-4 h-4" />
</button>
<button onClick={() => setShowNew(true)}
className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-400 hover:text-gray-600" title="Новый чат">
<Edit className="w-4 h-4" />
@@ -201,6 +208,7 @@ export default function MainLayout() {
if (chat) openChat(chat);
}} />}
{showAdmin && <AdminPanel onClose={() => setShowAdmin(false)} />}
{showProfile && <ProfileModal onClose={() => setShowProfile(false)} />}
</div>
);
}

View File

@@ -26,8 +26,15 @@ interface AppStore {
logout: () => void;
}
function loadUser(): User | null {
try {
const s = localStorage.getItem('jc_user');
return s ? JSON.parse(s) : null;
} catch { return null; }
}
export const useStore = create<AppStore>((set, get) => ({
user: null,
user: loadUser(),
chats: [],
activeChat: null,
messages: {},

View File

@@ -3,6 +3,7 @@ export interface User {
username: string;
displayName: string;
avatarColor: string;
avatar?: string | null;
bio?: string;
phone?: string;
isAdmin: boolean;
@@ -15,6 +16,7 @@ export interface ChatMember {
username: string;
displayName: string;
avatarColor: string;
avatar?: string | null;
role: 'owner' | 'admin' | 'member';
online: boolean;
lastSeen: string;
@@ -27,6 +29,7 @@ export interface Chat {
title: string;
description?: string;
avatarColor: string;
avatar?: string | null;
isPublic?: boolean;
role: 'owner' | 'admin' | 'member';
lastMessage?: string;