summaryrefslogtreecommitdiff
path: root/js/app.js
blob: ea6bcbd1cb405fd27377a01d0260c9d281b467b7 (plain)
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
/**
 * Sci-Fi Books Showcase Application
 * Fully offline version - uses local cover images and pre-fetched summaries.
 */

// State management
const state = {
  books: [],
  filteredBooks: [],
  currentFilter: {
    author: 'all',
    format: 'all',
    search: ''
  }
};

// DOM elements cache
const elements = {
  booksGrid: null,
  bookCount: null,
  authorFilter: null,
  formatFilter: null,
  searchInput: null,
  modal: null,
  modalContent: null
};

// Initialize the application
async function init() {
  cacheElements();
  setupUI();
  await initializeBooks();
}

function setupUI() {
  setupFilters();
  setupModal();
}

async function initializeBooks() {
  const books = await loadBooks();
  if (!books) return;

  state.books = books;
  state.filteredBooks = [...books];
  populateAuthorFilter();
  renderBooks();
}

// Cache DOM element references
function cacheElements() {
  elements.booksGrid = document.getElementById('books-grid');
  elements.bookCount = document.getElementById('book-count');
  elements.authorFilter = document.getElementById('author-filter');
  elements.formatFilter = document.getElementById('format-filter');
  elements.searchInput = document.getElementById('search-input');
  elements.modal = document.getElementById('book-modal');
  elements.modalContent = document.getElementById('modal-content');
}

// Load books from JSON file
async function loadBooks() {
  try {
    const response = await fetch('data/books.json');
    if (!response.ok) throw new Error('Failed to load books');
    const data = await response.json();
    return sortBooksByYear(data.books);
  } catch (error) {
    renderLoadError(error);
    return null;
  }
}

function renderLoadError(error) {
  console.error('Error loading books:', error);
  elements.booksGrid.innerHTML = `
    <div class="error-message">
      <p>Failed to load books. Please try refreshing the page.</p>
    </div>
  `;
}

function sortBooksByYear(books) {
  return [...books].sort((a, b) => {
    if (a.year !== b.year) return a.year - b.year;

    const authorCompare = a.author.localeCompare(b.author);
    if (authorCompare !== 0) return authorCompare;

    return a.title.localeCompare(b.title);
  });
}

// Populate author filter dropdown with unique authors
function populateAuthorFilter() {
  const authors = [...new Set(state.books.map(book => book.author))].sort();
  authors.forEach(author => {
    const option = document.createElement('option');
    option.value = author;
    option.textContent = author;
    elements.authorFilter.appendChild(option);
  });
}

// Setup filter event listeners
function setupFilters() {
  elements.authorFilter.addEventListener('change', handleFilterChange);
  elements.formatFilter.addEventListener('change', handleFilterChange);
  elements.searchInput.addEventListener('input', debounce(handleFilterChange, 300));
}

// Handle filter changes and update displayed books
function handleFilterChange() {
  state.currentFilter.author = elements.authorFilter.value;
  state.currentFilter.format = elements.formatFilter.value;
  state.currentFilter.search = elements.searchInput.value.toLowerCase().trim();

  state.filteredBooks = state.books.filter(book => {
    const matchesAuthor = state.currentFilter.author === 'all' ||
                          book.author === state.currentFilter.author;
    const matchesFormat = state.currentFilter.format === 'all' ||
                          book.format.toLowerCase() === state.currentFilter.format;
    const matchesSearch = !state.currentFilter.search ||
                          book.title.toLowerCase().includes(state.currentFilter.search) ||
                          book.author.toLowerCase().includes(state.currentFilter.search);

    return matchesAuthor && matchesFormat && matchesSearch;
  });

  renderBooks();
}

// Get cover image URL - uses local file if available, otherwise shows placeholder
function getCoverUrl(book) {
  if (book.coverLocal) {
    return book.coverLocal;
  }
  return null;
}

