/
RoditelevVV
/
web-static-labs
Обзор
Документация
Войти
/
RoditelevVV
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
html/lab6/task7/script.js
323 строки
12 KB
karpov
finish lab5, proba lab6
19 мар 2026, 17:02
19 мар 2026, 17:02
e0606a0
Код
Авторство
О чём код?
'use strict'; class UserProfile { constructor() { // Ключ для localStorage this.STORAGE_KEY = 'user_profiles'; // API URL this.apiUrl = 'https://randomuser.me/api/'; // Элементы DOM this.profileContainer = document.getElementById('profileContainer'); this.profilesCount = document.getElementById('profilesCount'); this.todayCount = document.getElementById('todayCount'); this.loadBtn = document.getElementById('loadBtn'); this.deleteBtn = document.getElementById('deleteBtn'); this.statusDiv = document.getElementById('status'); // Массив профилей this.profiles = []; // Текущий профиль this.currentProfile = null; this.init(); } init() { // Загружаем профили из localStorage this.loadFromStorage(); // Обновляем статистику this.updateStats(); // Показываем последний профиль, если есть if (this.profiles.length > 0) { this.currentProfile = this.profiles[0]; this.displayProfile(this.currentProfile); } else { this.showNoProfile(); } // Обработчики кнопок this.loadBtn.addEventListener('click', () => this.loadNewProfile()); this.deleteBtn.addEventListener('click', () => this.deleteCurrentProfile()); } // Загрузка из localStorage loadFromStorage() { try { const saved = localStorage.getItem(this.STORAGE_KEY); if (saved) { this.profiles = JSON.parse(saved); } else { this.profiles = []; } } catch (error) { console.error('Ошибка загрузки из localStorage:', error); this.profiles = []; } } // Сохранение в localStorage saveToStorage() { try { localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.profiles)); // Обновляем статистику на главной странице this.updateStats(); // Отправляем событие для обновления на других страницах window.dispatchEvent(new StorageEvent('storage', { key: this.STORAGE_KEY, newValue: JSON.stringify(this.profiles) })); } catch (error) { console.error('Ошибка сохранения в localStorage:', error); this.showStatus('Ошибка сохранения', 'error'); } } // Загрузка нового профиля из API async loadNewProfile() { this.showLoading(); try { const response = await fetch(this.apiUrl); if (!response.ok) { throw new Error(`Ошибка HTTP: ${response.status}`); } const data = await response.json(); const user = data.results[0]; // Создаем объект профиля const profile = { id: `${user.login.uuid}-${Date.now()}`, loadedAt: new Date().toISOString(), name: { title: user.name.title, first: user.name.first, last: user.name.last }, username: user.login.username, email: user.email, phone: user.phone, cell: user.cell, gender: user.gender, dob: { date: user.dob.date, age: user.dob.age }, location: { street: `${user.location.street.number} ${user.location.street.name}`, city: user.location.city, state: user.location.state, country: user.location.country, postcode: user.location.postcode }, picture: { large: user.picture.large, medium: user.picture.medium, thumbnail: user.picture.thumbnail }, nationality: user.nat }; // Добавляем в начало массива this.profiles.unshift(profile); // Сохраняем this.saveToStorage(); // Отображаем this.currentProfile = profile; this.displayProfile(profile); this.showStatus('✅ Профиль успешно загружен и сохранен!', 'success'); } catch (error) { console.error('Ошибка загрузки:', error); this.showStatus('❌ Ошибка загрузки профиля', 'error'); this.showNoProfile(); } } // Удаление текущего профиля deleteCurrentProfile() { if (!this.currentProfile) { this.showStatus('Нет профиля для удаления', 'error'); return; } if (confirm('Удалить текущий профиль?')) { // Удаляем из массива this.profiles = this.profiles.filter(p => p.id !== this.currentProfile.id); // Сохраняем this.saveToStorage(); // Показываем следующий профиль или сообщение if (this.profiles.length > 0) { this.currentProfile = this.profiles[0]; this.displayProfile(this.currentProfile); } else { this.currentProfile = null; this.showNoProfile(); } this.showStatus('✅ Профиль удален', 'success'); } } // Отображение профиля displayProfile(profile) { const formatDate = (isoString) => { const date = new Date(isoString); return date.toLocaleDateString('ru-RU', { year: 'numeric', month: 'long', day: 'numeric' }); }; const formatDateTime = (isoString) => { const date = new Date(isoString); return date.toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); }; const fullName = `${profile.name.first} ${profile.name.last}`; const gender = profile.gender === 'male' ? 'Мужской' : 'Женский'; const birthDate = formatDate(profile.dob.date); const loadedDate = formatDateTime(profile.loadedAt); this.profileContainer.innerHTML = ` <div class="profile-card"> <div class="delete-icon" onclick="window.profileManager.deleteProfile('${profile.id}')">✕</div> <div class="profile-header"> <img src="${profile.picture.large}" alt="${fullName}" class="profile-avatar"> <div> <div class="profile-name">${fullName}</div> <div class="profile-username">@${profile.username}</div> </div> </div> <div class="profile-details"> <div class="detail-item"> <div class="detail-label">Email</div> <div class="detail-value">${profile.email}</div> </div> <div class="detail-item"> <div class="detail-label">Телефон</div> <div class="detail-value">${profile.phone}</div> </div> <div class="detail-item"> <div class="detail-label">Пол</div> <div class="detail-value">${gender}</div> </div> <div class="detail-item"> <div class="detail-label">Возраст</div> <div class="detail-value">${profile.dob.age} лет</div> </div> <div class="detail-item"> <div class="detail-label">Дата рождения</div> <div class="detail-value">${birthDate}</div> </div> <div class="detail-item"> <div class="detail-label">Страна</div> <div class="detail-value">${profile.location.country}</div> </div> <div class="detail-item"> <div class="detail-label">Город</div> <div class="detail-value">${profile.location.city}</div> </div> <div class="detail-item"> <div class="detail-label">Адрес</div> <div class="detail-value">${profile.location.street}</div> </div> </div> <div style="font-size: 11px; color: #999; margin-top: 10px;"> Загружен: ${loadedDate} </div> </div> `; // Делаем функцию доступной глобально для удаления window.profileManager = this; } // Удаление профиля по ID (вызывается из карточки) deleteProfile(id) { if (confirm('Удалить этот профиль?')) { this.profiles = this.profiles.filter(p => p.id !== id); this.saveToStorage(); if (this.currentProfile && this.currentProfile.id === id) { if (this.profiles.length > 0) { this.currentProfile = this.profiles[0]; this.displayProfile(this.currentProfile); } else { this.currentProfile = null; this.showNoProfile(); } } this.showStatus('✅ Профиль удален', 'success'); } } // Показать сообщение о пустом профиле showNoProfile() { this.profileContainer.innerHTML = ` <div class="no-profile"> Нет сохраненных профилей. Нажмите "Загрузить новый профиль" </div> `; } // Показать загрузку showLoading() { this.profileContainer.innerHTML = ` <div class="loading">⏳ Загрузка профиля...</div> `; } // Обновление статистики updateStats() { this.profilesCount.textContent = this.profiles.length; // Считаем загруженные сегодня const today = new Date().toDateString(); const todayProfiles = this.profiles.filter(p => { const loadDate = new Date(p.loadedAt).toDateString(); return loadDate === today; }); this.todayCount.textContent = todayProfiles.length; } // Показать статус showStatus(message, type) { this.statusDiv.textContent = message; this.statusDiv.className = `status ${type}`; setTimeout(() => { this.statusDiv.className = 'status'; }, 3000); } } // Инициализация при загрузке страницы document.addEventListener('DOMContentLoaded', () => { new UserProfile(); });