$(document).ready(() => { const pathParts = window.location.pathname.split("/"); const bookId = pathParts[pathParts.length - 1]; if (!bookId || isNaN(bookId)) { showErrorState("Некорректный ID книги"); return; } loadBook(bookId); function loadBook(id) { showLoadingState(); 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(`

${escapeHtml(book.title)}

ID: ${book.id}

${escapeHtml(authorsText)}

${escapeHtml(book.description || "Описание отсутствует")}

Вернуться к списку книг
`); } function renderAuthors(authors) { const $container = $("#authors-container"); const $section = $("#authors-section"); $container.empty(); if (!authors || authors.length === 0) { $section.hide(); return; } const $grid = $('
'); authors.forEach((author) => { const firstLetter = author.name.charAt(0).toUpperCase(); const $authorCard = $(`
${firstLetter}
${escapeHtml(author.name)}
`); $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 = $('
'); genres.forEach((genre) => { const $genreTag = $(` ${escapeHtml(genre.name)} `); $grid.append($genreTag); }); $container.append($grid); } function showLoadingState() { const $bookCard = $("#book-card"); const $authorsContainer = $("#authors-container"); const $genresContainer = $("#genres-container"); $bookCard.html(`
`); $authorsContainer.html(`
`); $genresContainer.html(`
`); } function showErrorState(message) { const $bookCard = $("#book-card"); const $authorsSection = $("#authors-section"); const $genresSection = $("#genres-section"); $authorsSection.hide(); $genresSection.hide(); $bookCard.html(`

${escapeHtml(message)}

Не удалось загрузить информацию о книге

К списку книг
`); $("#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(); }); $(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(); }); } });