-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
376 lines (325 loc) · 14.4 KB
/
Copy pathapp.js
File metadata and controls
376 lines (325 loc) · 14.4 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import { books as initialBooks, categories } from './data.js';
// Application Logic
class LibraryApp {
constructor() {
try {
const storedBooks = localStorage.getItem('libraryBooks');
this.books = storedBooks ? JSON.parse(storedBooks) : [...initialBooks];
} catch (error) {
console.error("Failed to parse books from local storage:", error);
this.books = [...initialBooks];
}
this.currentCategory = 'All';
this.currentView = 'browse'; // 'browse', 'favorites', 'history'
this.currentSort = 'newest';
this.searchQuery = '';
this.history = []; // Placeholder for history
// Load history safely
try {
const storedHistory = localStorage.getItem('libraryHistory');
this.history = storedHistory ? JSON.parse(storedHistory) : [];
} catch (e) {
console.error("Failed to parse history:", e);
this.history = [];
}
this.init();
}
init() {
this.cacheDOM();
this.bindEvents();
this.renderCategories();
this.renderBooks();
}
saveToLocalStorage() {
try {
localStorage.setItem('libraryBooks', JSON.stringify(this.books));
localStorage.setItem('libraryHistory', JSON.stringify(this.history));
} catch (error) {
console.error("Failed to save to local storage:", error);
alert("Error: Could not save changes. Local storage might be full.");
}
}
cacheDOM() {
this.bookGrid = document.getElementById('bookGrid');
this.categoryList = document.getElementById('categoryList');
this.searchInput = document.querySelector('.search-input');
this.sortSelect = document.getElementById('sortSelect');
this.modalOverlay = document.getElementById('modalOverlay');
this.openModalBtn = document.getElementById('openModalBtn');
this.closeModalBtn = document.getElementById('closeModalBtn');
this.addBookForm = document.getElementById('addBookForm');
// Sidebar Elements
this.navItems = document.querySelectorAll('.nav-item');
// Details Modal Elements
this.detailsModalOverlay = document.getElementById('detailsModalOverlay');
this.closeDetailsBtn = document.getElementById('closeDetailsBtn');
this.detailsTitle = document.getElementById('detailsTitle');
this.detailsCover = document.getElementById('detailsCover');
this.detailsAuthor = document.getElementById('detailsAuthor');
this.detailsCategory = document.getElementById('detailsCategory');
this.detailsRating = document.getElementById('detailsRating');
this.detailsStatus = document.getElementById('detailsStatus');
this.detailsSummary = document.getElementById('detailsSummary');
}
bindEvents() {
this.searchInput.addEventListener('input', (e) => {
this.searchQuery = e.target.value.toLowerCase();
this.renderBooks();
});
this.sortSelect.addEventListener('change', (e) => {
this.currentSort = e.target.value;
this.renderBooks();
});
this.openModalBtn.addEventListener('click', () => this.toggleModal(true));
this.closeModalBtn.addEventListener('click', () => this.toggleModal(false));
this.modalOverlay.addEventListener('click', (e) => {
if (e.target === this.modalOverlay) this.toggleModal(false);
});
this.addBookForm.addEventListener('submit', (e) => this.handleAddBook(e));
// Sidebar Navigation
this.navItems.forEach(item => {
item.addEventListener('click', () => {
const view = item.dataset.nav;
this.handleNavigation(view);
// Update active state
this.navItems.forEach(nav => nav.classList.remove('active'));
item.classList.add('active');
});
});
// Book Grid Event Delegation
this.bookGrid.addEventListener('click', (e) => {
const btn = e.target.closest('.action-btn');
if (!btn) return;
const action = btn.dataset.action;
const id = Number(btn.dataset.id);
if (action === 'toggle-status') {
this.toggleStatus(id);
} else if (action === 'view-details') {
this.showBookDetails(id);
} else if (action === 'toggle-favorite') {
this.toggleFavorite(id);
}
});
// Details Modal Events
this.closeDetailsBtn.addEventListener('click', () => this.toggleDetailsModal(false));
this.detailsModalOverlay.addEventListener('click', (e) => {
if (e.target === this.detailsModalOverlay) this.toggleDetailsModal(false);
});
}
toggleModal(show) {
this.modalOverlay.classList.toggle('active', show);
if (!show) this.addBookForm.reset();
}
handleAddBook(e) {
e.preventDefault();
const formData = new FormData(e.target);
// Input Validation
const coverUrl = formData.get('cover');
let finalCover = "https://images.unsplash.com/photo-1543002588-bfa74002ed7e?auto=format&fit=crop&q=80&w=800";
if (coverUrl) {
try {
new URL(coverUrl);
finalCover = coverUrl;
} catch (_) {
alert("Invalid Cover URL. Using default cover.");
}
}
const newBook = {
id: Date.now(),
title: formData.get('title'),
author: formData.get('author'),
category: formData.get('category'),
cover: finalCover,
status: 'Available',
rating: 4.5, // Default rating
summary: formData.get('summary') || "No summary available."
};
this.books.unshift(newBook);
this.saveToLocalStorage();
// Reset filters so the new book is visible
this.currentCategory = 'All';
this.searchQuery = '';
this.searchInput.value = '';
this.renderCategories(); // Re-render categories to update active state
this.renderBooks();
this.toggleModal(false);
alert('Book added successfully!');
}
toggleStatus(id) {
const book = this.books.find(b => b.id === id);
if (book) {
book.status = book.status === 'Available' ? 'Borrowed' : 'Available';
// Log to history
this.history.unshift({
bookId: book.id,
bookTitle: book.title,
action: book.status, // "Borrowed" or "Available" (Returned)
date: new Date().toLocaleString()
});
this.saveToLocalStorage();
this.renderBooks();
// If details modal is open for this book, update it
if (this.detailsModalOverlay.classList.contains('active') && this.currentBookId === id) {
this.detailsStatus.textContent = book.status;
this.showBookDetails(id);
}
}
}
toggleFavorite(id) {
const book = this.books.find(b => b.id === id);
if (book) {
book.isFavorite = !book.isFavorite;
this.saveToLocalStorage();
this.renderBooks();
}
}
toggleDetailsModal(show) {
this.detailsModalOverlay.classList.toggle('active', show);
}
showBookDetails(id) {
const book = this.books.find(b => b.id === id);
if (!book) return;
this.currentBookId = id; // Track current book for updates
this.detailsTitle.textContent = book.title;
this.detailsCover.src = book.cover;
this.detailsCover.alt = book.title;
this.detailsAuthor.textContent = book.author;
this.detailsCategory.textContent = book.category;
this.detailsRating.textContent = book.rating;
this.detailsStatus.textContent = book.status;
this.detailsSummary.textContent = book.summary || "No summary available.";
this.toggleDetailsModal(true);
}
handleNavigation(view) {
this.currentView = view;
if (view === 'favorites') {
// Logic to filter favorites (Coming up)
this.currentCategory = 'All'; // Reset category filter when switching views
} else if (view === 'history') {
// Logic for history (Meaningless for grid, handled in render)
} else if (view === 'settings') {
alert('Settings coming soon');
return;
}
this.renderBooks();
}
filterBooks() {
return this.books.filter(book => {
// View filtering
if (this.currentView === 'favorites') {
// TODO: Add support for favorite property. For now, checking nothing.
// We need to implement isFavorite property.
if (!book.isFavorite) return false;
}
const matchesCategory = this.currentCategory === 'All' || book.category === this.currentCategory;
const matchesSearch = book.title.toLowerCase().includes(this.searchQuery) ||
book.author.toLowerCase().includes(this.searchQuery);
return matchesCategory && matchesSearch;
});
}
renderCategories() {
this.categoryList.innerHTML = categories.map(cat => `
<button class="category-pill ${cat === this.currentCategory ? 'active' : ''}"
data-category="${cat}">
${cat}
</button>
`).join('');
this.categoryList.querySelectorAll('.category-pill').forEach(btn => {
btn.addEventListener('click', () => {
this.currentCategory = btn.dataset.category;
this.renderCategories();
this.renderBooks();
});
});
}
renderBooks() {
// Handle History View specially
if (this.currentView === 'history') {
this.renderHistory();
return;
}
const filteredBooks = this.filterBooks();
// Sorting
filteredBooks.sort((a, b) => {
if (this.currentSort === 'newest') {
return b.id - a.id;
} else if (this.currentSort === 'title') {
return a.title.localeCompare(b.title);
} else if (this.currentSort === 'rating') {
return b.rating - a.rating;
}
return 0;
});
if (filteredBooks.length === 0) {
this.bookGrid.innerHTML = `
<div style="grid-column: 1/-1; text-align: center; color: var(--text-muted); padding: 3rem;">
<i class="fa-solid fa-book-open" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;"></i>
<p>No books found matching your criteria.</p>
</div>
`;
return;
}
this.bookGrid.innerHTML = filteredBooks.map(book => `
<div class="book-card">
<div style="position: relative;">
<img src="${book.cover}" alt="${book.title}" class="book-cover">
<button class="action-btn" data-action="toggle-favorite" data-id="${book.id}"
style="position: absolute; top: 10px; right: 10px; background: rgba(0,0,0,0.6); color: ${book.isFavorite ? 'var(--secondary)' : 'white'};">
<i class="${book.isFavorite ? 'fa-solid' : 'fa-regular'} fa-heart"></i>
</button>
</div>
<div class="book-info">
<div class="book-category">${book.category}</div>
<h3 class="book-title" title="${book.title}">${book.title}</h3>
<p class="book-author">by ${book.author}</p>
<div class="book-footer">
<span class="status-badge status-${book.status.toLowerCase()}">
${book.status}
</span>
<div style="display: flex; gap: 0.5rem;">
<button class="action-btn" data-action="view-details" data-id="${book.id}" title="View Details">
<i class="fa-solid fa-eye"></i>
</button>
<button class="action-btn" data-action="toggle-status" data-id="${book.id}"
title="${book.status === 'Available' ? 'Borrow' : 'Return'}">
<i class="fa-solid ${book.status === 'Available' ? 'fa-book-bookmark' : 'fa-rotate-left'}"></i>
</button>
</div>
</div>
</div>
</div>
`).join('');
}
renderHistory() {
if (this.history.length === 0) {
this.bookGrid.innerHTML = `
<div style="grid-column: 1/-1; text-align: center; color: var(--text-muted); padding: 3rem;">
<i class="fa-solid fa-clock-rotate-left" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;"></i>
<p>No history yet.</p>
</div>
`;
return;
}
// Render history as a list/table
this.bookGrid.innerHTML = `
<div style="grid-column: 1/-1;">
<h2 style="margin-bottom: 1.5rem; color: var(--text-main);">Activity History</h2>
<div style="background: var(--surface); border-radius: var(--radius); overflow: hidden;">
${this.history.map(item => `
<div style="padding: 1rem; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center;">
<div>
<span style="color: var(--primary); font-weight: 600;">${item.action === 'Borrowed' ? 'Borrowed' : 'Returned'}</span>
<span style="color: var(--text-main); font-weight: 500; margin: 0 0.5rem;">${item.bookTitle}</span>
</div>
<span style="color: var(--text-muted); font-size: 0.9rem;">${item.date}</span>
</div>
`).join('')}
</div>
</div>
`;
}
}
// Initialize app
document.addEventListener('DOMContentLoaded', () => {
window.app = new LibraryApp();
});