Files
InternetProg_MorozovDV_PIbd-22/html/mvc/view.js

149 lines
6.1 KiB
JavaScript

const view = {
renderAuthorOptions(authors, selectElement) {
selectElement.innerHTML = '<option value="">Выберите автора</option>';
authors.forEach((author) => {
const option = document.createElement("option");
option.value = author.id;
option.textContent = author.name;
selectElement.appendChild(option);
});
},
renderStatusOptions(statuses, selectElement) {
selectElement.innerHTML = '<option value="">Выберите статус</option>';
statuses.forEach((status) => {
const option = document.createElement("option");
option.value = status.id;
option.textContent = status.name;
selectElement.appendChild(option);
});
},
renderBooks(books, container) {
container.innerHTML = "";
books.forEach((book) => {
// определяем класс для статуса
let statusClass = "text-muted fw-bold";
switch ((book.statusName || "").toLowerCase()) {
case "вышла":
statusClass = "text-success fw-bold";
break;
case "не вышла":
statusClass = "text-danger fw-bold";
break;
case "не переведена":
statusClass = "text-warning fw-bold";
break;
case "прочитана":
statusClass = "text-primary fw-bold";
break;
default:
statusClass = "text-muted fw-bold";
break;
}
const div = document.createElement("div");
div.className = "card mb-3";
div.innerHTML = `
<a href="manga.html">
<img src="${book.cover || "img/заглушка.jpg"}" class="card-img-top shadow mt-2" alt="Обложка книги" style="max-height:300px; object-fit:contain; ">
</a>
<div class="card-body">
<h5 class="card-title">${book.title}</h5>
<p class="card-text">${book.description}</p>
<p class="card-text"><small class="text-muted">Автор: ${book.authorName || "Неизвестен"}</small></p>
<p class="card-text"><small class="${statusClass}">Статус: ${book.statusName || "Неизвестен"}</small></p>
<button data-id="${book.id}" class="btn btn-danger btn-sm delete-btn">Удалить</button>
<a href="add_book.html?id=${book.id}" class="btn btn-warning btn-sm edit-btn">Редактировать</a>
</div>`;
container.appendChild(div);
});
},
bindCoverInput() {
const coverInput = document.getElementById("cover");
const coverPreview = document.getElementById("coverPreview");
coverInput.addEventListener("change", () => {
const file = coverInput.files[0];
if (!file) {
coverPreview.style.display = "none";
coverPreview.src = "";
return;
}
const reader = new FileReader();
reader.onload = (e) => {
coverPreview.src = e.target.result;
coverPreview.style.display = "block";
};
reader.readAsDataURL(file);
});
},
async getBookFormData() {
const coverInput = document.getElementById("cover");
let coverData = "";
if (coverInput.files.length > 0) {
coverData = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error("Ошибка чтения файла обложки"));
reader.readAsDataURL(coverInput.files[0]);
});
} else {
// Если форма редактирования, и файл не поменяли, можно брать существующий cover (или пустую строку)
coverData = document.getElementById("cover").dataset.currentCover || "";
}
return {
title: document.getElementById("title").value.trim(),
description: document.getElementById("description").value.trim(),
authorId: parseInt(document.getElementById("authorId").value, 10),
statusId: parseInt(document.getElementById("statusId").value, 10),
cover: coverData,
};
},
fillBookForm(book) {
document.getElementById("title").value = book.title || "";
document.getElementById("description").value = book.description || "";
document.getElementById("authorId").value = book.authorId || "";
document.getElementById("statusId").value = book.statusId || "";
// Запоминаем текущую обложку в дата-атрибут для использования при сохранении
const coverInput = document.getElementById("cover");
coverInput.value = ""; // Очистить input файл
coverInput.dataset.currentCover = book.cover || "";
// Показываем превью
const coverPreview = document.getElementById("coverPreview");
if (book.cover) {
coverPreview.src = book.cover;
coverPreview.style.display = "block";
} else {
coverPreview.style.display = "none";
}
},
resetBookForm() {
document.getElementById("bookForm").reset();
const coverPreview = document.getElementById("coverPreview");
coverPreview.style.display = "none";
coverPreview.src = "";
},
showAlert(message, isError = false) {
alert(isError ? `Ошибка: ${message}` : `Успех: ${message}`);
},
confirm(message) {
return new Promise((resolve) => {
const result = confirm(message);
resolve(result);
});
},
};
export default view;