// Render books grid
function renderBooks() {
  if (state.filteredBooks.length === 0) {
    elements.booksGrid.innerHTML = `
      <div class="no-results">
        <p>No books found matching your filters.</p>
      </div>
    `;
    elements.bookCount.textContent = '0 books';
    return;
  }

  elements.bookCount.textContent = `${state.filteredBooks.length} book${state.filteredBooks.length !== 1 ? 's' : ''}`;

  elements.booksGrid.innerHTML = state.filteredBooks.map(book => {
    const coverUrl = getCoverUrl(book);
    return `
    <article class="book-card" tabindex="0" data-book-id="${book.id}" role="button" aria-label="View details for ${escapeHtml(book.title)}">
      <div class="cover-container">
        ${coverUrl ? `
          <img
            src="${coverUrl}"
            alt="Cover of ${escapeHtml(book.title)}"
            loading="lazy"
            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
          >
          <div class="cover-placeholder" style="display: none;">
            <span class="book-icon">📚</span>
            <span class="placeholder-title">${escapeHtml(book.title)}</span>
          </div>
        ` : `
          <div class="cover-placeholder">
            <span class="book-icon">📚</span>
            <span class="placeholder-title">${escapeHtml(book.title)}</span>
          </div>
        `}
      </div>
      <div class="card-info">
        <h3>${escapeHtml(book.title)}</h3>
        <p class="author">${escapeHtml(book.author)}</p>
        <div class="meta">
          <span class="format-badge ${book.format.toLowerCase()}">${book.format}</span>
          <span class="format-badge">${book.year}</span>
        </div>
      </div>
    </article>
  `}).join('');

  // Add click handlers to book cards
  document.querySelectorAll('.book-card').forEach(card => {
    card.addEventListener('click', () => openModal(parseInt(card.dataset.bookId)));
    card.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        openModal(parseInt(card.dataset.bookId));
      }
    });
  });
}

// Setup modal functionality
function setupModal() {
  // Close on backdrop click
  elements.modal.addEventListener('click', (e) => {
    if (e.target === elements.modal) {
      closeModal();
    }
  });

  // Close on Escape key
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && elements.modal.classList.contains('active')) {
      closeModal();
    }
  });
}

// Open modal with book details
function openModal(bookId) {
  const book = state.books.find(b => b.id === bookId);
  if (!book) return;

  const coverUrl = getCoverUrl(book);

  // Get summary from book data (embedded by build.js)
  const summary = book.summary;

  // Build summary section - split into paragraphs
  let summaryHtml;
  if (summary) {
    const paragraphs = summary.split(/\n\n+/).filter(p => p.trim());
    const paragraphsHtml = paragraphs.map(p => `<p>${escapeHtml(p)}</p>`).join('\n');
    summaryHtml = `
      <h3>Plot</h3>
      ${paragraphsHtml}
    `;
  } else {
    summaryHtml = `
      <h3>Plot</h3>
      <p class="no-summary">No plot summary available for this book.</p>
    `;
  }

  // Render modal content
  elements.modalContent.innerHTML = `
    <button class="modal-close" aria-label="Close modal">&times;</button>
    <div class="modal-body">
      <div class="modal-cover">
        ${coverUrl ? `
          <img
            src="${coverUrl}"
            alt="Cover of ${escapeHtml(book.title)}"
            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
          >
          <div class="cover-placeholder" style="display: none;">
            <span class="book-icon">📚</span>
            <span class="placeholder-title">${escapeHtml(book.title)}</span>
          </div>
        ` : `
          <div class="cover-placeholder">
            <span class="book-icon">📚</span>
            <span class="placeholder-title">${escapeHtml(book.title)}</span>
          </div>
        `}
      </div>
      <div class="modal-details">
        <h2 id="modal-title">${escapeHtml(book.title)}</h2>
        <p class="author">${escapeHtml(book.author)}</p>
        <div class="modal-meta">
          <div class="meta-item">
            <span class="label">Year</span>
            <span class="value">${book.year}</span>
          </div>
          <div class="meta-item">
            <span class="label">Format</span>
            <span class="value">${book.format}</span>
          </div>
          <div class="meta-item">
            <span class="label">Language</span>
            <span class="value">${book.language === 'de' ? 'German' : 'English'}</span>
          </div>
          ${book.isbn ? `
            <div class="meta-item">
              <span class="label">ISBN</span>
              <span class="value">${book.isbn}</span>
            </div>
          ` : ''}
        </div>
        <div class="modal-summary">
          ${summaryHtml}
        </div>
      </div>
    </div>
  `;

  // Add close button handler
  elements.modalContent.querySelector('.modal-close').addEventListener('click', closeModal);

  // Show modal
  elements.modal.classList.add('active');
  document.body.style.overflow = 'hidden';
}

// Close modal
function closeModal() {
  elements.modal.classList.remove('active');
  document.body.style.overflow = '';
}

// Utility: Escape HTML to prevent XSS
function escapeHtml(text) {
  if (!text) return '';
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

// Utility: Debounce function for search input
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', init);