-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
218 lines (199 loc) · 8.21 KB
/
Copy pathscript.js
File metadata and controls
218 lines (199 loc) · 8.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Класс LibrarySystem (модель DFD)
class LibrarySystem {
constructor() {
this.books = [];
// Начальные данные
this.addBook("Война и мир", "Лев Толстой", 1869);
this.addBook("Преступление и наказание", "Фёдор Достоевский", 1866);
this.addBook("Мастер и Маргарита", "Михаил Булгаков", 1967);
}
addBook(title, author, year) {
if (!title || !author || !year) return false;
const book = {
id: Date.now() + Math.random(),
title: title.trim(),
author: author.trim(),
year: parseInt(year),
available: true
};
this.books.push(book);
return true;
}
findBook(title) {
if (!title) return null;
return this.books.find(book => book.title.toLowerCase() === title.trim().toLowerCase()) || null;
}
issueBook(title) {
const book = this.findBook(title);
if (!book) return { success: false, message: `Книга "${title}" не найдена.` };
if (!book.available) return { success: false, message: `Книга "${title}" уже выдана.` };
book.available = false;
return { success: true, message: `Книга "${title}" выдана читателю.` };
}
returnBook(title) {
const book = this.findBook(title);
if (!book) return { success: false, message: `Книга "${title}" не найдена.` };
if (book.available) return { success: false, message: `Книга "${title}" уже доступна.` };
book.available = true;
return { success: true, message: `Книга "${title}" возвращена в библиотеку.` };
}
getAllBooks() {
return [...this.books];
}
}
// Инициализация
const library = new LibrarySystem();
// DOM элементы
const booksContainer = document.getElementById('booksContainer');
const addBookBtn = document.getElementById('addBookBtn');
const searchBookBtn = document.getElementById('searchBookBtn');
const issueBookBtn = document.getElementById('issueBookBtn');
const returnBookBtn = document.getElementById('returnBookBtn');
const addMessage = document.getElementById('addMessage');
const searchResult = document.getElementById('searchResult');
const actionMessage = document.getElementById('actionMessage');
// Утилиты
function escapeHtml(str) {
if (!str) return '';
return str.replace(/[&<>]/g, function(m) {
if (m === '&') return '&';
if (m === '<') return '<';
if (m === '>') return '>';
return m;
});
}
function showMessage(element, text, isSuccess) {
element.textContent = text;
element.className = `message ${isSuccess ? 'success' : 'error'}`;
setTimeout(() => {
element.textContent = '';
element.className = 'message';
}, 3000);
}
// Рендер всех книг
function renderBooks() {
const books = library.getAllBooks();
if (books.length === 0) {
booksContainer.innerHTML = '<p class="empty-message">Фонд пуст. Добавьте первую книгу.</p>';
return;
}
let html = '';
books.forEach(book => {
const statusClass = book.available ? 'available' : 'issued';
const statusText = book.available ? 'Доступна' : 'Выдана';
html += `
<div class="book-item">
<div class="book-info">
<div class="book-title">
${escapeHtml(book.title)}
<span class="status ${statusClass}">${statusText}</span>
</div>
<div class="book-details">${escapeHtml(book.author)} • ${book.year} г.</div>
</div>
<div class="book-actions">
<button onclick="window.quickIssue('${escapeHtml(book.title).replace(/'/g, "\\'")}')"
${!book.available ? 'disabled' : ''} class="btn-warning small">Выдать</button>
<button onclick="window.quickReturn('${escapeHtml(book.title).replace(/'/g, "\\'")}')"
${book.available ? 'disabled' : ''} class="btn-success small">Вернуть</button>
</div>
</div>
`;
});
booksContainer.innerHTML = html;
}
// Быстрые действия
window.quickIssue = function(title) {
const result = library.issueBook(title);
showMessage(actionMessage, result.message, result.success);
renderBooks();
const searchInput = document.getElementById('searchTitle');
if (searchInput.value.trim()) performSearch();
};
window.quickReturn = function(title) {
const result = library.returnBook(title);
showMessage(actionMessage, result.message, result.success);
renderBooks();
const searchInput = document.getElementById('searchTitle');
if (searchInput.value.trim()) performSearch();
};
// Поиск
function performSearch() {
const title = document.getElementById('searchTitle').value;
if (!title.trim()) {
searchResult.innerHTML = '<em>Введите название для поиска.</em>';
return;
}
const book = library.findBook(title);
if (book) {
const status = book.available ? 'Доступна' : 'Выдана';
searchResult.innerHTML = `
<strong>📘 Найдено:</strong><br>
<strong>${escapeHtml(book.title)}</strong><br>
${escapeHtml(book.author)} (${book.year})<br>
<span class="status ${book.available ? 'available' : 'issued'}">${status}</span>
`;
} else {
searchResult.innerHTML = '<em>❌ Книга не найдена.</em>';
}
}
// Добавление книги
addBookBtn.addEventListener('click', () => {
const title = document.getElementById('bookTitle').value;
const author = document.getElementById('bookAuthor').value;
const year = document.getElementById('bookYear').value;
if (!title || !author || !year) {
showMessage(addMessage, 'Заполните все поля!', false);
return;
}
const success = library.addBook(title, author, year);
if (success) {
showMessage(addMessage, `Книга "${title}" успешно добавлена.`, true);
document.getElementById('bookTitle').value = '';
document.getElementById('bookAuthor').value = '';
document.getElementById('bookYear').value = '';
renderBooks();
const searchInput = document.getElementById('searchTitle');
if (searchInput.value.trim()) performSearch();
} else {
showMessage(addMessage, 'Ошибка добавления книги.', false);
}
});
// Поиск (кнопка и Enter)
searchBookBtn.addEventListener('click', performSearch);
document.getElementById('searchTitle').addEventListener('keypress', (e) => {
if (e.key === 'Enter') performSearch();
});
// Выдача
issueBookBtn.addEventListener('click', () => {
const title = document.getElementById('actionTitle').value;
if (!title.trim()) {
showMessage(actionMessage, 'Введите название книги.', false);
return;
}
const result = library.issueBook(title);
showMessage(actionMessage, result.message, result.success);
if (result.success) {
document.getElementById('actionTitle').value = '';
renderBooks();
const searchInput = document.getElementById('searchTitle');
if (searchInput.value.trim()) performSearch();
}
});
// Возврат
returnBookBtn.addEventListener('click', () => {
const title = document.getElementById('actionTitle').value;
if (!title.trim()) {
showMessage(actionMessage, 'Введите название книги.', false);
return;
}
const result = library.returnBook(title);
showMessage(actionMessage, result.message, result.success);
if (result.success) {
document.getElementById('actionTitle').value = '';
renderBooks();
const searchInput = document.getElementById('searchTitle');
if (searchInput.value.trim()) performSearch();
}
});
// Первоначальный рендер
renderBooks();