Reflex/src/views/ProfileView.vue

2355 lines
64 KiB
Vue
Raw Normal View History

2025-05-21 22:13:09 +07:00
<template>
2025-05-23 23:52:44 +07:00
<div class="app-profile-view">
<!-- Header Section -->
<div class="profile-header">
<div class="container">
<div class="header-content">
<div class="profile-title">
2025-05-23 23:52:44 +07:00
<h1 class="section-title">Мой профиль</h1>
<p class="subtitle">Управление личными данными и настройками</p>
</div>
<div class="header-actions">
<button
class="action-btn primary"
@click="toggleEditMode"
:disabled="loading"
>
<i class="icon" :class="isEditMode ? 'bi-eye' : 'bi-pencil'"></i>
{{ isEditMode ? 'Просмотр' : 'Редактировать' }}
</button>
</div>
</div>
2025-05-21 22:13:09 +07:00
</div>
</div>
<!-- Loading State -->
<div v-if="loading && initialLoading" class="loading-section">
<div class="loading-spinner">
<div class="spinner"></div>
<p>Загрузка профиля...</p>
</div>
</div>
<!-- Error State -->
<div v-if="error" class="error-section">
<div class="container">
<div class="error-card">
<i class="bi-exclamation-triangle"></i>
<h3>Ошибка загрузки</h3>
<p>{{ error }}</p>
<button class="retry-btn" @click="fetchProfileDataLocal">Попробовать снова</button>
</div>
2025-05-21 22:13:09 +07:00
</div>
</div>
<!-- Main Content -->
2025-05-23 23:52:44 +07:00
<div v-if="profileData && !initialLoading" class="profile-content">
<div class="container">
<div class="profile-layout">
<!-- Profile Card Section -->
<div class="profile-card-section">
<div class="profile-card">
<!-- Avatar Section -->
<div class="avatar-section">
2025-05-23 23:52:44 +07:00
<div class="avatar-container">
<img
v-if="mainPhoto"
:src="mainPhoto.url"
:alt="profileData.name"
class="avatar-image"
>
<div v-else class="avatar-placeholder">
<i class="bi-person"></i>
</div>
<div class="avatar-overlay" v-if="isEditMode">
<button class="change-avatar-btn" @click="scrollToPhotos">
<i class="bi-camera"></i>
</button>
</div>
</div>
<div class="user-info">
<h2 class="user-name">{{ profileData.name || 'Не указано' }}</h2>
<p class="user-email">{{ profileData.email }}</p>
<div class="user-badges">
<span class="badge verified">Подтвержден</span>
<span class="badge member-since">С {{ formatShortDate(profileData.createdAt) }}</span>
</div>
<!-- Кнопка выхода из аккаунта -->
<button @click="logoutUser" class="logout-btn">
<i class="bi-box-arrow-right"></i>
Выйти из аккаунта
</button>
</div>
</div>
<!-- Stats Section -->
<div class="stats-section">
<div class="stat-item">
2025-05-23 23:52:44 +07:00
<div class="stat-icon">
<i class="bi-images"></i>
</div>
<div class="stat-info">
<span class="stat-value">{{ profileData.photos?.length || 0 }}</span>
<span class="stat-label">Фото</span>
</div>
</div>
<div class="stat-item">
2025-05-23 23:52:44 +07:00
<div class="stat-icon">
<i class="bi-heart"></i>
</div>
<div class="stat-info">
<span class="stat-value">{{ profileData.matches?.length || 0 }}</span>
<span class="stat-label">Совпадения</span>
</div>
</div>
<div class="stat-item">
2025-05-23 23:52:44 +07:00
<div class="stat-icon">
<i class="bi-check-circle"></i>
</div>
<div class="stat-info">
<span class="stat-value">{{ getProfileCompletion() }}%</span>
<span class="stat-label">Заполнено</span>
</div>
</div>
</div>
</div>
</div>
<!-- Details Section -->
<div class="details-section">
<!-- Basic Info -->
<div class="info-card">
<div class="card-header">
<h3><i class="bi-person-lines-fill"></i> Основная информация</h3>
</div>
<div class="card-content">
<!-- Форма с сообщениями -->
<div v-if="profileActionError" class="alert error">
<i class="bi-exclamation-circle"></i>
{{ profileActionError }}
</div>
<div v-if="profileActionSuccess" class="alert success">
<i class="bi-check-circle"></i>
{{ profileActionSuccess }}
</div>
<!-- Поля данных -->
<div class="info-grid">
<div class="info-item">
<label for="editName">Имя</label>
<span v-if="!isEditMode">{{ profileData.name || 'Не указано' }}</span>
<input
v-else
type="text"
class="form-input"
id="editName"
v-model="editableProfileData.name"
:disabled="profileLoading"
placeholder="Введите ваше имя"
/>
</div>
<div class="info-item">
<label for="editDateOfBirth">Дата рождения</label>
<span v-if="!isEditMode">{{ profileData.dateOfBirth ? formatDate(profileData.dateOfBirth) : 'Не указана' }}</span>
<input
v-else
type="date"
class="form-input"
id="editDateOfBirth"
v-model="editableProfileData.dateOfBirth"
:disabled="profileLoading"
2025-05-23 15:20:38 +07:00
onfocus="this.showPicker()"
/>
</div>
<div class="info-item">
<label for="editGender">Пол</label>
<span v-if="!isEditMode">{{ getGenderText(profileData.gender) }}</span>
2025-05-23 23:52:44 +07:00
<div v-else class="select-wrapper">
2025-05-23 15:14:17 +07:00
<input
type="text"
class="form-input"
id="editGender"
v-model="genderSearchQuery"
placeholder="Выберите пол..."
@focus="showGenderList = true; filteredGenders = genderOptions"
@input="onGenderSearch"
:disabled="profileLoading"
/>
<button
type="button"
2025-05-23 23:52:44 +07:00
class="clear-btn"
2025-05-23 15:14:17 +07:00
@click="clearGenderSelection"
v-if="editableProfileData.gender"
:disabled="profileLoading"
>
<i class="bi-x"></i>
</button>
2025-05-23 23:52:44 +07:00
<div class="dropdown" v-if="showGenderList && filteredGenders.length > 0">
2025-05-23 15:14:17 +07:00
<div
v-for="option in filteredGenders"
:key="option.value"
2025-05-23 23:52:44 +07:00
class="dropdown-option"
2025-05-23 15:14:17 +07:00
@click="selectGender(option)"
>
{{ option.text }}
</div>
</div>
</div>
</div>
<div class="info-item">
<label for="editCity">Город</label>
<span v-if="!isEditMode">{{ profileData.location?.city || 'Не указан' }}</span>
2025-05-23 23:52:44 +07:00
<div v-else class="select-wrapper">
<input
type="text"
class="form-input"
id="editCity"
v-model="citySearchQuery"
placeholder="Начните вводить название города..."
@focus="showCityList = true"
@input="onCitySearch"
:disabled="profileLoading"
/>
<button
type="button"
2025-05-23 23:52:44 +07:00
class="clear-btn"
@click="clearCitySelection"
v-if="editableProfileData.location && editableProfileData.location.city"
:disabled="profileLoading"
>
<i class="bi-x"></i>
</button>
2025-05-23 23:52:44 +07:00
<div class="dropdown" v-if="showCityList && filteredCities.length > 0">
<div
v-for="city in filteredCities"
:key="city"
2025-05-23 23:52:44 +07:00
class="dropdown-option"
@click="selectCity(city)"
>
{{ city }}
</div>
</div>
</div>
</div>
<div class="info-item full-width">
<label for="editBio">О себе</label>
<span v-if="!isEditMode" class="bio-text">{{ profileData.bio || 'Расскажите о себе...' }}</span>
<textarea
v-else
class="form-input form-textarea"
id="editBio"
rows="4"
v-model="editableProfileData.bio"
:disabled="profileLoading"
placeholder="Расскажите немного о себе..."
></textarea>
</div>
</div>
</div>
2025-05-23 23:52:44 +07:00
</div>
<!-- Photos Section -->
<div class="info-card" id="photos-section">
<div class="card-header">
<h3><i class="bi-images"></i> Мои фотографии</h3>
<div class="header-actions" v-if="profileData.photos && profileData.photos.length > 0">
2025-05-23 13:16:13 +07:00
<button class="add-photo-btn" @click="triggerPhotoUpload" :disabled="photoActionLoading">
<span v-if="photoActionLoading" class="spinner-small"></span>
<i v-else class="bi-plus"></i>
{{ photoActionLoading ? 'Загрузка...' : 'Добавить фото' }}
</button>
</div>
</div>
<div class="card-content">
<!-- Photo Grid -->
<div v-if="profileData.photos && profileData.photos.length > 0" class="photo-grid">
<div
v-for="photo in profileData.photos"
:key="photo.public_id || photo._id"
class="photo-item"
:class="{ 'main-photo': photo.isProfilePhoto }"
>
<img :src="photo.url" :alt="'Фото ' + profileData.name" class="photo-image">
<div v-if="photo.isProfilePhoto" class="main-badge">
<i class="bi-star-fill"></i>
Главное
</div>
<div v-if="isEditMode" class="photo-actions">
<button
v-if="!photo.isProfilePhoto"
class="action-btn small primary"
@click="setAsMainPhoto(photo._id)"
:disabled="photoActionLoading"
title="Сделать главным"
>
<i class="bi-star"></i>
</button>
<button
class="action-btn small danger"
@click="confirmDeletePhoto(photo._id)"
:disabled="photoActionLoading"
title="Удалить"
>
<i class="bi-trash"></i>
</button>
</div>
</div>
</div>
<!-- Empty State -->
<div v-else class="empty-photos">
<i class="bi-image"></i>
<h4>Нет фотографий</h4>
<p>Добавьте фотографии, чтобы сделать профиль привлекательнее</p>
2025-05-23 13:16:13 +07:00
<button class="action-btn primary" @click="triggerPhotoUpload" :disabled="photoActionLoading">
<span v-if="photoActionLoading" class="spinner-small"></span>
<i v-else class="bi-plus"></i>
{{ photoActionLoading ? 'Загрузка...' : 'Добавить первое фото' }}
</button>
</div>
2025-05-23 23:52:44 +07:00
<!-- Photo Messages -->
<div v-if="photoActionError" class="alert error">
<i class="bi-exclamation-circle"></i>
{{ photoActionError }}
</div>
<div v-if="photoActionSuccess" class="alert success">
<i class="bi-check-circle"></i>
{{ photoActionSuccess }}
</div>
2025-05-23 13:16:13 +07:00
<div v-if="photoActionLoading" class="alert info">
<div class="spinner-small" style="border-top-color:#667eea"></div>
Загрузка фотографий...
</div>
2025-05-21 23:43:24 +07:00
</div>
</div>
2025-05-21 22:13:09 +07:00
</div>
</div>
2025-05-23 23:52:44 +07:00
</div>
</div>
<!-- Hidden File Input -->
<input
ref="fileInput"
type="file"
multiple
accept="image/*"
@change="handlePhotoSelect"
style="display: none;"
>
2025-05-21 23:43:24 +07:00
<!-- Delete Confirmation Modal -->
<div class="modal-overlay" v-if="showDeleteModal" @click="closeDeleteModal">
<div class="delete-modal" @click.stop>
<div class="modal-header">
<h3>Удалить фотографию</h3>
<button class="close-btn" @click="closeDeleteModal">
<i class="bi-x"></i>
</button>
</div>
2025-05-21 23:43:24 +07:00
<div class="modal-content">
<p>Вы уверены, что хотите удалить эту фотографию? Это действие нельзя отменить.</p>
</div>
<div class="modal-actions">
<button class="action-btn secondary" @click="closeDeleteModal">Отмена</button>
<button
class="action-btn danger"
@click="executeDeletePhoto"
:disabled="photoActionLoading"
>
<span v-if="photoActionLoading" class="spinner-small"></span>
Удалить
</button>
</div>
</div>
</div>
<!-- No Data State -->
<div v-if="!profileData && !initialLoading && !error" class="no-data-section">
<div class="container">
<div class="no-data-card">
<i class="bi-person-x"></i>
<h3>Данные профиля недоступны</h3>
<p>Возможно, вы не авторизованы или произошла ошибка.</p>
<router-link to="/login" class="action-btn primary">Войти в систему</router-link>
2025-05-21 23:43:24 +07:00
</div>
</div>
</div>
2025-05-21 22:13:09 +07:00
</div>
</template>
<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue';
2025-05-21 22:13:09 +07:00
import { useAuth } from '@/auth';
import api from '@/services/api';
const { isAuthenticated, user: authUserFromStore, token, fetchUser, logout } = useAuth();
2025-05-21 22:13:09 +07:00
const profileData = ref(null);
const loading = ref(true);
const initialLoading = ref(true);
const error = ref('');
const isEditMode = ref(false);
let originalProfileData = ''; // Для хранения исходных данных профиля в формате JSON
2025-05-21 22:13:09 +07:00
2025-05-21 23:43:24 +07:00
// Для управления фото
const photoActionLoading = ref(false);
const photoActionError = ref('');
const photoActionSuccess = ref('');
const photoToDeleteId = ref(null);
const showDeleteModal = ref(false);
const fileInput = ref(null);
// Для редактирования профиля
const editableProfileData = ref({
name: '',
bio: '',
dateOfBirth: '',
gender: '',
location: { city: '' }
});
const profileLoading = ref(false);
const profileActionError = ref('');
const profileActionSuccess = ref('');
const citySearchQuery = ref('');
const showCityList = ref(false);
const filteredCities = ref([]);
let cities = []; // для хранения списка городов
2025-05-21 23:43:24 +07:00
2025-05-23 15:14:17 +07:00
// Для выпадающего списка пола
const genderOptions = ref([
{ value: 'male', text: 'Мужской' },
{ value: 'female', text: 'Женский' },
{ value: 'other', text: 'Другой' }
]);
const genderSearchQuery = ref('');
const showGenderList = ref(false);
const filteredGenders = ref([]);
// Computed properties
const mainPhoto = computed(() => {
return profileData.value?.photos?.find(photo => photo.isProfilePhoto) ||
profileData.value?.photos?.[0] || null;
});
// Methods
const toggleEditMode = async () => {
// Если сейчас в режиме редактирования и пользователь хочет вернуться в режим просмотра
if (isEditMode.value) {
try {
// Проверяем, были ли изменения
const hasChanges = checkForChanges();
console.log('[ProfileView] Обнаружены изменения:', hasChanges);
if (hasChanges) {
console.log('[ProfileView] Сохранение изменений...');
2025-05-23 23:37:15 +07:00
profileLoading.value = true; // Устанавливаем индикатор загрузки формы
// Подготавливаем данные для отправки на сервер
const dataToUpdate = { ...editableProfileData.value };
// Обрабатываем дату рождения
if (dataToUpdate.dateOfBirth) {
try {
const dateObj = new Date(dataToUpdate.dateOfBirth);
2025-05-23 23:37:15 +07:00
if (!isNaN(dateObj.getTime())) {
dataToUpdate.dateOfBirth = dateObj.toISOString();
}
} catch (e) {
console.error('[ProfileView] Ошибка обработки даты:', e);
}
}
// Отправляем запрос на сервер
const response = await api.updateUserProfile(dataToUpdate);
2025-05-23 23:37:15 +07:00
console.log('[ProfileView] Профиль успешно обновлен:', response.data);
// Обновляем локальный profileData напрямую, не вызывая fetchUser()
profileData.value = {
...profileData.value,
name: dataToUpdate.name,
bio: dataToUpdate.bio,
dateOfBirth: dataToUpdate.dateOfBirth,
gender: dataToUpdate.gender,
location: dataToUpdate.location
};
2025-05-23 23:37:15 +07:00
// Обновляем authUserFromStore напрямую, если он доступен
if (authUserFromStore.value) {
// Копируем новые данные в хранилище авторизации
authUserFromStore.value = {
...authUserFromStore.value,
name: dataToUpdate.name,
bio: dataToUpdate.bio,
dateOfBirth: dataToUpdate.dateOfBirth,
gender: dataToUpdate.gender,
location: dataToUpdate.location
};
}
profileActionSuccess.value = 'Профиль успешно обновлен!';
// Автоматически скрываем сообщение через 3 секунды
setTimeout(() => {
profileActionSuccess.value = '';
}, 3000);
} else {
console.log('[ProfileView] Нет изменений, сохранение не требуется');
}
} catch (err) {
console.error('[ProfileView] Ошибка при сохранении профиля:', err);
profileActionError.value = err.response?.data?.message ||
'Произошла ошибка при обновлении профиля. Пожалуйста, попробуйте позже.';
} finally {
2025-05-23 23:37:15 +07:00
// Переключаемся в режим просмотра и сбрасываем состояние загрузки
isEditMode.value = false;
profileLoading.value = false;
2025-05-23 23:37:15 +07:00
// Гарантированно сбрасываем индикаторы загрузки
loading.value = false;
initialLoading.value = false;
}
} else {
// Переключаемся в режим редактирования
isEditMode.value = true;
// Копируем данные профиля в редактируемый объект
2025-05-23 14:05:22 +07:00
let formattedDate = '';
if (profileData.value && profileData.value.dateOfBirth) {
2025-05-23 14:05:22 +07:00
try {
const date = new Date(profileData.value.dateOfBirth);
2025-05-23 23:37:15 +07:00
formattedDate = date.toISOString().split('T')[0];
2025-05-23 14:05:22 +07:00
} catch (e) {
console.error('[ProfileView] Ошибка форматирования даты:', e);
2025-05-23 14:05:22 +07:00
}
}
editableProfileData.value = {
name: profileData.value?.name || '',
bio: profileData.value?.bio || '',
2025-05-23 14:05:22 +07:00
dateOfBirth: formattedDate,
gender: profileData.value?.gender || '',
location: {
2025-05-23 23:37:15 +07:00
city: profileData.value?.location?.city || ''
}
};
2025-05-23 23:37:15 +07:00
// Сохраняем копию для сравнения
originalProfileData = JSON.stringify(editableProfileData.value);
2025-05-23 23:37:15 +07:00
// Устанавливаем поля поиска
if (profileData.value?.location?.city) {
citySearchQuery.value = profileData.value.location.city;
} else {
citySearchQuery.value = '';
}
if (profileData.value?.gender) {
const genderOption = genderOptions.value.find(option => option.value === profileData.value.gender);
if (genderOption) {
genderSearchQuery.value = genderOption.text;
} else {
genderSearchQuery.value = '';
}
} else {
genderSearchQuery.value = '';
}
}
};
const scrollToPhotos = () => {
const photosSection = document.getElementById('photos-section');
if (photosSection) {
photosSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const triggerPhotoUpload = () => {
if (fileInput.value) {
2025-05-23 13:16:13 +07:00
clearMessages(); // Очищаем предыдущие сообщения перед новой загрузкой
fileInput.value.click();
}
};
const handlePhotoSelect = async (event) => {
const files = event.target.files;
if (!files || files.length === 0) return;
2025-05-23 13:16:13 +07:00
// Проверяем форматы и размеры файлов
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/jpg'];
const maxSizeMB = 10; // Максимальный размер файла в MB
const maxSizeBytes = maxSizeMB * 1024 * 1024;
let hasInvalidType = false;
let hasInvalidSize = false;
for (const file of files) {
if (!allowedTypes.includes(file.type)) {
hasInvalidType = true;
break;
}
if (file.size > maxSizeBytes) {
hasInvalidSize = true;
break;
}
}
if (hasInvalidType) {
photoActionError.value = 'Можно загружать только фотографии (JPEG, PNG, WebP)';
event.target.value = '';
return;
}
if (hasInvalidSize) {
photoActionError.value = `Размер файла не должен превышать ${maxSizeMB} МБ`;
event.target.value = '';
return;
}
// Обрабатываем загрузку фото
await uploadPhotos(Array.from(files));
// Очищаем input
event.target.value = '';
};
const getProfileCompletion = () => {
if (!profileData.value) return 0;
const fields = [
profileData.value.name,
profileData.value.bio,
profileData.value.dateOfBirth,
profileData.value.gender,
profileData.value.location?.city,
profileData.value.photos?.length > 0
];
const completed = fields.filter(field => !!field).length;
return Math.round((completed / fields.length) * 100);
};
const getGenderText = (gender) => {
const genderMap = {
'male': 'Мужской',
'female': 'Женский',
'other': 'Другой'
};
return genderMap[gender] || 'Не указан';
};
const formatDate = (dateString) => {
if (!dateString) return '';
const options = { year: 'numeric', month: 'long', day: 'numeric' };
return new Date(dateString).toLocaleDateString('ru-RU', options);
};
const formatShortDate = (dateString) => {
if (!dateString) return '';
const date = new Date(dateString);
2025-05-23 20:49:50 +07:00
// Возвращаем дату в формате дд.мм.гггг
return `${date.getDate().toString().padStart(2, '0')}.${(date.getMonth() + 1).toString().padStart(2, '0')}.${date.getFullYear()}`;
};
const handleProfileUpdate = () => {
// Обновляем данные после редактирования профиля
fetchUser();
clearMessages();
};
const handlePhotoUploadComplete = (result) => {
console.log('[ProfileView] Получено событие photo-upload-complete:', result);
if (result.success > 0) {
photoActionSuccess.value = `Успешно загружено фотографий: ${result.success}`;
// Автоматически скрываем сообщение через 3 секунды
setTimeout(() => {
photoActionSuccess.value = '';
}, 3000);
// Прокручиваем к разделу с фотографиями
setTimeout(() => {
scrollToPhotos();
}, 100);
}
if (result.errors > 0) {
photoActionError.value = `Не удалось загрузить некоторые фото (${result.errors})`;
}
};
2025-05-23 13:16:13 +07:00
// Новый метод для загрузки фотографий непосредственно из ProfileView
const uploadPhotos = async (files) => {
if (!files || files.length === 0) {
console.log('[ProfileView] uploadPhotos: нет файлов для загрузки');
return;
}
console.log(`[ProfileView] uploadPhotos: получено файлов: ${files.length}`);
// Индикатор для отслеживания успешных загрузок
let successCount = 0;
let errorCount = 0;
photoActionLoading.value = true;
clearMessages();
2025-05-23 23:37:15 +07:00
try {
2025-05-23 13:16:13 +07:00
let imageCompression;
try {
// Импортируем библиотеку для сжатия изображений динамически
imageCompression = (await import('browser-image-compression')).default;
} catch (importErr) {
console.error('[ProfileView] Ошибка при импорте библиотеки сжатия:', importErr);
throw new Error('Не удалось загрузить необходимые компоненты. Пожалуйста, обновите страницу и попробуйте снова.');
}
// Настройки для сжатия изображений
const options = {
maxSizeMB: 1,
maxWidthOrHeight: 1920,
useWebWorker: true,
};
for (let i = 0; i < files.length; i++) {
const originalFile = files[i];
try {
// Сжимаем файл
console.log(`[ProfileView] Сжатие файла ${originalFile.name}...`);
const compressedFile = await imageCompression(originalFile, options);
console.log(`[ProfileView] Файл ${originalFile.name} сжат. Оригинальный размер: ${(originalFile.size / 1024 / 1024).toFixed(2)} MB, Новый размер: ${(compressedFile.size / 1024 / 1024).toFixed(2)} MB`);
// Создаем FormData для отправки на сервер
const fd = new FormData();
fd.append('profilePhoto', compressedFile, originalFile.name);
// Отправляем файл
console.log(`[ProfileView] Отправка файла ${originalFile.name} (сжатого) на сервер...`);
const response = await api.uploadUserProfilePhoto(fd);
console.log(`[ProfileView] Ответ сервера (фото ${originalFile.name}):`, response.data);
// Увеличиваем счетчик успешных загрузок
successCount++;
2025-05-23 23:37:15 +07:00
// Вместо вызова fetchUser, получаем данные напрямую и обновляем локальный profileData
if (response.data && response.data.photos) {
// Обновляем фотографии в локальном profileData
profileData.value = {
...profileData.value,
photos: response.data.photos
};
// Обновляем глобальный authUserFromStore
if (authUserFromStore.value) {
authUserFromStore.value = {
...authUserFromStore.value,
photos: response.data.photos
};
}
} else {
// Если по какой-то причине фотографий нет в ответе, сделаем отдельный запрос
// для получения обновленных данных пользователя, но не через fetchUser
const userResponse = await api.getMe();
if (userResponse.data) {
profileData.value = userResponse.data;
// Также обновим глобальное хранилище
if (authUserFromStore.value) {
authUserFromStore.value = userResponse.data;
}
}
}
2025-05-23 13:16:13 +07:00
console.log(`[ProfileView] Данные пользователя обновлены после загрузки фото ${originalFile.name}`);
2025-05-23 23:37:15 +07:00
} catch (err) {
2025-05-23 13:16:13 +07:00
console.error(`[ProfileView] Ошибка при сжатии или загрузке фото ${originalFile.name}:`, err);
errorCount++;
// Показываем более информативное сообщение об ошибке
if (err.message && err.message.includes('network')) {
photoActionError.value = 'Ошибка сети при загрузке фото. Пожалуйста, проверьте подключение к интернету.';
} else if (err.response && err.response.status === 413) {
photoActionError.value = 'Файл слишком большой. Пожалуйста, выберите фото меньшего размера.';
2025-05-23 23:37:15 +07:00
} else {
photoActionError.value = 'Произошла ошибка при загрузке фото';
2025-05-23 13:16:13 +07:00
}
}
}
// Формируем сообщение для пользователя
if (successCount > 0) {
photoActionSuccess.value = `Успешно загружено фотографий: ${successCount}`;
console.log(`[ProfileView] Успешно загружено фотографий: ${successCount}`);
// Автоматически скрываем сообщение через 3 секунды
setTimeout(() => {
photoActionSuccess.value = '';
}, 3000);
// Прокручиваем к разделу с фотографиями
setTimeout(() => {
scrollToPhotos();
}, 100);
}
if (errorCount > 0) {
photoActionError.value = `Не удалось загрузить некоторые фото (${errorCount})`;
console.log(`[ProfileView] Ошибок при загрузке: ${errorCount}`);
}
} catch (err) {
console.error('[ProfileView] Общая ошибка при загрузке фото:', err);
photoActionError.value = 'Произошла ошибка при загрузке фотографий';
} finally {
photoActionLoading.value = false;
}
};
const clearMessages = () => {
photoActionError.value = '';
photoActionSuccess.value = '';
};
2025-05-21 23:43:24 +07:00
2025-05-21 22:13:09 +07:00
const fetchProfileDataLocal = async () => {
console.log('[ProfileView] Начало загрузки данных профиля...');
2025-05-21 22:13:09 +07:00
error.value = '';
loading.value = true;
initialLoading.value = true;
2025-05-21 22:13:09 +07:00
try {
// Проверяем авторизацию
if (!token.value) {
console.log('[ProfileView] Токен отсутствует, авторизация не выполнена');
error.value = "Вы не авторизованы для просмотра этой страницы.";
return;
}
// Если у нас уже есть данные пользователя в хранилище, используем их
if (authUserFromStore.value && Object.keys(authUserFromStore.value).length > 0) {
console.log('[ProfileView] Использую данные профиля из хранилища:', authUserFromStore.value);
profileData.value = { ...authUserFromStore.value };
} else {
// Иначе делаем прямой запрос к API, минуя fetchUser
console.log('[ProfileView] Данных в хранилище нет, делаю прямой запрос к API');
const response = await api.getMe();
console.log('[ProfileView] Ответ от API /auth/me:', response.data);
// Сохраняем данные пользователя локально
profileData.value = response.data;
}
console.log('[ProfileView] Данные профиля успешно загружены:', profileData.value);
2025-05-21 22:13:09 +07:00
} catch (err) {
console.error('[ProfileView] Ошибка при загрузке профиля:', err);
2025-05-21 22:13:09 +07:00
error.value = (err.response && err.response.data && err.response.data.message)
? err.response.data.message
: 'Не удалось загрузить данные профиля. Попробуйте позже.';
2025-05-21 22:13:09 +07:00
} finally {
// Всегда сбрасываем индикаторы загрузки
console.log('[ProfileView] Завершение загрузки профиля, сброс индикаторов загрузки');
loading.value = false;
2025-05-21 22:13:09 +07:00
initialLoading.value = false;
}
};
2025-05-21 23:43:24 +07:00
const setAsMainPhoto = async (photoId) => {
if (!photoId) {
photoActionError.value = 'Неверный ID фотографии';
return;
}
2025-05-21 23:43:24 +07:00
photoActionLoading.value = true;
clearMessages();
2025-05-21 23:43:24 +07:00
try {
console.log('[ProfileView] Установка главного фото, ID:', photoId);
2025-05-21 23:43:24 +07:00
const response = await api.setMainPhoto(photoId);
console.log('[ProfileView] Ответ сервера:', response.data);
// Обновляем локальные данные сразу для быстрого отклика
if (profileData.value && profileData.value.photos) {
2025-05-23 23:37:15 +07:00
// Сначала сбрасываем флаг isProfilePhoto для всех фото
profileData.value.photos.forEach(photo => {
photo.isProfilePhoto = photo._id === photoId;
});
2025-05-23 23:37:15 +07:00
// Обновляем данные и в глобальном хранилище если оно доступно
if (authUserFromStore.value && authUserFromStore.value.photos) {
authUserFromStore.value.photos.forEach(photo => {
photo.isProfilePhoto = photo._id === photoId;
});
}
}
2025-05-21 23:43:24 +07:00
photoActionSuccess.value = response.data.message || 'Главное фото обновлено.';
// Автоматически скрываем сообщение через 3 секунды
setTimeout(() => {
photoActionSuccess.value = '';
}, 3000);
2025-05-21 23:43:24 +07:00
} catch (err) {
console.error('[ProfileView] Ошибка при установке главного фото:', err);
photoActionError.value = err.response?.data?.message || 'Не удалось установить главное фото.';
} finally {
photoActionLoading.value = false;
}
};
const confirmDeletePhoto = (photoId) => {
photoToDeleteId.value = photoId;
showDeleteModal.value = true;
clearMessages();
};
const closeDeleteModal = () => {
showDeleteModal.value = false;
photoToDeleteId.value = null;
2025-05-21 23:43:24 +07:00
};
const executeDeletePhoto = async () => {
if (!photoToDeleteId.value) {
photoActionError.value = 'Неверный ID фотографии';
return;
}
2025-05-21 23:43:24 +07:00
photoActionLoading.value = true;
clearMessages();
2025-05-21 23:43:24 +07:00
try {
console.log('[ProfileView] Удаление фото, ID:', photoToDeleteId.value);
2025-05-21 23:43:24 +07:00
const response = await api.deletePhoto(photoToDeleteId.value);
console.log('[ProfileView] Ответ сервера:', response.data);
// Обновляем локальные данные сразу для быстрого отклика
if (profileData.value && profileData.value.photos) {
profileData.value.photos = profileData.value.photos.filter(
photo => photo._id !== photoToDeleteId.value
);
2025-05-23 23:37:15 +07:00
// Также обновляем глобальное хранилище
if (authUserFromStore.value && authUserFromStore.value.photos) {
authUserFromStore.value.photos = authUserFromStore.value.photos.filter(
photo => photo._id !== photoToDeleteId.value
);
}
}
2025-05-21 23:43:24 +07:00
photoActionSuccess.value = response.data.message || 'Фотография удалена.';
closeDeleteModal();
// Автоматически скрываем сообщение через 3 секунды
setTimeout(() => {
photoActionSuccess.value = '';
}, 3000);
2025-05-21 23:43:24 +07:00
} catch (err) {
console.error('[ProfileView] Ошибка при удалении фото:', err);
photoActionError.value = err.response?.data?.message || 'Не удалось удалить фотографию.';
closeDeleteModal();
2025-05-21 23:43:24 +07:00
} finally {
photoActionLoading.value = false;
}
};
const saveProfileChanges = async () => {
profileLoading.value = true;
loading.value = true; // Устанавливаем общий индикатор загрузки
clearProfileMessages();
try {
console.log('[ProfileView] Сохранение данных профиля:', editableProfileData.value);
// Подготавливаем данные для отправки на сервер
const dataToUpdate = { ...editableProfileData.value };
2025-05-23 14:05:22 +07:00
// Обрабатываем дату рождения - если это строка с датой в формате yyyy-MM-dd
// преобразуем её в полноценную дату (в формат ISO)
if (dataToUpdate.dateOfBirth) {
2025-05-23 14:05:22 +07:00
try {
// Получаем дату в формате ISO с поправкой на часовой пояс
const dateObj = new Date(dataToUpdate.dateOfBirth);
if (!isNaN(dateObj.getTime())) { // Проверяем, что дата валидна
dataToUpdate.dateOfBirth = dateObj.toISOString();
}
} catch (e) {
console.error('[ProfileView] Ошибка обработки даты:', e);
// Оставляем как есть, если возникла ошибка
}
console.log('[ProfileView] Дата рождения для отправки:', dataToUpdate.dateOfBirth);
}
const response = await api.updateUserProfile(dataToUpdate);
console.log('[ProfileView] Ответ от сервера (профиль):', response.data);
// Обновляем данные в профиле
await fetchUser();
profileActionSuccess.value = 'Профиль успешно обновлен!';
// Автоматически скрываем сообщение через 3 секунды
setTimeout(() => {
profileActionSuccess.value = '';
}, 3000);
} catch (err) {
console.error('[ProfileView] Ошибка при обновлении профиля:', err);
profileActionError.value = err.response?.data?.message ||
'Произошла ошибка при обновлении профиля. Пожалуйста, попробуйте позже.';
} finally {
profileLoading.value = false;
loading.value = false; // Сбрасываем общий индикатор загрузки
initialLoading.value = false; // Убеждаемся, что initialLoading тоже сброшен
}
};
const checkForChanges = () => {
// Сравниваем текущие редактируемые данные с оригинальными
const currentData = JSON.stringify(editableProfileData.value);
console.log('[ProfileView] Проверка изменений:');
console.log('Оригинал:', originalProfileData);
console.log('Текущие:', currentData);
console.log('Есть изменения:', currentData !== originalProfileData);
return currentData !== originalProfileData;
};
2025-05-23 23:41:30 +07:00
// Добавляем отсутствующие функции
const logoutUser = async () => {
try {
await logout();
// Перенаправляем на страницу входа после выхода
window.location.href = '/login';
} catch (err) {
console.error('[ProfileView] Ошибка при выходе:', err);
}
};
const clearProfileMessages = () => {
profileActionError.value = '';
profileActionSuccess.value = '';
};
// Функции для работы с городами
const onCitySearch = (event) => {
const query = event.target.value.toLowerCase().trim();
citySearchQuery.value = event.target.value;
if (query.length > 0) {
// Простой список российских городов для демонстрации
const allCities = [
'Москва', 'Санкт-Петербург', 'Новосибирск', 'Екатеринбург', 'Казань',
'Нижний Новгород', 'Челябинск', 'Самара', 'Омск', 'Ростов-на-Дону',
'Уфа', 'Красноярск', 'Воронеж', 'Пермь', 'Волгоград', 'Краснодар',
'Саратов', 'Тюмень', 'Тольятти', 'Ижевск', 'Барнаул', 'Ульяновск',
'Иркутск', 'Хабаровск', 'Ярославль', 'Владивосток', 'Махачкала',
'Томск', 'Оренбург', 'Кемерово', 'Новокузнецк', 'Рязань', 'Пенза',
'Астрахань', 'Липецк', 'Тула', 'Киров', 'Чебоксары', 'Калининград'
];
filteredCities.value = allCities.filter(city =>
city.toLowerCase().includes(query)
).slice(0, 10); // Ограничиваем до 10 результатов
showCityList.value = filteredCities.value.length > 0;
} else {
filteredCities.value = [];
showCityList.value = false;
}
};
const selectCity = (city) => {
citySearchQuery.value = city;
editableProfileData.value.location.city = city;
showCityList.value = false;
};
const clearCitySelection = () => {
citySearchQuery.value = '';
editableProfileData.value.location.city = '';
showCityList.value = false;
};
// Функции для работы с полом
const onGenderSearch = (event) => {
const query = event.target.value.toLowerCase().trim();
genderSearchQuery.value = event.target.value;
if (query.length > 0) {
filteredGenders.value = genderOptions.value.filter(option =>
option.text.toLowerCase().includes(query)
);
showGenderList.value = filteredGenders.value.length > 0;
} else {
filteredGenders.value = genderOptions.value;
showGenderList.value = true;
}
};
const selectGender = (option) => {
genderSearchQuery.value = option.text;
editableProfileData.value.gender = option.value;
showGenderList.value = false;
};
const clearGenderSelection = () => {
genderSearchQuery.value = '';
editableProfileData.value.gender = '';
showGenderList.value = false;
};
// Закрытие выпадающих списков при клике вне их
const handleClickOutside = (event) => {
if (!event.target.closest('.city-input-wrapper')) {
showCityList.value = false;
showGenderList.value = false;
}
};
// Добавляем onMounted для инициализации компонента
onMounted(async () => {
console.log('[ProfileView] Компонент смонтирован, начинаем загрузку профиля...');
// Добавляем обработчик для закрытия выпадающих списков
document.addEventListener('click', handleClickOutside);
// Загружаем данные профиля
await fetchProfileDataLocal();
});
// Очистка при размонтировании
import { onUnmounted } from 'vue';
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside);
});
2025-05-21 22:13:09 +07:00
</script>
<style scoped>
2025-05-23 23:52:44 +07:00
.app-profile-view {
display: flex;
flex-direction: column;
height: 100vh;
width: 100%;
position: relative;
2025-05-23 23:52:44 +07:00
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
overflow: hidden;
}
2025-05-23 23:52:44 +07:00
/* Container */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
width: 100%;
box-sizing: border-box;
}
2025-05-23 23:52:44 +07:00
/* Header Section */
.profile-header {
background: rgba(33, 33, 60, 0.9);
backdrop-filter: blur(10px);
padding: 1rem 0;
color: white;
position: sticky;
top: 0;
z-index: 10;
height: var(--header-height, 56px);
display: flex;
align-items: center;
justify-content: center;
}
2025-05-23 23:52:44 +07:00
.header-content {
display: flex;
2025-05-23 23:52:44 +07:00
justify-content: space-between;
align-items: center;
2025-05-23 23:52:44 +07:00
width: 100%;
position: relative;
}
2025-05-23 23:52:44 +07:00
.profile-title {
flex: 1;
text-align: center;
}
2025-05-23 23:52:44 +07:00
.section-title {
margin: 0;
font-size: 1.3rem;
font-weight: 600;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
color: white;
}
2025-05-23 23:52:44 +07:00
.subtitle {
margin: 0;
font-size: 0.85rem;
opacity: 0.9;
color: rgba(255, 255, 255, 0.8);
}
2025-05-23 23:52:44 +07:00
.header-actions {
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
}
2025-05-23 23:52:44 +07:00
/* Main Content */
.profile-content {
flex: 1;
overflow-y: auto;
padding: 1rem 0;
padding-bottom: calc(1rem + var(--nav-height, 60px));
-webkit-overflow-scrolling: touch;
}
.profile-layout {
display: flex;
flex-direction: column;
2025-05-23 23:52:44 +07:00
gap: 1.5rem;
}
2025-05-23 23:52:44 +07:00
/* Profile Card */
.profile-card {
2025-05-23 23:52:44 +07:00
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
border: 1px solid rgba(255, 255, 255, 0.2);
}
.avatar-section {
display: flex;
align-items: center;
2025-05-23 23:52:44 +07:00
gap: 1rem;
margin-bottom: 1.5rem;
}
.avatar-container {
position: relative;
2025-05-23 23:52:44 +07:00
width: 80px;
height: 80px;
border-radius: 50%;
overflow: hidden;
2025-05-23 23:52:44 +07:00
border: 3px solid rgba(102, 126, 234, 0.3);
flex-shrink: 0;
}
.avatar-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.avatar-placeholder {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
2025-05-23 23:52:44 +07:00
background: rgba(102, 126, 234, 0.1);
color: #667eea;
2025-05-23 23:52:44 +07:00
font-size: 2rem;
}
.avatar-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
2025-05-23 23:52:44 +07:00
background: rgba(0, 0, 0, 0.6);
opacity: 0;
transition: opacity 0.3s;
border-radius: 50%;
}
.avatar-container:hover .avatar-overlay {
opacity: 1;
}
.change-avatar-btn {
2025-05-23 23:52:44 +07:00
background: #667eea;
color: white;
border: none;
2025-05-23 23:52:44 +07:00
padding: 0.5rem;
border-radius: 50%;
cursor: pointer;
2025-05-23 23:52:44 +07:00
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
}
.change-avatar-btn:hover {
2025-05-23 23:52:44 +07:00
background: #5a6abf;
transform: scale(1.1);
}
.user-info {
flex: 1;
2025-05-23 23:52:44 +07:00
min-width: 0;
}
.user-name {
2025-05-23 23:52:44 +07:00
font-size: 1.4rem;
font-weight: 600;
margin: 0 0 0.3rem;
color: #333;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.user-email {
2025-05-23 23:52:44 +07:00
font-size: 0.9rem;
color: #6c757d;
margin: 0 0 0.8rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.user-badges {
display: flex;
2025-05-23 23:52:44 +07:00
flex-wrap: wrap;
gap: 0.5rem;
margin-bottom: 0.8rem;
}
.badge {
2025-05-23 23:52:44 +07:00
padding: 0.25rem 0.6rem;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 500;
white-space: nowrap;
}
.badge.verified {
2025-05-23 23:52:44 +07:00
background: linear-gradient(45deg, #28a745, #20c997);
color: white;
}
.badge.member-since {
2025-05-23 23:52:44 +07:00
background: linear-gradient(45deg, #667eea, #764ba2);
color: white;
}
.logout-btn {
2025-05-23 23:52:44 +07:00
background: none;
border: none;
2025-05-23 23:52:44 +07:00
color: #dc3545;
cursor: pointer;
2025-05-23 23:52:44 +07:00
font-size: 0.85rem;
display: flex;
align-items: center;
2025-05-23 23:52:44 +07:00
gap: 0.3rem;
padding: 0.25rem 0;
transition: color 0.3s ease;
}
.logout-btn:hover {
2025-05-23 23:52:44 +07:00
color: #c82333;
}
2025-05-23 23:52:44 +07:00
/* Stats Section */
.stats-section {
2025-05-23 23:52:44 +07:00
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.stat-item {
2025-05-23 23:52:44 +07:00
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
2025-05-23 23:52:44 +07:00
.stat-icon {
width: 40px;
height: 40px;
border-radius: 12px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 1.2rem;
margin-bottom: 0.5rem;
}
.stat-info {
display: flex;
flex-direction: column;
align-items: center;
}
.stat-value {
2025-05-23 23:52:44 +07:00
font-size: 1.2rem;
font-weight: 700;
color: #333;
margin: 0;
}
.stat-label {
2025-05-23 23:52:44 +07:00
font-size: 0.75rem;
color: #6c757d;
margin-top: 0.2rem;
}
2025-05-23 23:52:44 +07:00
/* Info Cards */
.info-card {
2025-05-23 23:52:44 +07:00
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
border: 1px solid rgba(255, 255, 255, 0.2);
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
2025-05-23 23:52:44 +07:00
margin-bottom: 1.5rem;
flex-wrap: wrap;
gap: 1rem;
}
.card-header h3 {
margin: 0;
2025-05-23 23:52:44 +07:00
font-size: 1.1rem;
font-weight: 600;
display: flex;
align-items: center;
2025-05-23 23:52:44 +07:00
gap: 0.5rem;
color: #333;
}
.card-header h3 i {
2025-05-23 23:52:44 +07:00
font-size: 1.2rem;
color: #667eea;
}
.card-content {
2025-05-23 23:52:44 +07:00
padding: 0;
}
2025-05-23 23:52:44 +07:00
/* Form Elements */
.info-grid {
display: grid;
2025-05-23 23:52:44 +07:00
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
}
.info-item {
display: flex;
flex-direction: column;
2025-05-23 23:52:44 +07:00
gap: 0.5rem;
}
.info-item.full-width {
grid-column: 1 / -1;
}
.info-item label {
2025-05-23 23:52:44 +07:00
font-weight: 600;
color: #495057;
font-size: 0.9rem;
}
.info-item span {
2025-05-23 23:52:44 +07:00
font-size: 1rem;
color: #6c757d;
padding: 0.75rem 1rem;
background: #f8f9fa;
border-radius: 8px;
border: 1px solid #e9ecef;
}
.bio-text {
line-height: 1.5;
white-space: pre-wrap;
}
.form-input {
2025-05-23 23:52:44 +07:00
padding: 0.75rem 1rem;
border: 1px solid #dee2e6;
border-radius: 8px;
font-size: 1rem;
transition: all 0.3s ease;
background: white;
}
.form-input:focus {
outline: none;
2025-05-23 23:52:44 +07:00
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}
.form-input:disabled {
background: #f8f9fa;
cursor: not-allowed;
}
.form-textarea {
2025-05-23 23:52:44 +07:00
resize: vertical;
min-height: 100px;
font-family: inherit;
}
2025-05-23 23:52:44 +07:00
.select-wrapper {
position: relative;
}
2025-05-23 23:52:44 +07:00
.clear-btn {
position: absolute;
2025-05-23 23:52:44 +07:00
top: 50%;
right: 0.75rem;
transform: translateY(-50%);
background: none;
border: none;
2025-05-23 23:52:44 +07:00
color: #6c757d;
cursor: pointer;
2025-05-23 23:52:44 +07:00
padding: 0.25rem;
border-radius: 4px;
transition: all 0.3s ease;
}
.clear-btn:hover {
color: #dc3545;
background: rgba(220, 53, 69, 0.1);
}
2025-05-23 23:52:44 +07:00
.dropdown {
position: absolute;
top: 100%;
left: 0;
right: 0;
2025-05-23 23:52:44 +07:00
background: white;
border: 1px solid #dee2e6;
border-radius: 8px;
max-height: 200px;
overflow-y: auto;
z-index: 1000;
2025-05-23 23:52:44 +07:00
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
margin-top: 0.25rem;
}
.dropdown-option {
padding: 0.75rem 1rem;
cursor: pointer;
transition: background-color 0.2s ease;
border-bottom: 1px solid #f8f9fa;
}
.dropdown-option:last-child {
border-bottom: none;
}
.dropdown-option:hover {
background: #f8f9fa;
color: #667eea;
}
2025-05-23 23:52:44 +07:00
/* Action Buttons */
.action-btn {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.6rem 1.2rem;
border: none;
border-radius: 50px;
font-weight: 600;
font-size: 0.9rem;
cursor: pointer;
2025-05-23 23:52:44 +07:00
transition: all 0.3s ease;
text-decoration: none;
white-space: nowrap;
}
.action-btn.primary {
background: linear-gradient(45deg, #667eea, #764ba2);
color: white;
}
.action-btn.primary:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}
.action-btn.secondary {
background: #f8f9fa;
color: #495057;
border: 1px solid #dee2e6;
}
.action-btn.secondary:hover {
background: #e9ecef;
color: #343a40;
}
2025-05-23 23:52:44 +07:00
.action-btn.danger {
background: #dc3545;
color: white;
}
2025-05-23 23:52:44 +07:00
.action-btn.danger:hover {
background: #c82333;
transform: translateY(-2px);
}
.action-btn.small {
padding: 0.4rem 0.8rem;
font-size: 0.8rem;
}
.action-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none !important;
}
.add-photo-btn {
background: linear-gradient(45deg, #667eea, #764ba2);
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 50px;
font-size: 0.85rem;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
gap: 0.4rem;
}
.add-photo-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}
/* Photo Grid */
.photo-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 1rem;
margin-top: 1rem;
}
.photo-item {
position: relative;
aspect-ratio: 1;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
}
.photo-item:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}
.photo-item.main-photo {
border: 3px solid #ffc107;
}
.photo-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.main-badge {
position: absolute;
top: 0.5rem;
left: 0.5rem;
background: linear-gradient(45deg, #ffc107, #ff8c00);
color: white;
padding: 0.25rem 0.5rem;
border-radius: 12px;
font-size: 0.7rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.2rem;
}
.photo-actions {
position: absolute;
top: 0.5rem;
right: 0.5rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
opacity: 0;
transition: opacity 0.3s ease;
}
.photo-item:hover .photo-actions {
opacity: 1;
}
/* Empty States */
.empty-photos {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
2025-05-23 23:52:44 +07:00
padding: 3rem 1.5rem;
border: 2px dashed #dee2e6;
border-radius: 16px;
background: rgba(248, 249, 250, 0.5);
}
.empty-photos i {
2025-05-23 23:52:44 +07:00
font-size: 3rem;
color: #6c757d;
margin-bottom: 1rem;
}
.empty-photos h4 {
margin: 0 0 0.5rem;
color: #495057;
font-size: 1.1rem;
}
.empty-photos p {
margin: 0 0 1.5rem;
color: #6c757d;
font-size: 0.9rem;
}
.no-data-section,
.error-section,
.loading-section {
display: flex;
justify-content: center;
align-items: center;
flex: 1;
padding: 2rem 1rem;
}
.no-data-card,
.error-card {
background: white;
border-radius: 20px;
padding: 2rem;
text-align: center;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
max-width: 400px;
width: 100%;
}
.no-data-card i,
.error-card i {
font-size: 3rem;
margin-bottom: 1rem;
color: #6c757d;
}
.no-data-card h3,
.error-card h3 {
color: #343a40;
margin-bottom: 0.5rem;
}
.retry-btn {
background: linear-gradient(45deg, #667eea, #764ba2);
color: white;
border: none;
padding: 0.75rem 1.5rem;
border-radius: 50px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
margin-top: 1rem;
}
.retry-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}
/* Loading States */
.loading-spinner {
text-align: center;
color: white;
}
.spinner {
width: 50px;
height: 50px;
border: 4px solid rgba(255, 255, 255, 0.3);
border-left: 4px solid white;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 1rem;
}
2025-05-23 23:52:44 +07:00
.spinner-small {
width: 20px;
height: 20px;
border: 3px solid rgba(102, 126, 234, 0.3);
border-top: 3px solid #667eea;
border-radius: 50%;
animation: spin 0.8s linear infinite;
display: inline-block;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Modal */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
2025-05-23 23:52:44 +07:00
background: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(4px);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
2025-05-23 23:52:44 +07:00
padding: 1rem;
}
.delete-modal {
2025-05-23 23:52:44 +07:00
background: white;
border-radius: 16px;
padding: 1.5rem;
width: 100%;
max-width: 400px;
2025-05-23 23:52:44 +07:00
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
2025-05-23 23:52:44 +07:00
margin-bottom: 1rem;
}
.modal-header h3 {
margin: 0;
2025-05-23 23:52:44 +07:00
font-size: 1.2rem;
color: #333;
}
.close-btn {
background: none;
border: none;
2025-05-23 23:52:44 +07:00
color: #6c757d;
cursor: pointer;
2025-05-23 23:52:44 +07:00
font-size: 1.5rem;
padding: 0.25rem;
border-radius: 4px;
transition: all 0.3s ease;
}
.close-btn:hover {
background: rgba(108, 117, 125, 0.1);
color: #495057;
}
.modal-content {
2025-05-23 23:52:44 +07:00
margin-bottom: 1.5rem;
color: #6c757d;
line-height: 1.5;
}
.modal-actions {
display: flex;
justify-content: flex-end;
2025-05-23 23:52:44 +07:00
gap: 0.75rem;
}
2025-05-23 23:52:44 +07:00
/* Alert Messages */
.alert {
2025-05-23 23:52:44 +07:00
padding: 0.75rem 1rem;
border-radius: 8px;
margin-bottom: 1rem;
display: flex;
align-items: center;
2025-05-23 23:52:44 +07:00
gap: 0.5rem;
font-size: 0.9rem;
}
.alert.error {
2025-05-23 23:52:44 +07:00
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.alert.success {
2025-05-23 23:52:44 +07:00
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.alert.info {
2025-05-23 23:52:44 +07:00
background: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
2025-05-23 23:52:44 +07:00
.alert i {
font-size: 1rem;
flex-shrink: 0;
}
2025-05-23 23:52:44 +07:00
/* Responsive Design */
/* Tablets */
@media (max-width: 992px) {
.container {
padding: 0 0.75rem;
}
.profile-card,
.info-card {
padding: 1.25rem;
}
.info-grid {
grid-template-columns: 1fr;
gap: 1.25rem;
}
.avatar-section {
flex-direction: column;
text-align: center;
gap: 1rem;
}
.avatar-container {
width: 100px;
height: 100px;
}
.stats-section {
gap: 0.75rem;
}
.stat-icon {
width: 35px;
height: 35px;
font-size: 1rem;
}
.photo-grid {
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 0.75rem;
}
}
/* Mobile Phones */
@media (max-width: 768px) {
.container {
padding: 0 0.5rem;
}
.profile-header {
padding: 0.75rem 0;
}
.header-content {
flex-direction: column;
gap: 0.5rem;
}
.header-actions {
position: static;
transform: none;
}
.section-title {
font-size: 1.2rem;
}
.subtitle {
font-size: 0.8rem;
}
.profile-content {
padding: 0.75rem 0;
}
.profile-layout {
gap: 1rem;
}
.profile-card,
.info-card {
padding: 1rem;
}
.avatar-section {
gap: 0.75rem;
}
.avatar-container {
width: 80px;
height: 80px;
}
.user-name {
font-size: 1.2rem;
}
.user-email {
font-size: 0.85rem;
}
.user-badges {
justify-content: center;
}
.stats-section {
gap: 0.5rem;
}
.stat-icon {
width: 30px;
height: 30px;
font-size: 0.9rem;
}
.stat-value {
font-size: 1rem;
}
.stat-label {
font-size: 0.7rem;
}
.card-header {
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
}
.card-header h3 {
font-size: 1rem;
}
.info-grid {
gap: 1rem;
}
.form-input {
padding: 0.6rem 0.8rem;
font-size: 0.9rem;
}
.action-btn {
padding: 0.5rem 1rem;
font-size: 0.85rem;
}
.photo-grid {
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
gap: 0.5rem;
}
.empty-photos {
padding: 2rem 1rem;
}
.modal-overlay {
padding: 0.5rem;
}
.delete-modal {
padding: 1.25rem;
}
.modal-actions {
flex-direction: column;
gap: 0.5rem;
}
.modal-actions .action-btn {
width: 100%;
justify-content: center;
}
}
/* Small Mobile Phones */
@media (max-width: 480px) {
.container {
padding: 0 0.25rem;
}
.profile-card,
.info-card {
padding: 0.75rem;
margin: 0 0.25rem;
}
.section-title {
font-size: 1.1rem;
}
.subtitle {
font-size: 0.75rem;
}
.avatar-container {
width: 70px;
height: 70px;
}
.user-name {
font-size: 1.1rem;
}
.user-email {
font-size: 0.8rem;
}
.badge {
font-size: 0.7rem;
padding: 0.2rem 0.5rem;
}
.stats-section {
grid-template-columns: repeat(3, 1fr);
gap: 0.25rem;
}
.stat-icon {
width: 25px;
height: 25px;
font-size: 0.8rem;
}
.stat-value {
font-size: 0.9rem;
}
.stat-label {
font-size: 0.65rem;
}
.card-header h3 {
font-size: 0.95rem;
}
.info-item label {
font-size: 0.8rem;
}
.info-item span {
font-size: 0.9rem;
padding: 0.6rem 0.8rem;
}
.form-input {
padding: 0.5rem 0.7rem;
font-size: 0.85rem;
}
.action-btn {
padding: 0.4rem 0.8rem;
font-size: 0.8rem;
}
.photo-grid {
grid-template-columns: repeat(2, 1fr);
gap: 0.5rem;
}
.empty-photos {
padding: 1.5rem 0.75rem;
}
.empty-photos i {
font-size: 2.5rem;
}
.empty-photos h4 {
font-size: 1rem;
}
.empty-photos p {
font-size: 0.8rem;
}
}
/* Very Small Screens */
@media (max-width: 375px) {
.profile-card,
.info-card {
margin: 0 0.125rem;
padding: 0.6rem;
}
.avatar-section {
gap: 0.5rem;
}
.avatar-container {
width: 60px;
height: 60px;
}
.user-name {
font-size: 1rem;
}
.user-badges {
gap: 0.3rem;
}
.badge {
font-size: 0.65rem;
padding: 0.15rem 0.4rem;
}
.action-btn {
padding: 0.4rem 0.7rem;
font-size: 0.75rem;
}
.photo-grid {
grid-template-columns: repeat(2, 1fr);
}
}
/* Landscape Orientation on Mobile */
@media (max-height: 450px) and (orientation: landscape) {
.profile-header {
padding: 0.5rem 0;
height: 46px;
}
.section-title {
font-size: 1rem;
}
.subtitle {
font-size: 0.7rem;
}
.profile-content {
padding: 0.5rem 0;
}
.avatar-section {
flex-direction: row;
gap: 1rem;
}
.avatar-container {
width: 60px;
height: 60px;
}
.stats-section {
margin-top: 0.5rem;
padding-top: 0.5rem;
}
.photo-grid {
grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
}
}
/* High DPI Displays */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
.avatar-image,
.photo-image {
image-rendering: -webkit-optimize-contrast;
}
}
/* Touch Devices - Improved Touch Targets */
@media (pointer: coarse) {
.action-btn {
min-height: 44px;
min-width: 44px;
}
.clear-btn {
min-width: 44px;
min-height: 44px;
}
.dropdown-option {
min-height: 44px;
display: flex;
align-items: center;
}
.change-avatar-btn {
min-width: 44px;
min-height: 44px;
}
}
/* iOS Safe Area Support */
@supports (padding-bottom: env(safe-area-inset-bottom)) {
.profile-content {
padding-bottom: calc(1rem + var(--nav-height, 60px) + env(safe-area-inset-bottom, 0px));
}
}
/* Reduced Motion Support */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
.spinner,
.spinner-small {
animation: none;
}
}
/* High Contrast Mode Support */
@media (prefers-contrast: high) {
.profile-card,
.info-card {
border: 2px solid;
}
.action-btn {
border: 2px solid;
}
}
/* Print Styles */
@media print {
.profile-header,
.header-actions,
.action-btn,
.photo-actions,
.modal-overlay {
display: none !important;
}
.profile-content {
padding: 0;
}
.profile-card,
.info-card {
box-shadow: none;
border: 1px solid #000;
}
}
</style>