mirror of
https://github.com/wowlikon/LiB.git
synced 2026-02-04 04:31:09 +00:00
Добавление зарплаты для ролей, добавление статусов книг, обновление фронтэнда
This commit is contained in:
+63
-281
@@ -1,287 +1,69 @@
|
||||
$(function () {
|
||||
const $loginTab = $("#login-tab");
|
||||
const $registerTab = $("#register-tab");
|
||||
const $loginForm = $("#login-form");
|
||||
const $registerForm = $("#register-form");
|
||||
|
||||
const $guestLink = $("#guest-link");
|
||||
const $userBtn = $("#user-btn");
|
||||
const $userDropdown = $("#user-dropdown");
|
||||
const $userArrow = $("#user-arrow");
|
||||
const $userAvatar = $("#user-avatar");
|
||||
const $dropdownName = $("#dropdown-name");
|
||||
const $dropdownUsername = $("#dropdown-username");
|
||||
const $dropdownEmail = $("#dropdown-email");
|
||||
const $logoutBtn = $("#logout-btn");
|
||||
const $menuContainer = $("#user-menu-container");
|
||||
|
||||
function switchToLogin() {
|
||||
$loginTab.addClass("text-gray-700 bg-gray-50 border-b-2 border-gray-500").removeClass("text-gray-400");
|
||||
$registerTab.removeClass("text-gray-700 bg-gray-50 border-b-2 border-gray-500").addClass("text-gray-400");
|
||||
$loginForm.removeClass("hidden"); $registerForm.addClass("hidden");
|
||||
history.replaceState(null, "", "/auth#login");
|
||||
}
|
||||
|
||||
function switchToRegister() {
|
||||
$registerTab.addClass("text-gray-700 bg-gray-50 border-b-2 border-gray-500").removeClass("text-gray-400");
|
||||
$loginTab.removeClass("text-gray-700 bg-gray-50 border-b-2 border-gray-500").addClass("text-gray-400");
|
||||
$registerForm.removeClass("hidden"); $loginForm.addClass("hidden");
|
||||
history.replaceState(null, "", "/auth#register");
|
||||
}
|
||||
|
||||
$loginTab.on("click", switchToLogin);
|
||||
$registerTab.on("click", switchToRegister);
|
||||
|
||||
$("body").on("click", ".toggle-password", function () {
|
||||
const $btn = $(this);
|
||||
const $input = $btn.siblings("input");
|
||||
const $eyeOpen = $btn.find(".eye-open");
|
||||
const $eyeClosed = $btn.find(".eye-closed");
|
||||
|
||||
if ($input.attr("type") === "password") {
|
||||
$input.attr("type", "text");
|
||||
$eyeOpen.addClass("hidden");
|
||||
$eyeClosed.removeClass("hidden");
|
||||
} else {
|
||||
$input.attr("type", "password");
|
||||
$eyeOpen.removeClass("hidden");
|
||||
$eyeClosed.addClass("hidden");
|
||||
}
|
||||
});
|
||||
|
||||
$("#register-password").on("input", function () {
|
||||
const password = $(this).val();
|
||||
let strength = 0;
|
||||
if (password.length >= 8) strength++;
|
||||
if (password.length >= 12) strength++;
|
||||
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
|
||||
if (/\d/.test(password)) strength++;
|
||||
if (/[^a-zA-Z0-9]/.test(password)) strength++;
|
||||
|
||||
const levels = [
|
||||
{ width: "0%", color: "", text: "" },
|
||||
{ width: "20%", color: "bg-red-500", text: "Очень слабый" },
|
||||
{ width: "40%", color: "bg-orange-500", text: "Слабый" },
|
||||
{ width: "60%", color: "bg-yellow-500", text: "Средний" },
|
||||
{ width: "80%", color: "bg-lime-500", text: "Хороший" },
|
||||
{ width: "100%", color: "bg-green-500", text: "Отличный" },
|
||||
];
|
||||
|
||||
const level = levels[strength];
|
||||
const $bar = $("#password-strength-bar");
|
||||
|
||||
$bar.css("width", level.width);
|
||||
$bar.attr("class", "h-full transition-all duration-300 " + level.color);
|
||||
$("#password-strength-text").text(level.text);
|
||||
|
||||
checkPasswordMatch();
|
||||
});
|
||||
|
||||
function checkPasswordMatch() {
|
||||
const password = $("#register-password").val();
|
||||
const confirm = $("#register-password-confirm").val();
|
||||
const $error = $("#password-match-error");
|
||||
|
||||
if (confirm && password !== confirm) {
|
||||
$error.removeClass("hidden");
|
||||
return false;
|
||||
} else {
|
||||
$error.addClass("hidden");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
$("#register-password-confirm").on("input", checkPasswordMatch);
|
||||
|
||||
$loginForm.on("submit", async function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
const $errorDiv = $("#login-error");
|
||||
const $submitBtn = $("#login-submit");
|
||||
const username = $("#login-username").val();
|
||||
const password = $("#login-password").val();
|
||||
|
||||
$errorDiv.addClass("hidden");
|
||||
$submitBtn.prop("disabled", true).text("Вход...");
|
||||
|
||||
try {
|
||||
const formData = new URLSearchParams();
|
||||
formData.append("username", username);
|
||||
formData.append("password", password);
|
||||
|
||||
const response = await fetch("/api/auth/token", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: formData.toString(),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
localStorage.setItem("access_token", data.access_token);
|
||||
if (data.refresh_token) {
|
||||
localStorage.setItem("refresh_token", data.refresh_token);
|
||||
}
|
||||
window.location.href = "/";
|
||||
} else {
|
||||
$errorDiv.text(data.detail || "Неверное имя пользователя или пароль");
|
||||
$errorDiv.removeClass("hidden");
|
||||
$submitBtn.prop("disabled", false).text("Войти");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Login error:", error);
|
||||
$errorDiv.text("Ошибка соединения с сервером");
|
||||
$errorDiv.removeClass("hidden");
|
||||
$submitBtn.prop("disabled", false).text("Войти");
|
||||
}
|
||||
});
|
||||
|
||||
$registerForm.on("submit", async function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
const $errorDiv = $("#register-error");
|
||||
const $successDiv = $("#register-success");
|
||||
const $submitBtn = $("#register-submit");
|
||||
|
||||
if (!checkPasswordMatch()) {
|
||||
$errorDiv.text("Пароли не совпадают").removeClass("hidden");
|
||||
return;
|
||||
}
|
||||
|
||||
const userData = {
|
||||
username: $("#register-username").val(),
|
||||
email: $("#register-email").val(),
|
||||
full_name: $("#register-fullname").val() || null,
|
||||
password: $("#register-password").val(),
|
||||
};
|
||||
|
||||
$errorDiv.addClass("hidden");
|
||||
$successDiv.addClass("hidden");
|
||||
$submitBtn.prop("disabled", true).text("Регистрация...");
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/auth/register", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(userData),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
$successDiv.text("Регистрация успешна! Переключаемся на вход...").removeClass("hidden");
|
||||
setTimeout(() => {
|
||||
$("#login-username").val(userData.username);
|
||||
switchToLogin();
|
||||
}, 2000);
|
||||
} else {
|
||||
let errorMessage = data.detail;
|
||||
if (Array.isArray(data.detail)) {
|
||||
errorMessage = data.detail.map((err) => err.msg).join(". ");
|
||||
}
|
||||
$errorDiv.text(errorMessage || "Ошибка регистрации").removeClass("hidden");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Register error:", error);
|
||||
$errorDiv.text("Ошибка соединения с сервером").removeClass("hidden");
|
||||
} finally {
|
||||
$submitBtn.prop("disabled", false).text("Зарегистрироваться");
|
||||
}
|
||||
});
|
||||
|
||||
let isDropdownOpen = false;
|
||||
|
||||
function openDropdown() {
|
||||
isDropdownOpen = true;
|
||||
$userDropdown.removeClass("hidden");
|
||||
$userArrow.addClass("rotate-180");
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
isDropdownOpen = false;
|
||||
$userDropdown.addClass("hidden");
|
||||
$userArrow.removeClass("rotate-180");
|
||||
}
|
||||
|
||||
$userBtn.on("click", function (e) {
|
||||
e.stopPropagation();
|
||||
isDropdownOpen ? closeDropdown() : openDropdown();
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (isDropdownOpen && !$(e.target).closest("#user-menu-container").length) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on("keydown", function (e) {
|
||||
if (e.key === "Escape" && isDropdownOpen) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$logoutBtn.on("click", function () {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
$("#login-form").on("submit", async function (event) {
|
||||
event.preventDefault();
|
||||
const $submitBtn = $("#login-submit");
|
||||
const username = $("#login-username").val();
|
||||
const password = $("#login-password").val();
|
||||
|
||||
$submitBtn.prop("disabled", true).text("Вход...");
|
||||
|
||||
try {
|
||||
const formData = new URLSearchParams();
|
||||
formData.append("username", username);
|
||||
formData.append("password", password);
|
||||
|
||||
const data = await Api.postForm("/api/auth/token", formData);
|
||||
|
||||
localStorage.setItem("access_token", data.access_token);
|
||||
if (data.refresh_token)
|
||||
localStorage.setItem("refresh_token", data.refresh_token);
|
||||
window.location.href = "/";
|
||||
});
|
||||
|
||||
function showGuest() {
|
||||
$guestLink.removeClass("hidden");
|
||||
$userBtn.addClass("hidden").removeClass("flex");
|
||||
closeDropdown();
|
||||
} catch (error) {
|
||||
Utils.showToast(error.message || "Ошибка входа", "error");
|
||||
} finally {
|
||||
$submitBtn.prop("disabled", false).text("Войти");
|
||||
}
|
||||
|
||||
function showUser(user) {
|
||||
$guestLink.addClass("hidden");
|
||||
$userBtn.removeClass("hidden").addClass("flex");
|
||||
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
$userAvatar.text(firstLetter);
|
||||
$dropdownName.text(displayName);
|
||||
$dropdownUsername.text("@" + user.username);
|
||||
$dropdownEmail.text(user.email);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
function updateUserAvatar(email) {
|
||||
if (!email) return;
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const emailHash = sha256(cleanEmail);
|
||||
$("#register-form").on("submit", async function (event) {
|
||||
event.preventDefault();
|
||||
const $submitBtn = $("#register-submit");
|
||||
const pass = $("#register-password").val();
|
||||
const confirm = $("#register-password-confirm").val();
|
||||
|
||||
const avatarUrl = `https://www.gravatar.com/avatar/${emailHash}?d=identicon&s=200`;
|
||||
const avatarImg = document.getElementById('user-avatar');
|
||||
if (avatarImg) { avatarImg.src = avatarUrl; }
|
||||
}
|
||||
|
||||
if (window.location.hash === "#register") { switchToRegister(); }
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
if (!token) {
|
||||
showGuest();
|
||||
} else {
|
||||
fetch("/api/auth/me", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) return response.json();
|
||||
throw new Error("Unauthorized");
|
||||
})
|
||||
.then((user) => {
|
||||
showUser(user);
|
||||
updateUserAvatar(user.email);
|
||||
|
||||
document.getElementById('user-btn').classList.remove('hidden');
|
||||
document.getElementById('guest-link').classList.add('hidden');
|
||||
if (window.location.pathname === "/auth") { window.location.href = "/"; }
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
showGuest();
|
||||
});
|
||||
if (pass !== confirm) {
|
||||
Utils.showToast("Пароли не совпадают", "error");
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const userData = {
|
||||
username: $("#register-username").val(),
|
||||
email: $("#register-email").val(),
|
||||
full_name: $("#register-fullname").val() || null,
|
||||
password: pass,
|
||||
};
|
||||
|
||||
$submitBtn.prop("disabled", true).text("Регистрация...");
|
||||
|
||||
try {
|
||||
await Api.post("/api/auth/register", userData);
|
||||
Utils.showToast("Регистрация успешна! Войдите в систему.", "success");
|
||||
setTimeout(() => window.location.reload(), 1500);
|
||||
} catch (error) {
|
||||
let msg = error.message;
|
||||
if (Array.isArray(error.detail)) {
|
||||
msg = error.detail.map((e) => e.msg).join(". ");
|
||||
}
|
||||
Utils.showToast(msg || "Ошибка регистрации", "error");
|
||||
} finally {
|
||||
$submitBtn.prop("disabled", false).text("Зарегистрироваться");
|
||||
}
|
||||
});
|
||||
|
||||
$("body").on("click", ".toggle-password", function () {
|
||||
const $input = $(this).siblings("input");
|
||||
const type = $input.attr("type") === "password" ? "text" : "password";
|
||||
$input.attr("type", type);
|
||||
$(this).find("svg").toggleClass("hidden");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,305 +1,61 @@
|
||||
$(document).ready(() => {
|
||||
const pathParts = window.location.pathname.split("/");
|
||||
const authorId = pathParts[pathParts.length - 1];
|
||||
|
||||
if (!authorId || isNaN(authorId)) {
|
||||
showErrorState("Некорректный ID автора");
|
||||
const pathParts = window.location.pathname.split("/");
|
||||
const authorId = pathParts[pathParts.length - 1];
|
||||
|
||||
if (!authorId || isNaN(authorId)) {
|
||||
Utils.showToast("Некорректный ID автора", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
Api.get(`/api/authors/${authorId}`)
|
||||
.then((author) => {
|
||||
document.title = `LiB - ${author.name}`;
|
||||
renderAuthor(author);
|
||||
renderBooks(author.books);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
Utils.showToast("Автор не найден", "error");
|
||||
$("#author-loader").html('<p class="text-red-500">Ошибка загрузки</p>');
|
||||
});
|
||||
|
||||
function renderAuthor(author) {
|
||||
$("#author-name").text(author.name);
|
||||
$("#author-id").text(`ID: ${author.id}`);
|
||||
$("#author-avatar").text(author.name.charAt(0).toUpperCase());
|
||||
|
||||
const count = author.books ? author.books.length : 0;
|
||||
$("#author-books-count").text(`${count} книг в библиотеке`);
|
||||
|
||||
$("#author-loader").addClass("hidden");
|
||||
$("#author-content").removeClass("hidden");
|
||||
}
|
||||
|
||||
function renderBooks(books) {
|
||||
const $container = $("#books-container");
|
||||
const tpl = document.getElementById("book-item-template");
|
||||
|
||||
$container.empty();
|
||||
|
||||
if (!books || books.length === 0) {
|
||||
$container.html('<p class="text-gray-500 italic">Книг пока нет</p>');
|
||||
return;
|
||||
}
|
||||
|
||||
loadAuthor(authorId);
|
||||
|
||||
function loadAuthor(id) {
|
||||
showLoadingState();
|
||||
|
||||
fetch(`/api/authors/${id}`)
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
throw new Error("Автор не найден");
|
||||
}
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((author) => {
|
||||
renderAuthor(author);
|
||||
renderBooks(author.books);
|
||||
document.title = `LiB - ${author.name}`;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error loading author:", error);
|
||||
showErrorState(error.message);
|
||||
});
|
||||
}
|
||||
|
||||
function renderAuthor(author) {
|
||||
const $card = $("#author-card");
|
||||
const firstLetter = author.name.charAt(0).toUpperCase();
|
||||
const booksCount = author.books ? author.books.length : 0;
|
||||
const booksWord = getWordForm(booksCount, ["книга", "книги", "книг"]);
|
||||
|
||||
$card.html(`
|
||||
<div class="flex items-start">
|
||||
<!-- Аватар -->
|
||||
<div class="w-24 h-24 bg-gray-500 text-white rounded-full flex items-center justify-center text-4xl font-bold mr-6 flex-shrink-0">
|
||||
${firstLetter}
|
||||
</div>
|
||||
|
||||
<!-- Информация -->
|
||||
<div class="flex-1">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<h1 class="text-3xl font-bold text-gray-900">${escapeHtml(author.name)}</h1>
|
||||
<span class="text-sm text-gray-500">ID: ${author.id}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center text-gray-600 mb-4">
|
||||
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/>
|
||||
</svg>
|
||||
<span>${booksCount} ${booksWord} в библиотеке</span>
|
||||
</div>
|
||||
|
||||
<!-- Кнопка назад -->
|
||||
<a href="/authors" class="inline-flex items-center text-gray-500 hover:text-gray-700 transition-colors">
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
|
||||
</svg>
|
||||
Вернуться к списку авторов
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
function renderBooks(books) {
|
||||
const $container = $("#books-container");
|
||||
$container.empty();
|
||||
|
||||
if (!books || books.length === 0) {
|
||||
$container.html(`
|
||||
<div class="text-center py-8">
|
||||
<svg class="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/>
|
||||
</svg>
|
||||
<p class="text-gray-500">У этого автора пока нет книг в библиотеке</p>
|
||||
</div>
|
||||
`);
|
||||
return;
|
||||
}
|
||||
|
||||
const $grid = $('<div class="space-y-4"></div>');
|
||||
|
||||
books.forEach((book) => {
|
||||
const $bookCard = $(`
|
||||
<div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow duration-200 cursor-pointer book-card" data-id="${book.id}">
|
||||
<div class="flex justify-between items-start">
|
||||
<div class="flex-1">
|
||||
<h3 class="text-lg font-semibold text-gray-900 hover:text-blue-600 transition-colors mb-2">
|
||||
${escapeHtml(book.title)}
|
||||
</h3>
|
||||
<p class="text-gray-600 text-sm line-clamp-3">
|
||||
${escapeHtml(book.description || "Описание отсутствует")}
|
||||
</p>
|
||||
</div>
|
||||
<svg class="w-5 h-5 text-gray-400 ml-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$grid.append($bookCard);
|
||||
});
|
||||
|
||||
$container.append($grid);
|
||||
|
||||
$container.off("click", ".book-card").on("click", ".book-card", function () {
|
||||
const bookId = $(this).data("id");
|
||||
window.location.href = `/book/${bookId}`;
|
||||
});
|
||||
}
|
||||
|
||||
function showLoadingState() {
|
||||
const $authorCard = $("#author-card");
|
||||
const $booksContainer = $("#books-container");
|
||||
|
||||
$authorCard.html(`
|
||||
<div class="flex items-start animate-pulse">
|
||||
<div class="w-24 h-24 bg-gray-200 rounded-full mr-6"></div>
|
||||
<div class="flex-1">
|
||||
<div class="h-8 bg-gray-200 rounded w-1/3 mb-4"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/4 mb-4"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/5"></div>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$booksContainer.html(`
|
||||
<div class="space-y-4">
|
||||
${Array(3)
|
||||
.fill()
|
||||
.map(
|
||||
() => `
|
||||
<div class="border border-gray-200 rounded-lg p-4 animate-pulse">
|
||||
<div class="h-5 bg-gray-200 rounded w-1/2 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-full mb-1"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-3/4"></div>
|
||||
</div>
|
||||
`
|
||||
)
|
||||
.join("")}
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
function showErrorState(message) {
|
||||
const $authorCard = $("#author-card");
|
||||
const $booksSection = $("#books-section");
|
||||
|
||||
$booksSection.hide();
|
||||
|
||||
$authorCard.html(`
|
||||
<div class="text-center py-8">
|
||||
<svg class="mx-auto h-16 w-16 text-red-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
|
||||
</svg>
|
||||
<h3 class="text-xl font-medium text-gray-900 mb-2">${escapeHtml(message)}</h3>
|
||||
<p class="text-gray-500 mb-6">Не удалось загрузить информацию об авторе</p>
|
||||
<div class="flex justify-center gap-4">
|
||||
<button id="retry-btn" class="bg-gray-500 text-white px-6 py-2 rounded-lg hover:bg-gray-600 transition-colors">
|
||||
Попробовать снова
|
||||
</button>
|
||||
<a href="/authors" class="bg-white text-gray-700 px-6 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
|
||||
К списку авторов
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$("#retry-btn").on("click", function () {
|
||||
$booksSection.show();
|
||||
loadAuthor(authorId);
|
||||
});
|
||||
}
|
||||
|
||||
function getWordForm(number, forms) {
|
||||
const cases = [2, 0, 1, 1, 1, 2];
|
||||
const index =
|
||||
number % 100 > 4 && number % 100 < 20
|
||||
? 2
|
||||
: cases[Math.min(number % 10, 5)];
|
||||
return forms[index];
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
const div = document.createElement("div");
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
const $guestLink = $("#guest-link");
|
||||
const $userBtn = $("#user-btn");
|
||||
const $userDropdown = $("#user-dropdown");
|
||||
const $userArrow = $("#user-arrow");
|
||||
const $userAvatar = $("#user-avatar");
|
||||
const $dropdownName = $("#dropdown-name");
|
||||
const $dropdownUsername = $("#dropdown-username");
|
||||
const $dropdownEmail = $("#dropdown-email");
|
||||
const $logoutBtn = $("#logout-btn");
|
||||
|
||||
let isDropdownOpen = false;
|
||||
|
||||
function openDropdown() {
|
||||
isDropdownOpen = true;
|
||||
$userDropdown.removeClass("hidden");
|
||||
$userArrow.addClass("rotate-180");
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
isDropdownOpen = false;
|
||||
$userDropdown.addClass("hidden");
|
||||
$userArrow.removeClass("rotate-180");
|
||||
}
|
||||
|
||||
$userBtn.on("click", function (e) {
|
||||
e.stopPropagation();
|
||||
isDropdownOpen ? closeDropdown() : openDropdown();
|
||||
|
||||
books.forEach((book) => {
|
||||
const clone = tpl.content.cloneNode(true);
|
||||
const card = clone.querySelector(".book-card");
|
||||
|
||||
card.dataset.id = book.id;
|
||||
clone.querySelector(".book-title").textContent = book.title;
|
||||
clone.querySelector(".book-desc").textContent =
|
||||
book.description || "Описание отсутствует";
|
||||
|
||||
$container.append(clone);
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (isDropdownOpen && !$(e.target).closest("#user-menu-container").length) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on("keydown", function (e) {
|
||||
if (e.key === "Escape" && isDropdownOpen) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$logoutBtn.on("click", function () {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
function showGuest() {
|
||||
$guestLink.removeClass("hidden");
|
||||
$userBtn.addClass("hidden").removeClass("flex");
|
||||
closeDropdown();
|
||||
}
|
||||
|
||||
function showUser(user) {
|
||||
$guestLink.addClass("hidden");
|
||||
$userBtn.removeClass("hidden").addClass("flex");
|
||||
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
$userAvatar.text(firstLetter);
|
||||
$dropdownName.text(displayName);
|
||||
$dropdownUsername.text("@" + user.username);
|
||||
$dropdownEmail.text(user.email);
|
||||
}
|
||||
|
||||
function updateUserAvatar(email) {
|
||||
if (!email) return;
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const emailHash = sha256(cleanEmail);
|
||||
|
||||
const avatarUrl = `https://www.gravatar.com/avatar/${emailHash}?d=identicon&s=200`;
|
||||
const avatarImg = document.getElementById("user-avatar");
|
||||
if (avatarImg) {
|
||||
avatarImg.src = avatarUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
if (!token) {
|
||||
showGuest();
|
||||
} else {
|
||||
fetch("/api/auth/me", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) return response.json();
|
||||
throw new Error("Unauthorized");
|
||||
})
|
||||
.then((user) => {
|
||||
showUser(user);
|
||||
updateUserAvatar(user.email);
|
||||
|
||||
document.getElementById("user-btn").classList.remove("hidden");
|
||||
document.getElementById("guest-link").classList.add("hidden");
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
showGuest();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$("#books-container").on("click", ".book-card", function () {
|
||||
window.location.href = `/book/${$(this).data("id")}`;
|
||||
});
|
||||
});
|
||||
|
||||
+174
-408
@@ -1,417 +1,183 @@
|
||||
$(document).ready(() => {
|
||||
let allAuthors = [];
|
||||
let filteredAuthors = [];
|
||||
let currentPage = 1;
|
||||
let pageSize = 12;
|
||||
let currentSort = "name_asc";
|
||||
|
||||
loadAuthors();
|
||||
|
||||
function loadAuthors() {
|
||||
showLoadingState();
|
||||
|
||||
fetch("/api/authors")
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
allAuthors = data.authors;
|
||||
applyFiltersAndSort();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error loading authors:", error);
|
||||
showErrorState();
|
||||
});
|
||||
}
|
||||
|
||||
function applyFiltersAndSort() {
|
||||
const searchQuery = $("#author-search-input").val().trim().toLowerCase();
|
||||
|
||||
filteredAuthors = allAuthors.filter((author) =>
|
||||
author.name.toLowerCase().includes(searchQuery)
|
||||
);
|
||||
|
||||
filteredAuthors.sort((a, b) => {
|
||||
const nameA = a.name.toLowerCase();
|
||||
const nameB = b.name.toLowerCase();
|
||||
|
||||
if (currentSort === "name_asc") {
|
||||
return nameA.localeCompare(nameB, "ru");
|
||||
} else {
|
||||
return nameB.localeCompare(nameA, "ru");
|
||||
}
|
||||
let allAuthors = [];
|
||||
let filteredAuthors = [];
|
||||
let currentPage = 1;
|
||||
let pageSize = 12;
|
||||
let currentSort = "name_asc";
|
||||
|
||||
loadAuthors();
|
||||
|
||||
function loadAuthors() {
|
||||
showLoadingState();
|
||||
|
||||
Api.get("/api/authors")
|
||||
.then((data) => {
|
||||
allAuthors = data.authors;
|
||||
applyFiltersAndSort();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
Utils.showToast("Не удалось загрузить авторов", "error");
|
||||
$("#authors-container").empty();
|
||||
});
|
||||
|
||||
updateResultsCounter();
|
||||
|
||||
renderAuthors();
|
||||
renderPagination();
|
||||
}
|
||||
|
||||
function applyFiltersAndSort() {
|
||||
const searchQuery = $("#author-search-input").val().trim().toLowerCase();
|
||||
|
||||
filteredAuthors = allAuthors.filter((author) =>
|
||||
author.name.toLowerCase().includes(searchQuery),
|
||||
);
|
||||
|
||||
filteredAuthors.sort((a, b) => {
|
||||
const nameA = a.name.toLowerCase();
|
||||
const nameB = b.name.toLowerCase();
|
||||
return currentSort === "name_asc"
|
||||
? nameA.localeCompare(nameB, "ru")
|
||||
: nameB.localeCompare(nameA, "ru");
|
||||
});
|
||||
|
||||
const total = filteredAuthors.length;
|
||||
$("#results-counter").text(
|
||||
total === 0 ? "Авторы не найдены" : `Найдено: ${total}`,
|
||||
);
|
||||
|
||||
renderAuthors();
|
||||
renderPagination();
|
||||
}
|
||||
|
||||
function renderAuthors() {
|
||||
const $container = $("#authors-container");
|
||||
const tpl = document.getElementById("author-card-template");
|
||||
const emptyTpl = document.getElementById("empty-state-template");
|
||||
|
||||
$container.empty();
|
||||
|
||||
if (filteredAuthors.length === 0) {
|
||||
$container.append(emptyTpl.content.cloneNode(true));
|
||||
return;
|
||||
}
|
||||
|
||||
function updateResultsCounter() {
|
||||
const $counter = $("#results-counter");
|
||||
const total = filteredAuthors.length;
|
||||
|
||||
if (total === 0) {
|
||||
$counter.text("Авторы не найдены");
|
||||
} else {
|
||||
const wordForm = getWordForm(total, ["автор", "автора", "авторов"]);
|
||||
$counter.text(`Найдено: ${total} ${wordForm}`);
|
||||
|
||||
const startIndex = (currentPage - 1) * pageSize;
|
||||
const pageAuthors = filteredAuthors.slice(
|
||||
startIndex,
|
||||
startIndex + pageSize,
|
||||
);
|
||||
|
||||
pageAuthors.forEach((author) => {
|
||||
const clone = tpl.content.cloneNode(true);
|
||||
const card = clone.querySelector(".author-card");
|
||||
|
||||
card.dataset.id = author.id;
|
||||
clone.querySelector(".author-name").textContent = author.name;
|
||||
clone.querySelector(".author-id").textContent = `ID: ${author.id}`;
|
||||
clone.querySelector(".author-avatar").textContent = author.name
|
||||
.charAt(0)
|
||||
.toUpperCase();
|
||||
|
||||
$container.append(clone);
|
||||
});
|
||||
}
|
||||
|
||||
function renderPagination() {
|
||||
$("#pagination-container").empty();
|
||||
const totalPages = Math.ceil(filteredAuthors.length / pageSize);
|
||||
if (totalPages <= 1) return;
|
||||
|
||||
const $pagination = $(`
|
||||
<div class="flex justify-center items-center gap-2 mt-6 mb-4">
|
||||
<button id="prev-page" class="px-3 py-2 bg-white border rounded-lg hover:bg-gray-50" ${currentPage === 1 ? "disabled" : ""}>←</button>
|
||||
<div id="page-numbers" class="flex gap-1"></div>
|
||||
<button id="next-page" class="px-3 py-2 bg-white border rounded-lg hover:bg-gray-50" ${currentPage === totalPages ? "disabled" : ""}>→</button>
|
||||
</div>
|
||||
`);
|
||||
|
||||
const $pageNumbers = $pagination.find("#page-numbers");
|
||||
const pages = [];
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
if (
|
||||
i === 1 ||
|
||||
i === totalPages ||
|
||||
(i >= currentPage - 2 && i <= currentPage + 2)
|
||||
) {
|
||||
pages.push(i);
|
||||
} else if (pages[pages.length - 1] !== "...") {
|
||||
pages.push("...");
|
||||
}
|
||||
}
|
||||
|
||||
function getWordForm(number, forms) {
|
||||
const cases = [2, 0, 1, 1, 1, 2];
|
||||
const index =
|
||||
number % 100 > 4 && number % 100 < 20
|
||||
? 2
|
||||
: cases[Math.min(number % 10, 5)];
|
||||
return forms[index];
|
||||
}
|
||||
|
||||
function renderAuthors() {
|
||||
const $container = $("#authors-container");
|
||||
$container.empty();
|
||||
|
||||
if (filteredAuthors.length === 0) {
|
||||
$container.html(`
|
||||
<div class="bg-white p-8 rounded-lg shadow-md text-center">
|
||||
<svg class="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
|
||||
</svg>
|
||||
<h3 class="text-lg font-medium text-gray-900 mb-2">Авторы не найдены</h3>
|
||||
<p class="text-gray-500">Попробуйте изменить параметры поиска</p>
|
||||
</div>
|
||||
`);
|
||||
return;
|
||||
pages.forEach((page) => {
|
||||
if (page === "...") {
|
||||
$pageNumbers.append(`<span class="px-3 py-2">...</span>`);
|
||||
} else {
|
||||
const isActive = page === currentPage;
|
||||
$pageNumbers.append(`
|
||||
<button class="page-btn px-3 py-2 rounded-lg ${isActive ? "bg-gray-500 text-white" : "bg-white border hover:bg-gray-50"}" data-page="${page}">${page}</button>
|
||||
`);
|
||||
}
|
||||
|
||||
const startIndex = (currentPage - 1) * pageSize;
|
||||
const endIndex = startIndex + pageSize;
|
||||
const pageAuthors = filteredAuthors.slice(startIndex, endIndex);
|
||||
|
||||
const $grid = $('<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"></div>');
|
||||
|
||||
pageAuthors.forEach((author) => {
|
||||
const firstLetter = author.name.charAt(0).toUpperCase();
|
||||
|
||||
const $authorCard = $(`
|
||||
<div class="bg-white p-4 rounded-lg shadow-md hover:shadow-lg transition-shadow duration-200 cursor-pointer author-card" data-id="${author.id}">
|
||||
<div class="flex items-center">
|
||||
<div class="w-12 h-12 bg-gray-500 text-white rounded-full flex items-center justify-center text-xl font-bold mr-4">
|
||||
${firstLetter}
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<h3 class="text-lg font-semibold text-gray-900 hover:text-blue-600 transition-colors">
|
||||
${escapeHtml(author.name)}
|
||||
</h3>
|
||||
<p class="text-sm text-gray-500">ID: ${author.id}</p>
|
||||
</div>
|
||||
<svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$grid.append($authorCard);
|
||||
});
|
||||
|
||||
$container.append($grid);
|
||||
|
||||
$container.off("click", ".author-card").on("click", ".author-card", function () {
|
||||
const authorId = $(this).data("id");
|
||||
window.location.href = `/author/${authorId}`;
|
||||
});
|
||||
}
|
||||
|
||||
function renderPagination() {
|
||||
const $paginationContainer = $("#pagination-container");
|
||||
$paginationContainer.empty();
|
||||
|
||||
const totalPages = Math.ceil(filteredAuthors.length / pageSize);
|
||||
|
||||
if (totalPages <= 1) return;
|
||||
|
||||
const $pagination = $(`
|
||||
<div class="flex justify-center items-center gap-2 mt-6 mb-4">
|
||||
<button id="prev-page" class="px-3 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" ${currentPage === 1 ? "disabled" : ""}>
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
|
||||
</svg>
|
||||
</button>
|
||||
<div id="page-numbers" class="flex gap-1"></div>
|
||||
<button id="next-page" class="px-3 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" ${currentPage === totalPages ? "disabled" : ""}>
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
`);
|
||||
|
||||
const $pageNumbers = $pagination.find("#page-numbers");
|
||||
|
||||
const pages = generatePageNumbers(currentPage, totalPages);
|
||||
|
||||
pages.forEach((page) => {
|
||||
if (page === "...") {
|
||||
$pageNumbers.append(`<span class="px-3 py-2">...</span>`);
|
||||
} else {
|
||||
const isActive = page === currentPage;
|
||||
$pageNumbers.append(`
|
||||
<button class="page-btn px-3 py-2 rounded-lg ${isActive ? "bg-gray-500 text-white" : "bg-white border border-gray-300 hover:bg-gray-50"}" data-page="${page}">
|
||||
${page}
|
||||
</button>
|
||||
`);
|
||||
}
|
||||
});
|
||||
|
||||
$paginationContainer.append($pagination);
|
||||
|
||||
$paginationContainer.find("#prev-page").on("click", function () {
|
||||
if (currentPage > 1) {
|
||||
currentPage--;
|
||||
renderAuthors();
|
||||
renderPagination();
|
||||
scrollToTop();
|
||||
}
|
||||
});
|
||||
|
||||
$paginationContainer.find("#next-page").on("click", function () {
|
||||
if (currentPage < totalPages) {
|
||||
currentPage++;
|
||||
renderAuthors();
|
||||
renderPagination();
|
||||
scrollToTop();
|
||||
}
|
||||
});
|
||||
|
||||
$paginationContainer.find(".page-btn").on("click", function () {
|
||||
const page = parseInt($(this).data("page"));
|
||||
if (page !== currentPage) {
|
||||
currentPage = page;
|
||||
renderAuthors();
|
||||
renderPagination();
|
||||
scrollToTop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function generatePageNumbers(current, total) {
|
||||
const pages = [];
|
||||
const delta = 2;
|
||||
|
||||
for (let i = 1; i <= total; i++) {
|
||||
if (
|
||||
i === 1 ||
|
||||
i === total ||
|
||||
(i >= current - delta && i <= current + delta)
|
||||
) {
|
||||
pages.push(i);
|
||||
} else if (pages[pages.length - 1] !== "...") {
|
||||
pages.push("...");
|
||||
}
|
||||
});
|
||||
|
||||
$("#pagination-container").append($pagination);
|
||||
|
||||
$("#prev-page").on("click", () => {
|
||||
if (currentPage > 1) {
|
||||
currentPage--;
|
||||
renderAuthors();
|
||||
renderPagination();
|
||||
scrollToTop();
|
||||
}
|
||||
|
||||
return pages;
|
||||
}
|
||||
|
||||
function scrollToTop() {
|
||||
$("html, body").animate({ scrollTop: 0 }, 300);
|
||||
}
|
||||
|
||||
function showLoadingState() {
|
||||
const $container = $("#authors-container");
|
||||
$container.html(`
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
${Array(6)
|
||||
.fill()
|
||||
.map(
|
||||
() => `
|
||||
<div class="bg-white p-4 rounded-lg shadow-md animate-pulse">
|
||||
<div class="flex items-center">
|
||||
<div class="w-12 h-12 bg-gray-200 rounded-full mr-4"></div>
|
||||
<div class="flex-1">
|
||||
<div class="h-5 bg-gray-200 rounded w-3/4 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/4"></div>
|
||||
});
|
||||
$("#next-page").on("click", () => {
|
||||
if (currentPage < totalPages) {
|
||||
currentPage++;
|
||||
renderAuthors();
|
||||
renderPagination();
|
||||
scrollToTop();
|
||||
}
|
||||
});
|
||||
$(".page-btn").on("click", function () {
|
||||
currentPage = parseInt($(this).data("page"));
|
||||
renderAuthors();
|
||||
renderPagination();
|
||||
scrollToTop();
|
||||
});
|
||||
}
|
||||
|
||||
function showLoadingState() {
|
||||
$("#authors-container").html(`
|
||||
${Array(6)
|
||||
.fill()
|
||||
.map(
|
||||
() => `
|
||||
<div class="bg-white p-4 rounded-lg shadow-md animate-pulse flex items-center">
|
||||
<div class="w-12 h-12 bg-gray-200 rounded-full mr-4"></div>
|
||||
<div class="flex-1">
|
||||
<div class="h-5 bg-gray-200 rounded w-3/4 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/4"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
)
|
||||
.join("")}
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
function showErrorState() {
|
||||
const $container = $("#authors-container");
|
||||
$container.html(`
|
||||
<div class="bg-red-50 p-8 rounded-lg shadow-md text-center">
|
||||
<svg class="mx-auto h-12 w-12 text-red-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
|
||||
</svg>
|
||||
<h3 class="text-lg font-medium text-red-900 mb-2">Ошибка загрузки</h3>
|
||||
<p class="text-red-700 mb-4">Не удалось загрузить список авторов</p>
|
||||
<button id="retry-btn" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700">
|
||||
Попробовать снова
|
||||
</button>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$("#retry-btn").on("click", loadAuthors);
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
const div = document.createElement("div");
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function initializeFilters() {
|
||||
const $authorSearch = $("#author-search-input");
|
||||
const $resetBtn = $("#reset-filters-btn");
|
||||
const $sortRadios = $('input[name="sort"]');
|
||||
|
||||
let searchTimeout;
|
||||
$authorSearch.on("input", function () {
|
||||
clearTimeout(searchTimeout);
|
||||
searchTimeout = setTimeout(() => {
|
||||
currentPage = 1;
|
||||
applyFiltersAndSort();
|
||||
}, 300);
|
||||
});
|
||||
|
||||
$authorSearch.on("keypress", function (e) {
|
||||
if (e.which === 13) {
|
||||
clearTimeout(searchTimeout);
|
||||
currentPage = 1;
|
||||
applyFiltersAndSort();
|
||||
}
|
||||
});
|
||||
|
||||
$sortRadios.on("change", function () {
|
||||
currentSort = $(this).val();
|
||||
currentPage = 1;
|
||||
applyFiltersAndSort();
|
||||
});
|
||||
|
||||
$resetBtn.on("click", function () {
|
||||
$authorSearch.val("");
|
||||
$('input[name="sort"][value="name_asc"]').prop("checked", true);
|
||||
currentSort = "name_asc";
|
||||
currentPage = 1;
|
||||
applyFiltersAndSort();
|
||||
});
|
||||
}
|
||||
|
||||
initializeFilters();
|
||||
|
||||
const $guestLink = $("#guest-link");
|
||||
const $userBtn = $("#user-btn");
|
||||
const $userDropdown = $("#user-dropdown");
|
||||
const $userArrow = $("#user-arrow");
|
||||
const $userAvatar = $("#user-avatar");
|
||||
const $dropdownName = $("#dropdown-name");
|
||||
const $dropdownUsername = $("#dropdown-username");
|
||||
const $dropdownEmail = $("#dropdown-email");
|
||||
const $logoutBtn = $("#logout-btn");
|
||||
|
||||
let isDropdownOpen = false;
|
||||
|
||||
function openDropdown() {
|
||||
isDropdownOpen = true;
|
||||
$userDropdown.removeClass("hidden");
|
||||
$userArrow.addClass("rotate-180");
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
isDropdownOpen = false;
|
||||
$userDropdown.addClass("hidden");
|
||||
$userArrow.removeClass("rotate-180");
|
||||
}
|
||||
|
||||
$userBtn.on("click", function (e) {
|
||||
e.stopPropagation();
|
||||
isDropdownOpen ? closeDropdown() : openDropdown();
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (isDropdownOpen && !$(e.target).closest("#user-menu-container").length) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on("keydown", function (e) {
|
||||
if (e.key === "Escape" && isDropdownOpen) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$logoutBtn.on("click", function () {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
function showGuest() {
|
||||
$guestLink.removeClass("hidden");
|
||||
$userBtn.addClass("hidden").removeClass("flex");
|
||||
closeDropdown();
|
||||
}
|
||||
|
||||
function showUser(user) {
|
||||
$guestLink.addClass("hidden");
|
||||
$userBtn.removeClass("hidden").addClass("flex");
|
||||
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
$userAvatar.text(firstLetter);
|
||||
$dropdownName.text(displayName);
|
||||
$dropdownUsername.text("@" + user.username);
|
||||
$dropdownEmail.text(user.email);
|
||||
}
|
||||
|
||||
function updateUserAvatar(email) {
|
||||
if (!email) return;
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const emailHash = sha256(cleanEmail);
|
||||
|
||||
const avatarUrl = `https://www.gravatar.com/avatar/${emailHash}?d=identicon&s=200`;
|
||||
const avatarImg = document.getElementById("user-avatar");
|
||||
if (avatarImg) {
|
||||
avatarImg.src = avatarUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
if (!token) {
|
||||
showGuest();
|
||||
} else {
|
||||
fetch("/api/auth/me", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) return response.json();
|
||||
throw new Error("Unauthorized");
|
||||
})
|
||||
.then((user) => {
|
||||
showUser(user);
|
||||
updateUserAvatar(user.email);
|
||||
|
||||
document.getElementById("user-btn").classList.remove("hidden");
|
||||
document.getElementById("guest-link").classList.add("hidden");
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
showGuest();
|
||||
});
|
||||
}
|
||||
});
|
||||
`,
|
||||
)
|
||||
.join("")}
|
||||
`);
|
||||
}
|
||||
|
||||
function scrollToTop() {
|
||||
$("html, body").animate({ scrollTop: 0 }, 300);
|
||||
}
|
||||
|
||||
$("#author-search-input").on("input", function () {
|
||||
currentPage = 1;
|
||||
applyFiltersAndSort();
|
||||
});
|
||||
|
||||
$('input[name="sort"]').on("change", function () {
|
||||
currentSort = $(this).val();
|
||||
currentPage = 1;
|
||||
applyFiltersAndSort();
|
||||
});
|
||||
|
||||
$("#authors-container").on("click", ".author-card", function () {
|
||||
window.location.href = `/author/${$(this).data("id")}`;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<svg
|
||||
width="800px"
|
||||
height="800px"
|
||||
viewBox="0 0 15 15"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
clip-rule="evenodd"
|
||||
d="M0.877014 7.49988C0.877014 3.84219 3.84216 0.877045 7.49985 0.877045C11.1575 0.877045 14.1227 3.84219 14.1227 7.49988C14.1227 11.1575 11.1575 14.1227 7.49985 14.1227C3.84216 14.1227 0.877014 11.1575 0.877014 7.49988ZM7.49985 1.82704C4.36683 1.82704 1.82701 4.36686 1.82701 7.49988C1.82701 8.97196 2.38774 10.3131 3.30727 11.3213C4.19074 9.94119 5.73818 9.02499 7.50023 9.02499C9.26206 9.02499 10.8093 9.94097 11.6929 11.3208C12.6121 10.3127 13.1727 8.97172 13.1727 7.49988C13.1727 4.36686 10.6328 1.82704 7.49985 1.82704ZM10.9818 11.9787C10.2839 10.7795 8.9857 9.97499 7.50023 9.97499C6.01458 9.97499 4.71624 10.7797 4.01845 11.9791C4.97952 12.7272 6.18765 13.1727 7.49985 13.1727C8.81227 13.1727 10.0206 12.727 10.9818 11.9787ZM5.14999 6.50487C5.14999 5.207 6.20212 4.15487 7.49999 4.15487C8.79786 4.15487 9.84999 5.207 9.84999 6.50487C9.84999 7.80274 8.79786 8.85487 7.49999 8.85487C6.20212 8.85487 5.14999 7.80274 5.14999 6.50487ZM7.49999 5.10487C6.72679 5.10487 6.09999 5.73167 6.09999 6.50487C6.09999 7.27807 6.72679 7.90487 7.49999 7.90487C8.27319 7.90487 8.89999 7.27807 8.89999 6.50487C8.89999 5.73167 8.27319 5.10487 7.49999 5.10487Z"
|
||||
fill="#000000"
|
||||
/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,116 @@
|
||||
$(function () {
|
||||
const $guestLink = $("#guest-link");
|
||||
const $userBtn = $("#user-btn");
|
||||
const $userDropdown = $("#user-dropdown");
|
||||
const $userArrow = $("#user-arrow");
|
||||
const $userAvatar = $("#user-avatar");
|
||||
const $dropdownName = $("#dropdown-name");
|
||||
const $dropdownUsername = $("#dropdown-username");
|
||||
const $dropdownEmail = $("#dropdown-email");
|
||||
const $logoutBtn = $("#logout-btn");
|
||||
const $menuContainer = $("#user-menu-area");
|
||||
|
||||
let isDropdownOpen = false;
|
||||
|
||||
function openDropdown() {
|
||||
isDropdownOpen = true;
|
||||
$userDropdown.removeClass("hidden");
|
||||
$userArrow.addClass("rotate-180");
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
isDropdownOpen = false;
|
||||
$userDropdown.addClass("hidden");
|
||||
$userArrow.removeClass("rotate-180");
|
||||
}
|
||||
|
||||
$userBtn.on("click", function (e) {
|
||||
e.stopPropagation();
|
||||
isDropdownOpen ? closeDropdown() : openDropdown();
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (isDropdownOpen && !$(e.target).closest("#user-menu-area").length) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on("keydown", function (e) {
|
||||
if (e.key === "Escape" && isDropdownOpen) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$logoutBtn.on("click", function () {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
function showGuest() {
|
||||
$guestLink.removeClass("hidden");
|
||||
$userBtn.addClass("hidden").removeClass("flex");
|
||||
closeDropdown();
|
||||
}
|
||||
|
||||
function showUser(user) {
|
||||
$guestLink.addClass("hidden");
|
||||
$userBtn.removeClass("hidden").addClass("flex");
|
||||
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
$userAvatar.text(firstLetter);
|
||||
|
||||
$dropdownName.text(displayName);
|
||||
$dropdownUsername.text("@" + user.username);
|
||||
$dropdownEmail.text(user.email);
|
||||
}
|
||||
|
||||
function updateUserAvatar(email) {
|
||||
if (!email) return;
|
||||
if (typeof sha256 === "undefined") {
|
||||
console.warn("sha256 library not loaded yet");
|
||||
return;
|
||||
}
|
||||
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const emailHash = sha256(cleanEmail);
|
||||
|
||||
const avatarUrl = `https://www.gravatar.com/avatar/${emailHash}?d=identicon&s=200`;
|
||||
const avatarImg = document.getElementById("user-avatar");
|
||||
if (avatarImg) {
|
||||
avatarImg.src = avatarUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
if (!token) {
|
||||
showGuest();
|
||||
} else {
|
||||
fetch("/api/auth/me", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) return response.json();
|
||||
throw new Error("Unauthorized");
|
||||
})
|
||||
.then((user) => {
|
||||
showUser(user);
|
||||
updateUserAvatar(user.email);
|
||||
|
||||
document.getElementById("user-btn").classList.remove("hidden");
|
||||
document.getElementById("guest-link").classList.add("hidden");
|
||||
|
||||
if (window.location.pathname === "/auth") {
|
||||
window.location.href = "/";
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
showGuest();
|
||||
});
|
||||
}
|
||||
});
|
||||
+110
-308
@@ -1,321 +1,123 @@
|
||||
$(document).ready(() => {
|
||||
const pathParts = window.location.pathname.split("/");
|
||||
const bookId = pathParts[pathParts.length - 1];
|
||||
const STATUS_CONFIG = {
|
||||
active: {
|
||||
label: "Доступна",
|
||||
bgClass: "bg-green-100",
|
||||
textClass: "text-green-800",
|
||||
icon: `<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>`,
|
||||
},
|
||||
borrowed: {
|
||||
label: "Выдана",
|
||||
bgClass: "bg-yellow-100",
|
||||
textClass: "text-yellow-800",
|
||||
icon: `<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>`,
|
||||
},
|
||||
reserved: {
|
||||
label: "Забронирована",
|
||||
bgClass: "bg-blue-100",
|
||||
textClass: "text-blue-800",
|
||||
icon: `<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z"></path>
|
||||
</svg>`,
|
||||
},
|
||||
restoration: {
|
||||
label: "На реставрации",
|
||||
bgClass: "bg-orange-100",
|
||||
textClass: "text-orange-800",
|
||||
icon: `<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"></path>
|
||||
</svg>`,
|
||||
},
|
||||
written_off: {
|
||||
label: "Списана",
|
||||
bgClass: "bg-red-100",
|
||||
textClass: "text-red-800",
|
||||
icon: `<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"></path>
|
||||
</svg>`,
|
||||
},
|
||||
};
|
||||
|
||||
if (!bookId || isNaN(bookId)) {
|
||||
showErrorState("Некорректный ID книги");
|
||||
return;
|
||||
}
|
||||
function getStatusConfig(status) {
|
||||
return (
|
||||
STATUS_CONFIG[status] || {
|
||||
label: status || "Неизвестно",
|
||||
bgClass: "bg-gray-100",
|
||||
textClass: "text-gray-800",
|
||||
icon: "",
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
loadBook(bookId);
|
||||
const pathParts = window.location.pathname.split("/");
|
||||
const bookId = pathParts[pathParts.length - 1];
|
||||
|
||||
function loadBook(id) {
|
||||
showLoadingState();
|
||||
if (!bookId || isNaN(bookId)) {
|
||||
Utils.showToast("Некорректный ID книги", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`/api/books/${id}`)
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
throw new Error("Книга не найдена");
|
||||
}
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((book) => {
|
||||
renderBook(book);
|
||||
renderAuthors(book.authors);
|
||||
renderGenres(book.genres);
|
||||
document.title = `LiB - ${book.title}`;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error loading book:", error);
|
||||
showErrorState(error.message);
|
||||
});
|
||||
}
|
||||
|
||||
function renderBook(book) {
|
||||
const $card = $("#book-card");
|
||||
const authorsText = book.authors.map((a) => a.name).join(", ") || "Автор неизвестен";
|
||||
|
||||
$card.html(`
|
||||
<div class="flex flex-col md:flex-row items-start">
|
||||
<!-- Иконка книги -->
|
||||
<div class="w-32 h-40 bg-gradient-to-br from-gray-400 to-gray-600 rounded-lg flex items-center justify-center mb-4 md:mb-0 md:mr-6 flex-shrink-0 shadow-md">
|
||||
<svg class="w-16 h-16 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Информация о книге -->
|
||||
<div class="flex-1">
|
||||
<div class="flex items-start justify-between mb-2">
|
||||
<h1 class="text-3xl font-bold text-gray-900">${escapeHtml(book.title)}</h1>
|
||||
<span class="text-sm text-gray-500 ml-4">ID: ${book.id}</span>
|
||||
</div>
|
||||
|
||||
<p class="text-lg text-gray-600 mb-4">
|
||||
${escapeHtml(authorsText)}
|
||||
</p>
|
||||
|
||||
<div class="prose prose-gray max-w-none mb-6">
|
||||
<p class="text-gray-700 leading-relaxed">
|
||||
${escapeHtml(book.description || "Описание отсутствует")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Кнопка назад -->
|
||||
<a href="/books" class="inline-flex items-center text-gray-500 hover:text-gray-700 transition-colors">
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
|
||||
</svg>
|
||||
Вернуться к списку книг
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
function renderAuthors(authors) {
|
||||
const $container = $("#authors-container");
|
||||
const $section = $("#authors-section");
|
||||
$container.empty();
|
||||
|
||||
if (!authors || authors.length === 0) {
|
||||
$section.hide();
|
||||
return;
|
||||
}
|
||||
|
||||
const $grid = $('<div class="flex flex-wrap gap-3"></div>');
|
||||
|
||||
authors.forEach((author) => {
|
||||
const firstLetter = author.name.charAt(0).toUpperCase();
|
||||
|
||||
const $authorCard = $(`
|
||||
<a href="/author/${author.id}" class="flex items-center bg-gray-50 hover:bg-gray-100 rounded-lg p-3 transition-colors duration-200 border border-gray-200">
|
||||
<div class="w-10 h-10 bg-gray-500 text-white rounded-full flex items-center justify-center text-lg font-bold mr-3">
|
||||
${firstLetter}
|
||||
</div>
|
||||
<span class="text-gray-900 font-medium">${escapeHtml(author.name)}</span>
|
||||
<svg class="w-4 h-4 text-gray-400 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
</a>
|
||||
`);
|
||||
|
||||
$grid.append($authorCard);
|
||||
});
|
||||
|
||||
$container.append($grid);
|
||||
}
|
||||
|
||||
function renderGenres(genres) {
|
||||
const $container = $("#genres-container");
|
||||
const $section = $("#genres-section");
|
||||
$container.empty();
|
||||
|
||||
if (!genres || genres.length === 0) {
|
||||
$section.hide();
|
||||
return;
|
||||
}
|
||||
|
||||
const $grid = $('<div class="flex flex-wrap gap-2"></div>');
|
||||
|
||||
genres.forEach((genre) => {
|
||||
const $genreTag = $(`
|
||||
<a href="/books?genre_id=${genre.id}" class="inline-flex items-center bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-2 rounded-full transition-colors duration-200">
|
||||
<svg class="w-4 h-4 mr-2 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/>
|
||||
</svg>
|
||||
${escapeHtml(genre.name)}
|
||||
</a>
|
||||
`);
|
||||
|
||||
$grid.append($genreTag);
|
||||
});
|
||||
|
||||
$container.append($grid);
|
||||
}
|
||||
|
||||
function showLoadingState() {
|
||||
const $bookCard = $("#book-card");
|
||||
const $authorsContainer = $("#authors-container");
|
||||
const $genresContainer = $("#genres-container");
|
||||
|
||||
$bookCard.html(`
|
||||
<div class="flex flex-col md:flex-row items-start animate-pulse">
|
||||
<div class="w-32 h-40 bg-gray-200 rounded-lg mb-4 md:mb-0 md:mr-6"></div>
|
||||
<div class="flex-1">
|
||||
<div class="h-8 bg-gray-200 rounded w-2/3 mb-4"></div>
|
||||
<div class="h-5 bg-gray-200 rounded w-1/3 mb-4"></div>
|
||||
<div class="space-y-2 mb-6">
|
||||
<div class="h-4 bg-gray-200 rounded w-full"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-full"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-3/4"></div>
|
||||
</div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/4"></div>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$authorsContainer.html(`
|
||||
<div class="flex gap-3 animate-pulse">
|
||||
<div class="flex items-center bg-gray-100 rounded-lg p-3">
|
||||
<div class="w-10 h-10 bg-gray-200 rounded-full mr-3"></div>
|
||||
<div class="h-5 bg-gray-200 rounded w-24"></div>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$genresContainer.html(`
|
||||
<div class="flex gap-2 animate-pulse">
|
||||
<div class="h-10 bg-gray-200 rounded-full w-24"></div>
|
||||
<div class="h-10 bg-gray-200 rounded-full w-32"></div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
function showErrorState(message) {
|
||||
const $bookCard = $("#book-card");
|
||||
const $authorsSection = $("#authors-section");
|
||||
const $genresSection = $("#genres-section");
|
||||
|
||||
$authorsSection.hide();
|
||||
$genresSection.hide();
|
||||
|
||||
$bookCard.html(`
|
||||
<div class="text-center py-8">
|
||||
<svg class="mx-auto h-16 w-16 text-red-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
|
||||
</svg>
|
||||
<h3 class="text-xl font-medium text-gray-900 mb-2">${escapeHtml(message)}</h3>
|
||||
<p class="text-gray-500 mb-6">Не удалось загрузить информацию о книге</p>
|
||||
<div class="flex justify-center gap-4">
|
||||
<button id="retry-btn" class="bg-gray-500 text-white px-6 py-2 rounded-lg hover:bg-gray-600 transition-colors">
|
||||
Попробовать снова
|
||||
</button>
|
||||
<a href="/books" class="bg-white text-gray-700 px-6 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
|
||||
К списку книг
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$("#retry-btn").on("click", function () {
|
||||
$authorsSection.show();
|
||||
$genresSection.show();
|
||||
loadBook(bookId);
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
const div = document.createElement("div");
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
const $guestLink = $("#guest-link");
|
||||
const $userBtn = $("#user-btn");
|
||||
const $userDropdown = $("#user-dropdown");
|
||||
const $userArrow = $("#user-arrow");
|
||||
const $userAvatar = $("#user-avatar");
|
||||
const $dropdownName = $("#dropdown-name");
|
||||
const $dropdownUsername = $("#dropdown-username");
|
||||
const $dropdownEmail = $("#dropdown-email");
|
||||
const $logoutBtn = $("#logout-btn");
|
||||
|
||||
let isDropdownOpen = false;
|
||||
|
||||
function openDropdown() {
|
||||
isDropdownOpen = true;
|
||||
$userDropdown.removeClass("hidden");
|
||||
$userArrow.addClass("rotate-180");
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
isDropdownOpen = false;
|
||||
$userDropdown.addClass("hidden");
|
||||
$userArrow.removeClass("rotate-180");
|
||||
}
|
||||
|
||||
$userBtn.on("click", function (e) {
|
||||
e.stopPropagation();
|
||||
isDropdownOpen ? closeDropdown() : openDropdown();
|
||||
Api.get(`/api/books/${bookId}`)
|
||||
.then((book) => {
|
||||
document.title = `LiB - ${book.title}`;
|
||||
renderBook(book);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
Utils.showToast("Книга не найдена", "error");
|
||||
$("#book-loader").html(
|
||||
'<p class="text-center text-red-500 w-full p-4">Ошибка загрузки</p>',
|
||||
);
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (isDropdownOpen && !$(e.target).closest("#user-menu-container").length) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
function renderBook(book) {
|
||||
$("#book-title").text(book.title);
|
||||
$("#book-id").text(`ID: ${book.id}`);
|
||||
$("#book-authors-text").text(
|
||||
book.authors.map((a) => a.name).join(", ") || "Автор неизвестен",
|
||||
);
|
||||
$("#book-description").text(book.description || "Описание отсутствует");
|
||||
|
||||
$(document).on("keydown", function (e) {
|
||||
if (e.key === "Escape" && isDropdownOpen) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
const statusConfig = getStatusConfig(book.status);
|
||||
$("#book-status")
|
||||
.html(statusConfig.icon + statusConfig.label)
|
||||
.removeClass()
|
||||
.addClass(
|
||||
`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${statusConfig.bgClass} ${statusConfig.textClass}`,
|
||||
);
|
||||
|
||||
$logoutBtn.on("click", function () {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
function showGuest() {
|
||||
$guestLink.removeClass("hidden");
|
||||
$userBtn.addClass("hidden").removeClass("flex");
|
||||
closeDropdown();
|
||||
if (book.genres && book.genres.length > 0) {
|
||||
$("#genres-section").removeClass("hidden");
|
||||
const $genres = $("#genres-container");
|
||||
book.genres.forEach((g) => {
|
||||
$genres.append(`
|
||||
<a href="/books?genre_id=${g.id}" class="inline-flex items-center bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-1 rounded-full text-sm transition-colors">
|
||||
${Utils.escapeHtml(g.name)}
|
||||
</a>
|
||||
`);
|
||||
});
|
||||
}
|
||||
|
||||
function showUser(user) {
|
||||
$guestLink.addClass("hidden");
|
||||
$userBtn.removeClass("hidden").addClass("flex");
|
||||
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
$userAvatar.text(firstLetter);
|
||||
$dropdownName.text(displayName);
|
||||
$dropdownUsername.text("@" + user.username);
|
||||
$dropdownEmail.text(user.email);
|
||||
if (book.authors && book.authors.length > 0) {
|
||||
$("#authors-section").removeClass("hidden");
|
||||
const $authors = $("#authors-container");
|
||||
book.authors.forEach((a) => {
|
||||
$authors.append(`
|
||||
<a href="/author/${a.id}" class="flex items-center bg-gray-50 hover:bg-gray-100 rounded-lg p-2 border transition-colors">
|
||||
<div class="w-8 h-8 bg-gray-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">
|
||||
${a.name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<span class="text-gray-900 font-medium text-sm">${Utils.escapeHtml(a.name)}</span>
|
||||
</a>
|
||||
`);
|
||||
});
|
||||
}
|
||||
|
||||
function updateUserAvatar(email) {
|
||||
if (!email) return;
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const emailHash = sha256(cleanEmail);
|
||||
|
||||
const avatarUrl = `https://www.gravatar.com/avatar/${emailHash}?d=identicon&s=200`;
|
||||
const avatarImg = document.getElementById("user-avatar");
|
||||
if (avatarImg) {
|
||||
avatarImg.src = avatarUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
if (!token) {
|
||||
showGuest();
|
||||
} else {
|
||||
fetch("/api/auth/me", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) return response.json();
|
||||
throw new Error("Unauthorized");
|
||||
})
|
||||
.then((user) => {
|
||||
showUser(user);
|
||||
updateUserAvatar(user.email);
|
||||
|
||||
document.getElementById("user-btn").classList.remove("hidden");
|
||||
document.getElementById("guest-link").classList.add("hidden");
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
showGuest();
|
||||
});
|
||||
}
|
||||
});
|
||||
$("#book-loader").addClass("hidden");
|
||||
$("#book-content").removeClass("hidden");
|
||||
}
|
||||
});
|
||||
|
||||
+237
-424
@@ -1,4 +1,42 @@
|
||||
$(document).ready(() => {
|
||||
const STATUS_CONFIG = {
|
||||
active: {
|
||||
label: "Доступна",
|
||||
bgClass: "bg-green-100",
|
||||
textClass: "text-green-800",
|
||||
},
|
||||
borrowed: {
|
||||
label: "Выдана",
|
||||
bgClass: "bg-yellow-100",
|
||||
textClass: "text-yellow-800",
|
||||
},
|
||||
reserved: {
|
||||
label: "Забронирована",
|
||||
bgClass: "bg-blue-100",
|
||||
textClass: "text-blue-800",
|
||||
},
|
||||
restoration: {
|
||||
label: "На реставрации",
|
||||
bgClass: "bg-orange-100",
|
||||
textClass: "text-orange-800",
|
||||
},
|
||||
written_off: {
|
||||
label: "Списана",
|
||||
bgClass: "bg-red-100",
|
||||
textClass: "text-red-800",
|
||||
},
|
||||
};
|
||||
|
||||
function getStatusConfig(status) {
|
||||
return (
|
||||
STATUS_CONFIG[status] || {
|
||||
label: status || "Неизвестно",
|
||||
bgClass: "bg-gray-100",
|
||||
textClass: "text-gray-800",
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let selectedAuthors = new Map();
|
||||
let selectedGenres = new Map();
|
||||
let currentPage = 1;
|
||||
@@ -10,237 +48,183 @@ $(document).ready(() => {
|
||||
const authorIdsFromUrl = urlParams.getAll("author_id");
|
||||
const searchFromUrl = urlParams.get("q");
|
||||
|
||||
Promise.all([
|
||||
fetch("/api/authors").then((response) => response.json()),
|
||||
fetch("/api/genres").then((response) => response.json()),
|
||||
])
|
||||
if (searchFromUrl) $("#book-search-input").val(searchFromUrl);
|
||||
|
||||
Promise.all([Api.get("/api/authors"), Api.get("/api/genres")])
|
||||
.then(([authorsData, genresData]) => {
|
||||
const $dropdown = $("#author-dropdown");
|
||||
authorsData.authors.forEach((author) => {
|
||||
$("<div>")
|
||||
.addClass("p-2 hover:bg-gray-100 cursor-pointer author-item")
|
||||
.attr("data-id", author.id)
|
||||
.attr("data-name", author.name)
|
||||
.text(author.name)
|
||||
.appendTo($dropdown);
|
||||
|
||||
if (authorIdsFromUrl.includes(String(author.id))) {
|
||||
selectedAuthors.set(author.id, author.name);
|
||||
}
|
||||
});
|
||||
|
||||
const $list = $("#genres-list");
|
||||
genresData.genres.forEach((genre) => {
|
||||
const isChecked = genreIdsFromUrl.includes(String(genre.id));
|
||||
|
||||
if (isChecked) {
|
||||
selectedGenres.set(genre.id, genre.name);
|
||||
}
|
||||
|
||||
$("<li>")
|
||||
.addClass("mb-1")
|
||||
.html(
|
||||
`<label class="custom-checkbox flex items-center">
|
||||
<input type="checkbox" data-id="${genre.id}" data-name="${genre.name}" ${isChecked ? 'checked' : ''} />
|
||||
<span class="checkmark"></span>
|
||||
${genre.name}
|
||||
</label>`,
|
||||
)
|
||||
.appendTo($list);
|
||||
});
|
||||
|
||||
initializeAuthorDropdown();
|
||||
initializeFilters();
|
||||
|
||||
initAuthors(authorsData.authors);
|
||||
initGenres(genresData.genres);
|
||||
initializeAuthorDropdownListeners();
|
||||
renderChips();
|
||||
loadBooks();
|
||||
})
|
||||
.catch((error) => console.error("Error loading data:", error));
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
Utils.showToast("Ошибка загрузки данных", "error");
|
||||
});
|
||||
|
||||
function initAuthors(authors) {
|
||||
const $dropdown = $("#author-dropdown");
|
||||
authors.forEach((author) => {
|
||||
$("<div>")
|
||||
.addClass(
|
||||
"p-2 hover:bg-gray-100 cursor-pointer author-item transition-colors",
|
||||
)
|
||||
.attr("data-id", author.id)
|
||||
.attr("data-name", author.name)
|
||||
.text(author.name)
|
||||
.appendTo($dropdown);
|
||||
|
||||
if (authorIdsFromUrl.includes(String(author.id))) {
|
||||
selectedAuthors.set(author.id, author.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initGenres(genres) {
|
||||
const $list = $("#genres-list");
|
||||
genres.forEach((genre) => {
|
||||
const isChecked = genreIdsFromUrl.includes(String(genre.id));
|
||||
if (isChecked) selectedGenres.set(genre.id, genre.name);
|
||||
|
||||
$list.append(`
|
||||
<li class="mb-1">
|
||||
<label class="custom-checkbox flex items-center">
|
||||
<input type="checkbox" data-id="${genre.id}" data-name="${genre.name}" ${isChecked ? "checked" : ""} />
|
||||
<span class="checkmark"></span> ${Utils.escapeHtml(genre.name)}
|
||||
</label>
|
||||
</li>
|
||||
`);
|
||||
});
|
||||
|
||||
$list.on("change", "input", function () {
|
||||
const id = parseInt($(this).data("id"));
|
||||
const name = $(this).data("name");
|
||||
this.checked ? selectedGenres.set(id, name) : selectedGenres.delete(id);
|
||||
});
|
||||
}
|
||||
|
||||
function loadBooks() {
|
||||
const searchQuery = $("#book-search-input").val().trim();
|
||||
|
||||
const params = new URLSearchParams();
|
||||
if (searchQuery.length >= 3) {
|
||||
params.append("q", searchQuery);
|
||||
}
|
||||
|
||||
selectedAuthors.forEach((name, id) => {
|
||||
params.append("author_ids", id);
|
||||
});
|
||||
params.append("q", searchQuery);
|
||||
selectedAuthors.forEach((_, id) => params.append("author_ids", id));
|
||||
selectedGenres.forEach((_, id) => params.append("genre_ids", id));
|
||||
|
||||
selectedGenres.forEach((name, id) => {
|
||||
params.append("genre_ids", id);
|
||||
});
|
||||
const browserParams = new URLSearchParams();
|
||||
browserParams.append("q", searchQuery);
|
||||
selectedAuthors.forEach((_, id) => browserParams.append("author_id", id));
|
||||
selectedGenres.forEach((_, id) => browserParams.append("genre_id", id));
|
||||
|
||||
function updateBrowserUrl() {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
const searchQuery = $("#book-search-input").val().trim();
|
||||
if (searchQuery.length >= 3) {
|
||||
params.append("q", searchQuery);
|
||||
}
|
||||
|
||||
selectedAuthors.forEach((name, id) => {
|
||||
params.append("author_id", id);
|
||||
});
|
||||
|
||||
selectedGenres.forEach((name, id) => {
|
||||
params.append("genre_id", id);
|
||||
});
|
||||
|
||||
const newUrl = params.toString()
|
||||
? `${window.location.pathname}?${params.toString()}`
|
||||
: window.location.pathname;
|
||||
|
||||
window.history.replaceState({}, "", newUrl);
|
||||
}
|
||||
const newUrl =
|
||||
window.location.pathname +
|
||||
(browserParams.toString() ? `?${browserParams.toString()}` : "");
|
||||
window.history.replaceState({}, "", newUrl);
|
||||
|
||||
params.append("page", currentPage);
|
||||
params.append("size", pageSize);
|
||||
|
||||
const url = `/api/books/filter?${params.toString()}`;
|
||||
|
||||
showLoadingState();
|
||||
|
||||
updateBrowserUrl();
|
||||
|
||||
fetch(url)
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
Api.get(`/api/books/filter?${params.toString()}`)
|
||||
.then((data) => {
|
||||
totalBooks = data.total;
|
||||
renderBooks(data.books);
|
||||
renderPagination();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error loading books:", error);
|
||||
showErrorState();
|
||||
console.error(error);
|
||||
Utils.showToast("Не удалось загрузить книги", "error");
|
||||
$("#books-container").html(
|
||||
document.getElementById("empty-state-template").innerHTML,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function renderBooks(books) {
|
||||
const $container = $("#books-container");
|
||||
const tpl = document.getElementById("book-card-template");
|
||||
const emptyTpl = document.getElementById("empty-state-template");
|
||||
const badgeTpl = document.getElementById("genre-badge-template");
|
||||
|
||||
$container.empty();
|
||||
|
||||
if (books.length === 0) {
|
||||
$container.html(`
|
||||
<div class="bg-white p-8 rounded-lg shadow-md text-center">
|
||||
<svg class="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/>
|
||||
</svg>
|
||||
<h3 class="text-lg font-medium text-gray-900 mb-2">Книги не найдены</h3>
|
||||
<p class="text-gray-500">Попробуйте изменить параметры поиска или фильтры</p>
|
||||
</div>
|
||||
`);
|
||||
$container.append(emptyTpl.content.cloneNode(true));
|
||||
return;
|
||||
}
|
||||
|
||||
books.forEach((book) => {
|
||||
const authorsText =
|
||||
const clone = tpl.content.cloneNode(true);
|
||||
const card = clone.querySelector(".book-card");
|
||||
|
||||
card.dataset.id = book.id;
|
||||
clone.querySelector(".book-title").textContent = book.title;
|
||||
clone.querySelector(".book-authors").textContent =
|
||||
book.authors.map((a) => a.name).join(", ") || "Автор неизвестен";
|
||||
const genresText =
|
||||
book.genres.map((g) => g.name).join(", ") || "Без жанра";
|
||||
clone.querySelector(".book-desc").textContent = book.description || "";
|
||||
|
||||
const $bookCard = $(`
|
||||
<div class="bg-white p-4 rounded-lg shadow-md mb-4 hover:shadow-lg transition-shadow duration-200 cursor-pointer book-card" data-id="${book.id}">
|
||||
<div class="flex justify-between items-start">
|
||||
<div class="flex-1">
|
||||
<h3 class="text-lg font-bold mb-1 text-gray-900 hover:text-blue-600 transition-colors">
|
||||
${escapeHtml(book.title)}
|
||||
</h3>
|
||||
<p class="text-sm text-gray-600 mb-2">
|
||||
<span class="font-medium">Авторы:</span> ${escapeHtml(authorsText)}
|
||||
</p>
|
||||
<p class="text-gray-700 text-sm mb-2">
|
||||
${escapeHtml(book.description || "Описание отсутствует")}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
${book.genres
|
||||
.map(
|
||||
(g) => `
|
||||
<span class="inline-block bg-gray-100 text-gray-600 text-xs px-2 py-1 rounded-full">
|
||||
${escapeHtml(g.name)}
|
||||
</span>
|
||||
`,
|
||||
)
|
||||
.join("")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
const statusConfig = getStatusConfig(book.status);
|
||||
const statusEl = clone.querySelector(".book-status");
|
||||
statusEl.textContent = statusConfig.label;
|
||||
statusEl.classList.add(statusConfig.bgClass, statusConfig.textClass);
|
||||
|
||||
$container.append($bookCard);
|
||||
});
|
||||
|
||||
$container.on("click", ".book-card", function () {
|
||||
const bookId = $(this).data("id");
|
||||
window.location.href = `/book/${bookId}`;
|
||||
const genresContainer = clone.querySelector(".book-genres");
|
||||
book.genres.forEach((g) => {
|
||||
const badge = badgeTpl.content.cloneNode(true);
|
||||
const span = badge.querySelector("span");
|
||||
span.textContent = g.name;
|
||||
genresContainer.appendChild(badge);
|
||||
});
|
||||
|
||||
$container.append(clone);
|
||||
});
|
||||
}
|
||||
|
||||
function renderPagination() {
|
||||
$("#pagination-container").remove();
|
||||
|
||||
$("#pagination-container").empty();
|
||||
const totalPages = Math.ceil(totalBooks / pageSize);
|
||||
|
||||
if (totalPages <= 1) return;
|
||||
|
||||
const $pagination = $(`
|
||||
<div id="pagination-container" class="flex justify-center items-center gap-2 mt-6 mb-4">
|
||||
<button id="prev-page" class="px-3 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" ${currentPage === 1 ? "disabled" : ""}>
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
|
||||
</svg>
|
||||
</button>
|
||||
<div id="page-numbers" class="flex gap-1"></div>
|
||||
<button id="next-page" class="px-3 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" ${currentPage === totalPages ? "disabled" : ""}>
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
`);
|
||||
<div class="flex justify-center items-center gap-2 mt-6 mb-4">
|
||||
<button id="prev-page" class="px-3 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" ${currentPage === 1 ? "disabled" : ""}>←</button>
|
||||
<div id="page-numbers" class="flex gap-1"></div>
|
||||
<button id="next-page" class="px-3 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" ${currentPage === totalPages ? "disabled" : ""}>→</button>
|
||||
</div>
|
||||
`);
|
||||
|
||||
const $pageNumbers = $pagination.find("#page-numbers");
|
||||
|
||||
const pages = generatePageNumbers(currentPage, totalPages);
|
||||
|
||||
pages.forEach((page) => {
|
||||
if (page === "...") {
|
||||
$pageNumbers.append(`<span class="px-3 py-2">...</span>`);
|
||||
$pageNumbers.append(`<span class="px-3 py-2 text-gray-500">...</span>`);
|
||||
} else {
|
||||
const isActive = page === currentPage;
|
||||
$pageNumbers.append(`
|
||||
<button class="page-btn px-3 py-2 rounded-lg ${isActive ? "bg-gray-500 text-white" : "bg-white border border-gray-300 hover:bg-gray-50"}" data-page="${page}">
|
||||
${page}
|
||||
</button>
|
||||
`);
|
||||
<button class="page-btn px-3 py-2 rounded-lg transition-colors ${isActive ? "bg-gray-600 text-white" : "bg-white border border-gray-300 hover:bg-gray-50"}" data-page="${page}">${page}</button>
|
||||
`);
|
||||
}
|
||||
});
|
||||
|
||||
$("#books-container").after($pagination);
|
||||
$("#pagination-container").append($pagination);
|
||||
|
||||
$("#prev-page").on("click", function () {
|
||||
$("#prev-page").on("click", () => {
|
||||
if (currentPage > 1) {
|
||||
currentPage--;
|
||||
loadBooks();
|
||||
scrollToTop();
|
||||
}
|
||||
});
|
||||
|
||||
$("#next-page").on("click", function () {
|
||||
$("#next-page").on("click", () => {
|
||||
if (currentPage < totalPages) {
|
||||
currentPage++;
|
||||
loadBooks();
|
||||
scrollToTop();
|
||||
}
|
||||
});
|
||||
|
||||
$(".page-btn").on("click", function () {
|
||||
const page = parseInt($(this).data("page"));
|
||||
if (page !== currentPage) {
|
||||
@@ -254,7 +238,6 @@ $(document).ready(() => {
|
||||
function generatePageNumbers(current, total) {
|
||||
const pages = [];
|
||||
const delta = 2;
|
||||
|
||||
for (let i = 1; i <= total; i++) {
|
||||
if (
|
||||
i === 1 ||
|
||||
@@ -266,7 +249,6 @@ $(document).ready(() => {
|
||||
pages.push("...");
|
||||
}
|
||||
}
|
||||
|
||||
return pages;
|
||||
}
|
||||
|
||||
@@ -275,115 +257,78 @@ $(document).ready(() => {
|
||||
}
|
||||
|
||||
function showLoadingState() {
|
||||
const $container = $("#books-container");
|
||||
$container.html(`
|
||||
<div class="space-y-4">
|
||||
${Array(3)
|
||||
.fill()
|
||||
.map(
|
||||
() => `
|
||||
<div class="bg-white p-4 rounded-lg shadow-md animate-pulse">
|
||||
<div class="h-6 bg-gray-200 rounded w-3/4 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-full mb-2"></div>
|
||||
<div class="flex gap-2">
|
||||
<div class="h-6 bg-gray-200 rounded-full w-16"></div>
|
||||
<div class="h-6 bg-gray-200 rounded-full w-20"></div>
|
||||
$("#books-container").html(`
|
||||
<div class="space-y-4">
|
||||
${Array(3)
|
||||
.fill()
|
||||
.map(
|
||||
() => `
|
||||
<div class="bg-white p-4 rounded-lg shadow-md animate-pulse">
|
||||
<div class="h-6 bg-gray-200 rounded w-3/4 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-full mb-2"></div>
|
||||
</div>
|
||||
`,
|
||||
)
|
||||
.join("")}
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
)
|
||||
.join("")}
|
||||
</div>
|
||||
`);
|
||||
`);
|
||||
}
|
||||
|
||||
function showErrorState() {
|
||||
const $container = $("#books-container");
|
||||
$container.html(`
|
||||
<div class="bg-red-50 p-8 rounded-lg shadow-md text-center">
|
||||
<svg class="mx-auto h-12 w-12 text-red-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
|
||||
</svg>
|
||||
<h3 class="text-lg font-medium text-red-900 mb-2">Ошибка загрузки</h3>
|
||||
<p class="text-red-700 mb-4">Не удалось загрузить список книг</p>
|
||||
<button id="retry-btn" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700">
|
||||
Попробовать снова
|
||||
</button>
|
||||
</div>
|
||||
`);
|
||||
function renderChips() {
|
||||
const $container = $("#selected-authors-container");
|
||||
const $dropdown = $("#author-dropdown");
|
||||
|
||||
$("#retry-btn").on("click", loadBooks);
|
||||
$container.empty();
|
||||
|
||||
selectedAuthors.forEach((name, id) => {
|
||||
$(`<span class="author-chip inline-flex items-center bg-gray-600 text-white text-sm font-medium px-2.5 pt-0.5 pb-1 rounded-full">
|
||||
${Utils.escapeHtml(name)}
|
||||
<button type="button" class="remove-author mt-0.5 ml-2 inline-flex items-center justify-center text-gray-300 hover:text-white hover:bg-gray-400 rounded-full w-4 h-4 transition-colors" data-id="${id}">
|
||||
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
|
||||
</svg>
|
||||
</button>
|
||||
</span>`).appendTo($container);
|
||||
});
|
||||
|
||||
$dropdown.find(".author-item").each(function () {
|
||||
const id = parseInt($(this).data("id"));
|
||||
if (selectedAuthors.has(id)) {
|
||||
$(this)
|
||||
.addClass("bg-gray-200 text-gray-900 font-semibold")
|
||||
.removeClass("hover:bg-gray-100");
|
||||
} else {
|
||||
$(this)
|
||||
.removeClass("bg-gray-200 text-gray-900 font-semibold")
|
||||
.addClass("hover:bg-gray-100");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
const div = document.createElement("div");
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function initializeAuthorDropdown() {
|
||||
function initializeAuthorDropdownListeners() {
|
||||
const $input = $("#author-search-input");
|
||||
const $dropdown = $("#author-dropdown");
|
||||
const $container = $("#selected-authors-container");
|
||||
|
||||
function updateHighlights() {
|
||||
$dropdown.find(".author-item").each(function () {
|
||||
const id = $(this).attr("data-id");
|
||||
const isSelected = selectedAuthors.has(parseInt(id));
|
||||
$(this)
|
||||
.toggleClass("bg-gray-300 text-gray-600", isSelected)
|
||||
.toggleClass("hover:bg-gray-100", !isSelected);
|
||||
});
|
||||
}
|
||||
|
||||
function filterDropdown(query) {
|
||||
const lowerQuery = query.toLowerCase();
|
||||
$dropdown.find(".author-item").each(function () {
|
||||
$(this).toggle($(this).text().toLowerCase().includes(lowerQuery));
|
||||
});
|
||||
}
|
||||
|
||||
function renderChips() {
|
||||
$container.find(".author-chip").remove();
|
||||
selectedAuthors.forEach((name, id) => {
|
||||
$(`<span class="author-chip flex items-center bg-gray-500 text-white text-sm font-medium px-2.5 py-0.5 rounded-full">
|
||||
${escapeHtml(name)}
|
||||
<button type="button" class="remove-author ml-1.5 inline-flex items-center p-0.5 text-gray-200 hover:text-white hover:bg-gray-600 rounded-full" data-id="${id}">
|
||||
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 14 14">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/>
|
||||
</svg>
|
||||
</button>
|
||||
</span>`).insertBefore($input);
|
||||
});
|
||||
updateHighlights();
|
||||
}
|
||||
|
||||
function toggleAuthor(id, name) {
|
||||
id = parseInt(id);
|
||||
if (selectedAuthors.has(id)) {
|
||||
selectedAuthors.delete(id);
|
||||
} else {
|
||||
selectedAuthors.add(id, name);
|
||||
selectedAuthors.set(id, name);
|
||||
}
|
||||
$input.val("");
|
||||
filterDropdown("");
|
||||
renderChips();
|
||||
}
|
||||
|
||||
$input.on("focus", () => $dropdown.removeClass("hidden"));
|
||||
|
||||
$input.on("input", function () {
|
||||
filterDropdown($(this).val().toLowerCase());
|
||||
$input.on("focus", function () {
|
||||
$dropdown.removeClass("hidden");
|
||||
});
|
||||
|
||||
$(document).on("click", (e) => {
|
||||
$input.on("input", function () {
|
||||
const val = $(this).val().toLowerCase();
|
||||
$dropdown.removeClass("hidden");
|
||||
$dropdown.find(".author-item").each(function () {
|
||||
const text = $(this).text().toLowerCase();
|
||||
$(this).toggle(text.includes(val));
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (
|
||||
!$(e.target).closest("#selected-authors-container, #author-dropdown")
|
||||
.length
|
||||
!$(e.target).closest(
|
||||
"#author-search-input, #author-dropdown, #selected-authors-container",
|
||||
).length
|
||||
) {
|
||||
$dropdown.addClass("hidden");
|
||||
}
|
||||
@@ -391,184 +336,52 @@ $(document).ready(() => {
|
||||
|
||||
$dropdown.on("click", ".author-item", function (e) {
|
||||
e.stopPropagation();
|
||||
toggleAuthor($(this).attr("data-id"), $(this).attr("data-name"));
|
||||
$input.focus();
|
||||
const id = parseInt($(this).data("id"));
|
||||
const name = $(this).data("name");
|
||||
|
||||
if (selectedAuthors.has(id)) {
|
||||
selectedAuthors.delete(id);
|
||||
} else {
|
||||
selectedAuthors.set(id, name);
|
||||
}
|
||||
|
||||
$input.val("");
|
||||
$dropdown.find(".author-item").show();
|
||||
renderChips();
|
||||
$input[0].focus();
|
||||
});
|
||||
|
||||
$container.on("click", ".remove-author", function (e) {
|
||||
e.stopPropagation();
|
||||
selectedAuthors.delete(parseInt($(this).attr("data-id")));
|
||||
const id = parseInt($(this).data("id"));
|
||||
selectedAuthors.delete(id);
|
||||
renderChips();
|
||||
$input.focus();
|
||||
});
|
||||
|
||||
$container.on("click", (e) => {
|
||||
if (!$(e.target).closest(".author-chip").length) {
|
||||
$input.focus();
|
||||
}
|
||||
});
|
||||
|
||||
window.renderAuthorChips = renderChips;
|
||||
window.updateAuthorHighlights = updateHighlights;
|
||||
}
|
||||
|
||||
function initializeFilters() {
|
||||
const $bookSearch = $("#book-search-input");
|
||||
const $applyBtn = $("#apply-filters-btn");
|
||||
const $resetBtn = $("#reset-filters-btn");
|
||||
$("#books-container").on("click", ".book-card", function () {
|
||||
window.location.href = `/book/${$(this).data("id")}`;
|
||||
});
|
||||
|
||||
$("#genres-list").on("change", "input[type='checkbox']", function () {
|
||||
const id = parseInt($(this).attr("data-id"));
|
||||
const name = $(this).attr("data-name");
|
||||
if ($(this).is(":checked")) {
|
||||
selectedGenres.set(id, name);
|
||||
} else {
|
||||
selectedGenres.delete(id);
|
||||
}
|
||||
});
|
||||
$("#apply-filters-btn").on("click", function () {
|
||||
currentPage = 1;
|
||||
loadBooks();
|
||||
});
|
||||
|
||||
$applyBtn.on("click", function () {
|
||||
$("#reset-filters-btn").on("click", function () {
|
||||
$("#book-search-input").val("");
|
||||
selectedAuthors.clear();
|
||||
selectedGenres.clear();
|
||||
$("#genres-list input").prop("checked", false);
|
||||
renderChips();
|
||||
currentPage = 1;
|
||||
loadBooks();
|
||||
});
|
||||
|
||||
$("#book-search-input").on("keypress", function (e) {
|
||||
if (e.which === 13) {
|
||||
currentPage = 1;
|
||||
loadBooks();
|
||||
});
|
||||
|
||||
$resetBtn.on("click", function () {
|
||||
$bookSearch.val("");
|
||||
|
||||
selectedAuthors.clear();
|
||||
$("#selected-authors-container .author-chip").remove();
|
||||
if (window.updateAuthorHighlights) window.updateAuthorHighlights();
|
||||
|
||||
selectedGenres.clear();
|
||||
$("#genres-list input[type='checkbox']").prop("checked", false);
|
||||
|
||||
currentPage = 1;
|
||||
loadBooks();
|
||||
});
|
||||
|
||||
let searchTimeout;
|
||||
$bookSearch.on("input", function () {
|
||||
clearTimeout(searchTimeout);
|
||||
const query = $(this).val().trim();
|
||||
|
||||
if (query.length >= 3 || query.length === 0) {
|
||||
searchTimeout = setTimeout(() => {
|
||||
currentPage = 1;
|
||||
loadBooks();
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
$bookSearch.on("keypress", function (e) {
|
||||
if (e.which === 13) {
|
||||
clearTimeout(searchTimeout);
|
||||
currentPage = 1;
|
||||
loadBooks();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const $guestLink = $("#guest-link");
|
||||
const $userBtn = $("#user-btn");
|
||||
const $userDropdown = $("#user-dropdown");
|
||||
const $userArrow = $("#user-arrow");
|
||||
const $userAvatar = $("#user-avatar");
|
||||
const $dropdownName = $("#dropdown-name");
|
||||
const $dropdownUsername = $("#dropdown-username");
|
||||
const $dropdownEmail = $("#dropdown-email");
|
||||
const $logoutBtn = $("#logout-btn");
|
||||
|
||||
let isDropdownOpen = false;
|
||||
|
||||
function openDropdown() {
|
||||
isDropdownOpen = true;
|
||||
$userDropdown.removeClass("hidden");
|
||||
$userArrow.addClass("rotate-180");
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
isDropdownOpen = false;
|
||||
$userDropdown.addClass("hidden");
|
||||
$userArrow.removeClass("rotate-180");
|
||||
}
|
||||
|
||||
$userBtn.on("click", function (e) {
|
||||
e.stopPropagation();
|
||||
isDropdownOpen ? closeDropdown() : openDropdown();
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (isDropdownOpen && !$(e.target).closest("#user-menu-container").length) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on("keydown", function (e) {
|
||||
if (e.key === "Escape" && isDropdownOpen) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$logoutBtn.on("click", function () {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
function showGuest() {
|
||||
$guestLink.removeClass("hidden");
|
||||
$userBtn.addClass("hidden").removeClass("flex");
|
||||
closeDropdown();
|
||||
}
|
||||
|
||||
function showUser(user) {
|
||||
$guestLink.addClass("hidden");
|
||||
$userBtn.removeClass("hidden").addClass("flex");
|
||||
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
$userAvatar.text(firstLetter);
|
||||
$dropdownName.text(displayName);
|
||||
$dropdownUsername.text("@" + user.username);
|
||||
$dropdownEmail.text(user.email);
|
||||
}
|
||||
|
||||
function updateUserAvatar(email) {
|
||||
if (!email) return;
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const emailHash = sha256(cleanEmail);
|
||||
|
||||
const avatarUrl = `https://www.gravatar.com/avatar/${emailHash}?d=identicon&s=200`;
|
||||
const avatarImg = document.getElementById("user-avatar");
|
||||
if (avatarImg) {
|
||||
avatarImg.src = avatarUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
if (!token) {
|
||||
showGuest();
|
||||
} else {
|
||||
fetch("/api/auth/me", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) return response.json();
|
||||
throw new Error("Unauthorized");
|
||||
})
|
||||
.then((user) => {
|
||||
showUser(user);
|
||||
updateUserAvatar(user.email);
|
||||
|
||||
document.getElementById("user-btn").classList.remove("hidden");
|
||||
document.getElementById("guest-link").classList.add("hidden");
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
showGuest();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -11,9 +11,9 @@ const bookX = (svgWidth - bookWidth) / 2;
|
||||
const bookY = (svgHeight - bookHeight) / 2;
|
||||
const desiredLineSpacing = 8;
|
||||
const baseLineWidth = 2;
|
||||
const maxLineWidth = 10;
|
||||
const maxLineWidth = 8;
|
||||
const maxLineHeight = bookHeight - 24;
|
||||
const innerPaddingX = 10;
|
||||
const innerPaddingX = 15;
|
||||
const appearStagger = 8;
|
||||
|
||||
let lineSpacing;
|
||||
@@ -28,7 +28,7 @@ if (lineCount > 1) {
|
||||
const linesSpan = lineSpacing * (lineCount - 1);
|
||||
|
||||
const rightBase = bookX + bookWidth - innerPaddingX - maxLineWidth;
|
||||
const lineStartX = rightBase - linesSpan;
|
||||
const lineStartX = rightBase - linesSpan + maxLineWidth;
|
||||
|
||||
const leftLimit = bookX + innerPaddingX;
|
||||
|
||||
@@ -250,18 +250,16 @@ function observeStatCards() {
|
||||
entries.forEach((entry, index) => {
|
||||
if (entry.isIntersecting) {
|
||||
setTimeout(() => {
|
||||
$(entry.target)
|
||||
.addClass("animate-fade-in")
|
||||
.css({
|
||||
opacity: "1",
|
||||
transform: "translateY(0)",
|
||||
});
|
||||
$(entry.target).addClass("animate-fade-in").css({
|
||||
opacity: "1",
|
||||
transform: "translateY(0)",
|
||||
});
|
||||
}, index * 100);
|
||||
observer.unobserve(entry.target);
|
||||
}
|
||||
});
|
||||
},
|
||||
{ threshold: 0.1 }
|
||||
{ threshold: 0.1 },
|
||||
);
|
||||
|
||||
$cards.each((index, card) => {
|
||||
@@ -277,108 +275,4 @@ function observeStatCards() {
|
||||
$(document).ready(() => {
|
||||
loadStats();
|
||||
observeStatCards();
|
||||
|
||||
const $guestLink = $("#guest-link");
|
||||
const $userBtn = $("#user-btn");
|
||||
const $userDropdown = $("#user-dropdown");
|
||||
const $userArrow = $("#user-arrow");
|
||||
const $userAvatar = $("#user-avatar");
|
||||
const $dropdownName = $("#dropdown-name");
|
||||
const $dropdownUsername = $("#dropdown-username");
|
||||
const $dropdownEmail = $("#dropdown-email");
|
||||
const $logoutBtn = $("#logout-btn");
|
||||
|
||||
let isDropdownOpen = false;
|
||||
|
||||
function openDropdown() {
|
||||
isDropdownOpen = true;
|
||||
$userDropdown.removeClass("hidden");
|
||||
$userArrow.addClass("rotate-180");
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
isDropdownOpen = false;
|
||||
$userDropdown.addClass("hidden");
|
||||
$userArrow.removeClass("rotate-180");
|
||||
}
|
||||
|
||||
$userBtn.on("click", function (e) {
|
||||
e.stopPropagation();
|
||||
isDropdownOpen ? closeDropdown() : openDropdown();
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (isDropdownOpen && !$(e.target).closest("#user-menu-container").length) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on("keydown", function (e) {
|
||||
if (e.key === "Escape" && isDropdownOpen) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$logoutBtn.on("click", function () {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
function showGuest() {
|
||||
$guestLink.removeClass("hidden");
|
||||
$userBtn.addClass("hidden").removeClass("flex");
|
||||
closeDropdown();
|
||||
}
|
||||
|
||||
function showUser(user) {
|
||||
$guestLink.addClass("hidden");
|
||||
$userBtn.removeClass("hidden").addClass("flex");
|
||||
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
$userAvatar.text(firstLetter);
|
||||
$dropdownName.text(displayName);
|
||||
$dropdownUsername.text("@" + user.username);
|
||||
$dropdownEmail.text(user.email);
|
||||
}
|
||||
|
||||
function updateUserAvatar(email) {
|
||||
if (!email) return;
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const emailHash = sha256(cleanEmail);
|
||||
|
||||
const avatarUrl = `https://www.gravatar.com/avatar/${emailHash}?d=identicon&s=200`;
|
||||
const avatarImg = document.getElementById("user-avatar");
|
||||
if (avatarImg) {
|
||||
avatarImg.src = avatarUrl;
|
||||
}
|
||||
}
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
if (!token) {
|
||||
showGuest();
|
||||
} else {
|
||||
fetch("/api/auth/me", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) return response.json();
|
||||
throw new Error("Unauthorized");
|
||||
})
|
||||
.then((user) => {
|
||||
showUser(user);
|
||||
updateUserAvatar(user.email);
|
||||
|
||||
document.getElementById("user-btn").classList.remove("hidden");
|
||||
document.getElementById("guest-link").classList.add("hidden");
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
showGuest();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
+123
-501
@@ -1,509 +1,131 @@
|
||||
$(document).ready(() => {
|
||||
let currentUser = null;
|
||||
let allRoles = [];
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
if (!token) {
|
||||
window.location.href = "/login";
|
||||
return;
|
||||
}
|
||||
|
||||
loadProfile();
|
||||
|
||||
function loadProfile() {
|
||||
showLoadingState();
|
||||
|
||||
Promise.all([
|
||||
fetch("/api/auth/me", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
}).then((response) => {
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
}),
|
||||
fetch("/api/auth/roles", {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
}).then((response) => {
|
||||
if (response.ok) return response.json();
|
||||
return { roles: [] };
|
||||
}),
|
||||
])
|
||||
.then(([user, rolesData]) => {
|
||||
currentUser = user;
|
||||
allRoles = rolesData.roles || [];
|
||||
renderProfile(user);
|
||||
renderAccountInfo(user);
|
||||
renderRoles(user.roles, allRoles);
|
||||
renderActions();
|
||||
document.title = `LiB - ${user.full_name || user.username}`;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error loading profile:", error);
|
||||
if (error.message === "Unauthorized") {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.href = "/login";
|
||||
} else {
|
||||
showErrorState(error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function renderProfile(user) {
|
||||
const $card = $("#profile-card");
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
const emailHash = sha256(user.email.trim().toLowerCase());
|
||||
const avatarUrl = `https://www.gravatar.com/avatar/${emailHash}?d=identicon&s=200`;
|
||||
|
||||
$card.html(`
|
||||
<div class="flex flex-col sm:flex-row items-center sm:items-start">
|
||||
<!-- Аватар -->
|
||||
<div class="relative mb-4 sm:mb-0 sm:mr-6">
|
||||
<img src="${avatarUrl}" alt="Аватар"
|
||||
class="w-24 h-24 rounded-full object-cover border-4 border-gray-200"
|
||||
onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
|
||||
<div class="w-24 h-24 bg-gray-500 text-white rounded-full items-center justify-center text-4xl font-bold hidden">
|
||||
${firstLetter}
|
||||
</div>
|
||||
<!-- Статус верификации -->
|
||||
${user.is_verified ? `
|
||||
<div class="absolute -bottom-1 -right-1 bg-green-500 rounded-full p-1" title="Подтверждённый аккаунт">
|
||||
<svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
|
||||
<!-- Информация -->
|
||||
<div class="flex-1 text-center sm:text-left">
|
||||
<h1 class="text-2xl font-bold text-gray-900 mb-1">${escapeHtml(displayName)}</h1>
|
||||
<p class="text-gray-500 mb-3">@${escapeHtml(user.username)}</p>
|
||||
|
||||
<!-- Статусы -->
|
||||
<div class="flex flex-wrap justify-center sm:justify-start gap-2">
|
||||
${user.is_active ? `
|
||||
<span class="inline-flex items-center bg-green-100 text-green-800 text-sm px-3 py-1 rounded-full">
|
||||
<span class="w-2 h-2 bg-green-500 rounded-full mr-2"></span>
|
||||
Активен
|
||||
</span>
|
||||
` : `
|
||||
<span class="inline-flex items-center bg-red-100 text-red-800 text-sm px-3 py-1 rounded-full">
|
||||
<span class="w-2 h-2 bg-red-500 rounded-full mr-2"></span>
|
||||
Заблокирован
|
||||
</span>
|
||||
`}
|
||||
${user.is_verified ? `
|
||||
<span class="inline-flex items-center bg-blue-100 text-blue-800 text-sm px-3 py-1 rounded-full">
|
||||
<svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
Подтверждён
|
||||
</span>
|
||||
` : `
|
||||
<span class="inline-flex items-center bg-yellow-100 text-yellow-800 text-sm px-3 py-1 rounded-full">
|
||||
<svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
Не подтверждён
|
||||
</span>
|
||||
`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
function renderAccountInfo(user) {
|
||||
const $container = $("#account-container");
|
||||
|
||||
$container.html(`
|
||||
<div class="space-y-4">
|
||||
<!-- ID пользователя -->
|
||||
<div class="flex items-center justify-between py-3 border-b border-gray-100">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-gray-400 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"/>
|
||||
</svg>
|
||||
<div>
|
||||
<p class="text-sm text-gray-500">ID пользователя</p>
|
||||
<p class="text-gray-900">${user.id}</p>
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/auth";
|
||||
return;
|
||||
}
|
||||
|
||||
loadProfile();
|
||||
|
||||
function loadProfile() {
|
||||
Promise.all([
|
||||
Api.get("/api/auth/me"),
|
||||
Api.get("/api/auth/roles").catch(() => ({ roles: [] })),
|
||||
])
|
||||
.then(async ([user, rolesData]) => {
|
||||
document.title = `LiB - ${user.full_name || user.username}`;
|
||||
await renderProfileHeader(user);
|
||||
renderInfo(user);
|
||||
renderRoles(user.roles || [], rolesData.roles || []);
|
||||
|
||||
$("#account-section, #roles-section").removeClass("hidden");
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
Utils.showToast("Ошибка загрузки профиля", "error");
|
||||
});
|
||||
}
|
||||
|
||||
async function renderProfileHeader(user) {
|
||||
const avatarUrl = await Utils.getGravatarUrl(user.email);
|
||||
const displayName = Utils.escapeHtml(user.full_name || user.username);
|
||||
|
||||
$("#profile-card").html(`
|
||||
<div class="flex flex-col sm:flex-row items-center sm:items-start">
|
||||
<div class="relative mb-4 sm:mb-0 sm:mr-6">
|
||||
<img src="${avatarUrl}" class="w-24 h-24 rounded-full object-cover border-4 border-gray-200">
|
||||
${user.is_verified ? '<div class="absolute -bottom-1 -right-1 bg-green-500 rounded-full p-1 border-2 border-white"><svg class="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/></svg></div>' : ""}
|
||||
</div>
|
||||
<div class="flex-1 text-center sm:text-left">
|
||||
<h1 class="text-2xl font-bold text-gray-900 mb-1">${displayName}</h1>
|
||||
<p class="text-gray-500 mb-3">@${Utils.escapeHtml(user.username)}</p>
|
||||
<span class="inline-flex items-center px-3 py-1 rounded-full text-sm ${user.is_active ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"}">
|
||||
${user.is_active ? "Активен" : "Заблокирован"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Имя пользователя -->
|
||||
<div class="flex items-center justify-between py-3 border-b border-gray-100">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-gray-400 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
|
||||
</svg>
|
||||
<div>
|
||||
<p class="text-sm text-gray-500">Имя пользователя</p>
|
||||
<p class="text-gray-900">@${escapeHtml(user.username)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Полное имя -->
|
||||
<div class="flex items-center justify-between py-3 border-b border-gray-100">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-gray-400 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V8a2 2 0 00-2-2h-5m-4 0V5a2 2 0 114 0v1m-4 0a2 2 0 104 0m-5 8a2 2 0 100-4 2 2 0 000 4zm0 0c1.306 0 2.417.835 2.83 2M9 14a3.001 3.001 0 00-2.83 2M15 11h3m-3 4h2"/>
|
||||
</svg>
|
||||
<div>
|
||||
<p class="text-sm text-gray-500">Полное имя</p>
|
||||
<p class="text-gray-900">${escapeHtml(user.full_name || "Не указано")}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Email -->
|
||||
<div class="flex items-center justify-between py-3">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-gray-400 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
|
||||
</svg>
|
||||
<div>
|
||||
<p class="text-sm text-gray-500">Email</p>
|
||||
<p class="text-gray-900">${escapeHtml(user.email)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
function renderRoles(userRoles, allRoles) {
|
||||
const $container = $("#roles-container");
|
||||
|
||||
if (!userRoles || userRoles.length === 0) {
|
||||
$container.html(`
|
||||
<p class="text-gray-500">У вас нет назначенных ролей</p>
|
||||
`);
|
||||
return;
|
||||
}
|
||||
|
||||
const roleDescriptions = {};
|
||||
allRoles.forEach((role) => {
|
||||
roleDescriptions[role.name] = role.description;
|
||||
});
|
||||
|
||||
const roleIcons = {
|
||||
admin: `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
|
||||
</svg>`,
|
||||
librarian: `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/>
|
||||
</svg>`,
|
||||
member: `<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
|
||||
</svg>`,
|
||||
};
|
||||
|
||||
const roleColors = {
|
||||
admin: "bg-red-100 text-red-800 border-red-200",
|
||||
librarian: "bg-blue-100 text-blue-800 border-blue-200",
|
||||
member: "bg-green-100 text-green-800 border-green-200",
|
||||
};
|
||||
|
||||
let rolesHtml = '<div class="space-y-3">';
|
||||
|
||||
userRoles.forEach((roleName) => {
|
||||
const description = roleDescriptions[roleName] || "Описание недоступно";
|
||||
const icon = roleIcons[roleName] || roleIcons.member;
|
||||
const colorClass = roleColors[roleName] || roleColors.member;
|
||||
|
||||
rolesHtml += `
|
||||
<div class="flex items-center p-4 rounded-lg border ${colorClass}">
|
||||
<div class="flex-shrink-0 mr-4">
|
||||
${icon}
|
||||
}
|
||||
|
||||
function renderInfo(user) {
|
||||
const fields = [
|
||||
{ label: "ID пользователя", value: user.id },
|
||||
{ label: "Email", value: user.email },
|
||||
{ label: "Полное имя", value: user.full_name || "Не указано" },
|
||||
];
|
||||
|
||||
const html = fields
|
||||
.map(
|
||||
(f) => `
|
||||
<div class="flex justify-between py-2 border-b last:border-0">
|
||||
<span class="text-gray-500">${f.label}</span>
|
||||
<span class="font-medium text-gray-900">${Utils.escapeHtml(String(f.value))}</span>
|
||||
</div>
|
||||
<div>
|
||||
<h4 class="font-medium capitalize">${escapeHtml(roleName)}</h4>
|
||||
<p class="text-sm opacity-75">${escapeHtml(description)}</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
rolesHtml += '</div>';
|
||||
|
||||
$container.html(rolesHtml);
|
||||
}
|
||||
|
||||
function renderActions() {
|
||||
const $container = $("#actions-container");
|
||||
|
||||
$container.html(`
|
||||
<div class="space-y-3">
|
||||
<!-- Смена пароля -->
|
||||
<button id="change-password-btn" class="w-full flex items-center justify-between p-4 bg-gray-50 hover:bg-gray-100 rounded-lg transition-colors">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-gray-500 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/>
|
||||
</svg>
|
||||
<span class="text-gray-700">Сменить пароль</span>
|
||||
</div>
|
||||
<svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Выход -->
|
||||
<button id="logout-profile-btn" class="w-full flex items-center justify-between p-4 bg-red-50 hover:bg-red-100 rounded-lg transition-colors">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-red-500 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/>
|
||||
</svg>
|
||||
<span class="text-red-700">Выйти из аккаунта</span>
|
||||
</div>
|
||||
<svg class="w-5 h-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$("#change-password-btn").on("click", openPasswordModal);
|
||||
$("#logout-profile-btn").on("click", logout);
|
||||
}
|
||||
|
||||
function openPasswordModal() {
|
||||
$("#password-modal").removeClass("hidden").addClass("flex");
|
||||
$("#current-password").focus();
|
||||
}
|
||||
|
||||
function closePasswordModal() {
|
||||
$("#password-modal").removeClass("flex").addClass("hidden");
|
||||
$("#password-form")[0].reset();
|
||||
$("#password-error").addClass("hidden").text("");
|
||||
}
|
||||
|
||||
$("#close-password-modal, #cancel-password").on("click", closePasswordModal);
|
||||
|
||||
$("#password-modal").on("click", function (e) {
|
||||
if (e.target === this) {
|
||||
closePasswordModal();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on("keydown", function (e) {
|
||||
if (e.key === "Escape" && $("#password-modal").hasClass("flex")) {
|
||||
closePasswordModal();
|
||||
}
|
||||
});
|
||||
|
||||
$("#password-form").on("submit", function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
const currentPassword = $("#current-password").val();
|
||||
const newPassword = $("#new-password").val();
|
||||
const confirmPassword = $("#confirm-password").val();
|
||||
const $error = $("#password-error");
|
||||
|
||||
if (newPassword !== confirmPassword) {
|
||||
$error.text("Пароли не совпадают").removeClass("hidden");
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPassword.length < 6) {
|
||||
$error.text("Пароль должен содержать минимум 6 символов").removeClass("hidden");
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: смена пароля, 2FA
|
||||
// fetch("/api/auth/change-password", {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/json",
|
||||
// Authorization: "Bearer " + token,
|
||||
// },
|
||||
// body: JSON.stringify({
|
||||
// current_password: currentPassword,
|
||||
// new_password: newPassword,
|
||||
// }),
|
||||
// })
|
||||
// .then((response) => {
|
||||
// if (!response.ok) throw new Error("Ошибка смены пароля");
|
||||
// return response.json();
|
||||
// })
|
||||
// .then(() => {
|
||||
// closePasswordModal();
|
||||
// showNotification("Пароль успешно изменён", "success");
|
||||
// })
|
||||
// .catch((error) => {
|
||||
// $error.text(error.message).removeClass("hidden");
|
||||
// });
|
||||
|
||||
$error.text("Функция смены пароля временно недоступна").removeClass("hidden");
|
||||
});
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.href = "/login";
|
||||
}
|
||||
|
||||
function showLoadingState() {
|
||||
const $profileCard = $("#profile-card");
|
||||
const $accountContainer = $("#account-container");
|
||||
const $rolesContainer = $("#roles-container");
|
||||
const $actionsContainer = $("#actions-container");
|
||||
|
||||
$profileCard.html(`
|
||||
<div class="flex flex-col sm:flex-row items-center sm:items-start animate-pulse">
|
||||
<div class="w-24 h-24 bg-gray-200 rounded-full mb-4 sm:mb-0 sm:mr-6"></div>
|
||||
<div class="flex-1 text-center sm:text-left">
|
||||
<div class="h-7 bg-gray-200 rounded w-48 mx-auto sm:mx-0 mb-2"></div>
|
||||
<div class="h-5 bg-gray-200 rounded w-32 mx-auto sm:mx-0 mb-3"></div>
|
||||
<div class="flex justify-center sm:justify-start gap-2">
|
||||
<div class="h-7 bg-gray-200 rounded-full w-20"></div>
|
||||
<div class="h-7 bg-gray-200 rounded-full w-28"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$accountContainer.html(`
|
||||
<div class="space-y-4 animate-pulse">
|
||||
${Array(4)
|
||||
.fill()
|
||||
.map(
|
||||
() => `
|
||||
<div class="flex items-center py-3 border-b border-gray-100">
|
||||
<div class="w-5 h-5 bg-gray-200 rounded mr-3"></div>
|
||||
<div>
|
||||
<div class="h-3 bg-gray-200 rounded w-16 mb-2"></div>
|
||||
<div class="h-4 bg-gray-200 rounded w-40"></div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
)
|
||||
.join("")}
|
||||
</div>
|
||||
`);
|
||||
|
||||
$rolesContainer.html(`
|
||||
<div class="space-y-3 animate-pulse">
|
||||
<div class="h-16 bg-gray-200 rounded-lg"></div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$actionsContainer.html(`
|
||||
<div class="space-y-3 animate-pulse">
|
||||
<div class="h-14 bg-gray-200 rounded-lg"></div>
|
||||
<div class="h-14 bg-gray-200 rounded-lg"></div>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
function showErrorState(message) {
|
||||
const $profileCard = $("#profile-card");
|
||||
const $accountSection = $("#account-section");
|
||||
const $rolesSection = $("#roles-section");
|
||||
const $actionsSection = $("#actions-section");
|
||||
|
||||
$accountSection.hide();
|
||||
$rolesSection.hide();
|
||||
$actionsSection.hide();
|
||||
|
||||
$profileCard.html(`
|
||||
<div class="text-center py-8">
|
||||
<svg class="mx-auto h-16 w-16 text-red-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
|
||||
</svg>
|
||||
<h3 class="text-xl font-medium text-gray-900 mb-2">${escapeHtml(message)}</h3>
|
||||
<p class="text-gray-500 mb-6">Не удалось загрузить профиль</p>
|
||||
<div class="flex justify-center gap-4">
|
||||
<button id="retry-btn" class="bg-gray-500 text-white px-6 py-2 rounded-lg hover:bg-gray-600 transition-colors">
|
||||
Попробовать снова
|
||||
</button>
|
||||
<a href="/" class="bg-white text-gray-700 px-6 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">
|
||||
На главную
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
$("#retry-btn").on("click", function () {
|
||||
$accountSection.show();
|
||||
$rolesSection.show();
|
||||
$actionsSection.show();
|
||||
loadProfile();
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
const div = document.createElement("div");
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
const $guestLink = $("#guest-link");
|
||||
const $userBtn = $("#user-btn");
|
||||
const $userDropdown = $("#user-dropdown");
|
||||
const $userArrow = $("#user-arrow");
|
||||
const $userAvatar = $("#user-avatar");
|
||||
const $dropdownName = $("#dropdown-name");
|
||||
const $dropdownUsername = $("#dropdown-username");
|
||||
const $dropdownEmail = $("#dropdown-email");
|
||||
const $logoutBtn = $("#logout-btn");
|
||||
|
||||
let isDropdownOpen = false;
|
||||
|
||||
function openDropdown() {
|
||||
isDropdownOpen = true;
|
||||
$userDropdown.removeClass("hidden");
|
||||
$userArrow.addClass("rotate-180");
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
isDropdownOpen = false;
|
||||
$userDropdown.addClass("hidden");
|
||||
$userArrow.removeClass("rotate-180");
|
||||
}
|
||||
|
||||
$userBtn.on("click", function (e) {
|
||||
e.stopPropagation();
|
||||
isDropdownOpen ? closeDropdown() : openDropdown();
|
||||
});
|
||||
|
||||
$(document).on("click", function (e) {
|
||||
if (isDropdownOpen && !$(e.target).closest("#user-menu-container").length) {
|
||||
closeDropdown();
|
||||
}
|
||||
});
|
||||
|
||||
$logoutBtn.on("click", logout);
|
||||
|
||||
function showGuest() {
|
||||
$guestLink.removeClass("hidden");
|
||||
$userBtn.addClass("hidden").removeClass("flex");
|
||||
closeDropdown();
|
||||
}
|
||||
|
||||
function showUser(user) {
|
||||
$guestLink.addClass("hidden");
|
||||
$userBtn.removeClass("hidden").addClass("flex");
|
||||
|
||||
const displayName = user.full_name || user.username;
|
||||
const firstLetter = displayName.charAt(0).toUpperCase();
|
||||
|
||||
$userAvatar.text(firstLetter);
|
||||
$dropdownName.text(displayName);
|
||||
$dropdownUsername.text("@" + user.username);
|
||||
$dropdownEmail.text(user.email);
|
||||
`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
$("#account-info").html(html);
|
||||
}
|
||||
|
||||
function renderRoles(userRoles, allRoles) {
|
||||
const $container = $("#roles-container");
|
||||
if (userRoles.length === 0) {
|
||||
$container.html('<p class="text-gray-500">Нет ролей</p>');
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentUser) {
|
||||
showUser(currentUser);
|
||||
const roleMap = {};
|
||||
allRoles.forEach((r) => (roleMap[r.name] = r.description));
|
||||
|
||||
const html = userRoles
|
||||
.map(
|
||||
(role) => `
|
||||
<div class="p-3 bg-blue-50 border border-blue-100 rounded text-blue-800">
|
||||
<div class="font-bold capitalize">${Utils.escapeHtml(role)}</div>
|
||||
<div class="text-xs opacity-75">${Utils.escapeHtml(roleMap[role] || "")}</div>
|
||||
</div>
|
||||
`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
$container.html(html);
|
||||
}
|
||||
|
||||
$("#submit-password-btn").on("click", async function () {
|
||||
const $btn = $(this);
|
||||
const newPass = $("#new-password").val();
|
||||
const confirm = $("#confirm-password").val();
|
||||
|
||||
if (newPass !== confirm) {
|
||||
Utils.showToast("Пароли не совпадают", "error");
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
if (newPass.length < 4) {
|
||||
Utils.showToast("Пароль слишком короткий", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
$btn.prop("disabled", true).text("Меняем...");
|
||||
|
||||
try {
|
||||
await Api.request("/api/auth/me", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
password: newPass,
|
||||
}),
|
||||
});
|
||||
|
||||
Utils.showToast("Пароль успешно изменен", "success");
|
||||
window.dispatchEvent(new CustomEvent("close-modal"));
|
||||
|
||||
$("#change-password-form")[0].reset();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
Utils.showToast(error.message || "Ошибка смены пароля", "error");
|
||||
} finally {
|
||||
$btn.prop("disabled", false).text("Сменить");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ h1 {
|
||||
letter-spacing: 10px;
|
||||
}
|
||||
|
||||
h2,
|
||||
nav ul li a {
|
||||
font-family: "Dited", sans-serif;
|
||||
letter-spacing: 2.5px;
|
||||
@@ -245,8 +246,8 @@ button:disabled {
|
||||
}
|
||||
|
||||
.line-clamp-3 {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
const Utils = {
|
||||
escapeHtml: (text) => {
|
||||
if (!text) return "";
|
||||
return text.replace(/[&<>"']/g, function (m) {
|
||||
return {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
}[m];
|
||||
});
|
||||
},
|
||||
|
||||
showToast: (message, type = "info") => {
|
||||
const container = document.getElementById("toast-container");
|
||||
if (!container) return;
|
||||
|
||||
const el = document.createElement("div");
|
||||
const colors =
|
||||
type === "error"
|
||||
? "bg-red-500"
|
||||
: type === "success"
|
||||
? "bg-green-500"
|
||||
: "bg-blue-500";
|
||||
el.className = `${colors} text-white px-6 py-3 rounded shadow-lg transform transition-all duration-300 translate-y-10 opacity-0 mb-3`;
|
||||
el.textContent = message;
|
||||
|
||||
container.appendChild(el);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
el.classList.remove("translate-y-10", "opacity-0");
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
el.classList.add("translate-y-10", "opacity-0");
|
||||
setTimeout(() => el.remove(), 300);
|
||||
}, 3000);
|
||||
},
|
||||
|
||||
getGravatarUrl: async (email) => {
|
||||
if (!email) return "";
|
||||
const msgBuffer = new TextEncoder().encode(email.trim().toLowerCase());
|
||||
const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||
const hashHex = hashArray
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
return `https://www.gravatar.com/avatar/${hashHex}?d=identicon&s=200`;
|
||||
},
|
||||
};
|
||||
|
||||
const Api = {
|
||||
async request(endpoint, options = {}) {
|
||||
const token = localStorage.getItem("access_token");
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const config = { ...options, headers };
|
||||
|
||||
try {
|
||||
const response = await fetch(endpoint, config);
|
||||
if (response.status === 401) {
|
||||
Auth.logout();
|
||||
return null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.detail || `Error ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
get(endpoint) {
|
||||
return this.request(endpoint, { method: "GET" });
|
||||
},
|
||||
|
||||
post(endpoint, body) {
|
||||
return this.request(endpoint, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
},
|
||||
|
||||
postForm(endpoint, formData) {
|
||||
return this.request(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: formData.toString(),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const Auth = {
|
||||
logout: () => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
window.location.reload();
|
||||
},
|
||||
|
||||
init: async () => {
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const user = await Api.get("/api/auth/me");
|
||||
if (user) {
|
||||
document.dispatchEvent(new CustomEvent("auth:login", { detail: user }));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Auth check failed", e);
|
||||
}
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user