-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.js
More file actions
473 lines (385 loc) · 15.2 KB
/
render.js
File metadata and controls
473 lines (385 loc) · 15.2 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// Global variables
let selectedEpubPath = null;
let selectedCoverPath = null;
let currentBookId = null;
let books = [];
let metaData = null;
let modalSelectedBook = null;
// DOM Elements
const bookDateInput = document.getElementById('bookDate');
const bookTitleInput = document.getElementById('bookTitle');
const bookAuthorInput = document.getElementById('bookAuthor');
const bookDescriptionInput = document.getElementById('bookDescription');
const bookTagsInput = document.getElementById('bookTags');
const selectEpubBtn = document.getElementById('selectEpubBtn');
const selectCoverBtn = document.getElementById('selectCoverBtn');
const selectedEpubFile = document.getElementById('selectedEpubFile');
const selectedCoverFile = document.getElementById('selectedCoverFile');
const selectedCoverImage = document.getElementById('selectedCoverImage');
const addBookBtn = document.getElementById('addBookBtn');
const bookGrid = document.getElementById('bookGrid');
const bookModal = document.getElementById('bookModal');
const closeModal = document.getElementById('closeModal');
const modalBookTitle = document.getElementById('modalBookTitle');
const modalBookAuthor = document.getElementById('modalBookAuthor');
const modalBookDescription = document.getElementById('modalBookDescription');
const modalBookCover = document.getElementById('modalBookCover');
const modalBookTags = document.getElementById('modalBookTags');
const deleteBookBtn = document.getElementById('deleteBookBtn');
const openExternalBtn = document.getElementById('openExternalBtn');
const coverImage = document.getElementById('selectedCoverImage')
const addBookBtnLabel = document.getElementById('addBookBtnLabel')
const resetBtn = document.getElementById('resetBtn');
const dropZone = document.getElementById('drop-zone');
const reader = document.getElementById('reader');
// Initialize the application
async function init() {
await loadBooks();
setupEventListeners();
setupTabs();
placeHolderCover();
}
async function placeHolderCover(){
const coverPlaceHolder = await window.databaseAPI.getCoverPlaceholder();
coverImage.src = coverPlaceHolder;
}
// Load books from the database
async function loadBooks() {
try {
books = await window.databaseAPI.getBooks();
console.log("Loaded books from DB:", books.length);
renderBooks();
} catch (err) {
console.error('Error loading books:', err);
}
}
async function renderBooks() {
bookGrid.innerHTML = '';
if (books.length === 0) {
bookGrid.innerHTML = '<p>No books in your library yet. Add your first book using the form on the left.</p>';
return;
}
// Use a for...of loop so we can use await for each cover fetch.
for (const book of books) {
const bookCard = document.createElement('div');
bookCard.className = 'book-card';
bookCard.dataset.id = book.id;
let coverStyle = 'background-color: #4a6da7'; // fallback style
if (book.cover_path) {
try {
// Get the cover image as a data URL via IPC
const coverDataUrl = await window.databaseAPI.getBookCover(book.id);
if (coverDataUrl) {
coverStyle = `background-image: url('${coverDataUrl}')`;
console.log("Got a book cover");
}
else{
console.log("No book cover");
}
} catch (error) {
console.error('Error fetching cover for book', book.id, error);
}
}
bookCard.innerHTML = `
<div class="book-cover" style="${coverStyle}"></div>
<div class="book-info">
<h3 class="book-title">${book.title}</h3>
<p class="book-author">${book.author}</p>
</div>
`;
bookCard.addEventListener('click', () => openBookDetails(book.id));
bookGrid.appendChild(bookCard);
}
console.log("Rendered books count:", bookGrid.childNodes.length);
}
// Helper function
async function extractMetaData(epubPath) {
console.log("Calling extractMetaData with path:", epubPath);
if (!epubPath) {
console.error("ExtractMetaData received undefined path!");
return;
}
metaData = await window.databaseAPI.extractMetaData(epubPath);
console.log("Metadata received:", metaData);
return metaData; // metaData is a plain JS object
}
async function renderBook(book) {
// Create a new card for the book.
const bookCard = document.createElement('div');
bookCard.className = 'book-card';
bookCard.dataset.id = book.id;
// Start with a fallback style.
let coverStyle = 'background-color: #4a6da7';
// If the book has a cover, fetch its data URL.
if (book.cover_path) {
try {
const coverDataUrl = await window.databaseAPI.getBookCover(book.id);
if (coverDataUrl) {
coverStyle = `background-image: url('${coverDataUrl}')`;
}
} catch (error) {
console.error('Error fetching cover for book', book.id, error);
}
}
bookCard.innerHTML = `
<div class="book-cover" style="${coverStyle}"></div>
<div class="book-info">
<h3 class="book-title">${book.title}</h3>
<p class="book-author">${book.author}</p>
</div>
`;
// Open book details when clicked.
bookCard.addEventListener('click', () => openBookDetails(book.id));
// Append the new card to the book grid.
bookGrid.appendChild(bookCard);
}
async function handleEpubDrag(file) {
if (file.path) {
const result = await window.databaseAPI.handleEpubDrag({ path: file.path });
await renderBook({
id: result.bookId,
...result.metadata
});
console.log(result);
} else {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async (e) => {
try {
const arrayBuffer = e.target.result;
const result = await window.databaseAPI.handleEpubDrag({ data: arrayBuffer });
console.log(result);
// Immediately render the new book.
await renderBook({
id: result.bookId,
...result.metadata
});
resolve(result);
} catch (err) {
reject(err);
}
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
});
}}
// Set up event listeners
function setupEventListeners() {
console.log("setting up event listeners")
dropZone.addEventListener("dragover", (e) => {
e.preventDefault();
dropZone.classList.add("hover");
e.dataTransfer.dropEffect = "copy";
});
dropZone.addEventListener("dragleave", () => {
dropZone.classList.remove("hover");
});
dropZone.addEventListener("drop", async(e) => {
console.log("Drop event triggered");
e.preventDefault();
dropZone.classList.remove("hover");
const files = e.dataTransfer.files;
const promises = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.name.endsWith(".epub")) {
console.log("EPUB file dropped:", file.name);
promises.push(handleEpubDrag(file));
} else {
console.warn("Not an EPUB:", file.name);
}
}
// Wait until all files are processed
await Promise.all(promises);
// Then re-render the library once
await loadBooks();
});
// Select EPUB file
selectEpubBtn.addEventListener('click', async () => {
const fileInfo = await window.databaseAPI.selectEpubFile();
const { sourcePath } = fileInfo;
console.log('Selected EPUB Path:', sourcePath);
if (sourcePath) {
selectedEpubFile.textContent = sourcePath.split('/').pop();
try {
const metaData = await extractMetaData(sourcePath);
bookTitleInput.value = metaData.title;
bookAuthorInput.value = metaData['author'];
bookDateInput.value = metaData['date'];
coverImage.src = `data:${metaData.cover.mimeType};base64,${metaData.cover.data}`;
selectedCoverFile.textContent = "Extracted from EPUB file";
selectedEpubPath = sourcePath;
addBookBtnLabel.innerText = `Destination Path
${metaData.title} - ${metaData.author}.epub`;
} catch (err) {
console.error('Failed to extract metadata:', err);
}
// Optional: Display metadata in the UI
updateAddButtonState();
}
});
// Select cover image
selectCoverBtn.addEventListener('click', async () => {
selectedCoverPath = await window.databaseAPI.selectCoverImage();
if (selectedCoverPath) {
selectedCoverFile.textContent = selectedCoverPath.split('/').pop();
coverImage.src = `${selectedCoverPath}`;
}
});
resetBtn.addEventListener('click', async () => {
resetForm();
});
// Add book
addBookBtn.addEventListener('click', async () => {
console.log("Add book button clicked")
const title = bookTitleInput.value.trim();
const author = bookAuthorInput.value.trim();
const description = bookDescriptionInput.value.trim();
const tags = bookTagsInput.value.trim();
if (!title || !author || !selectedEpubPath) {
alert('Please fill in all required fields (title, author, and EPUB file)');
return;
}
try {
// Add the book
const bookId = await window.databaseAPI.addBook({
title,
author,
description,
filePath: selectedEpubPath,
coverPath: selectedCoverPath,
coverImage: `data:${metaData.cover.mimeType};base64,${metaData.cover.data}`
});
// Add tags if provided
if (tags) {
const tagArray = tags.split(',').map(tag => tag.trim()).filter(tag => tag);
for (const tagName of tagArray) {
const tagId = await window.databaseAPI.addTag(tagName);
await window.databaseAPI.addTagToBook(bookId, tagId);
}
}
// Reset form
resetForm();
// Reload books
await loadBooks();
} catch (err) {
console.error('Error adding book:', err);
alert('Failed to add book. Please try again.');
}
});
// Close modal
closeModal.addEventListener('click', () => {
bookModal.style.display = 'none';
});
// Delete book
deleteBookBtn.addEventListener('click', async () => {
if (currentBookId && confirm('Are you sure you want to delete this book?')) {
try {
await window.databaseAPI.deleteBook(currentBookId);
bookModal.style.display = 'none';
await loadBooks();
} catch (err) {
console.error('Error deleting book:', err);
alert('Failed to delete book. Please try again.');
}
}
});
async function loadBook() {
const bookPath = modalSelectedBook.file_path;
console.log("Loaded book from modal:", modalSelectedBook.file_path);
await window.readerAPI.openReaderWindow(bookPath);
}
// Open in external reader
openExternalBtn.addEventListener('click', () => {
loadBook();
});
// Close modal when clicking outside
window.addEventListener('click', (event) => {
if (event.target === bookModal) {
bookModal.style.display = 'none';
}
});
}
// Set up tabs in the modal
function setupTabs() {
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const tabId = tab.dataset.tab;
// Update active tab
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
// Update active content
tabContents.forEach(content => content.classList.remove('active'));
document.getElementById(`${tabId}Tab`).classList.add('active');
});
});
}
// Open book details modal
async function openBookDetails(bookId) {
try {
currentBookId = bookId;
modalSelectedBook = await window.databaseAPI.getBookById(bookId);
const tags = await window.databaseAPI.getBookTags(bookId);
modalBookTitle.textContent = modalSelectedBook.title;
modalBookAuthor.textContent = modalSelectedBook.author;
modalBookDescription.textContent = modalSelectedBook.description || 'No description available.';
if (modalSelectedBook.cover_path) {
try {
// Get the cover image as a data URL via IPC
const coverDataUrl = await window.databaseAPI.getBookCover(modalSelectedBook.id);
if (coverDataUrl) {
modalBookCover.style.backgroundImage = `url('${coverDataUrl}')`;
}
else{
modalBookCover.style.backgroundImage = '';
modalBookCover.style.backgroundColor = '#4a6da7';
}
} catch (error) {
console.error('Error fetching cover for book', modalSelectedBook.id, error);
}
}
// Render tags
modalBookTags.innerHTML = '';
tags.forEach(tag => {
const tagElement = document.createElement('span');
tagElement.className = 'tag';
tagElement.textContent = tag.name;
modalBookTags.appendChild(tagElement);
});
// Show the modal
bookModal.style.display = 'flex';
} catch (err) {
console.error('Error loading book details:', err);
}
}
// Reset the add book form
function resetForm() {
bookTitleInput.value = '';
bookAuthorInput.value = '';
bookDescriptionInput.value = '';
bookTagsInput.value = '';
selectedEpubPath = null;
selectedCoverPath = null;
selectedEpubFile.textContent = '';
selectedCoverFile.textContent = '';
coverImage.innerHTML = window.databaseAPI.getCoverPlaceholder();
updateAddButtonState();
addBookBtnLabel.value = "Destination Path"
placeHolderCover();
}
// Update the state of the add button
function updateAddButtonState() {
console.log("updateAddButtonState")
const title = bookTitleInput.value.trim();
const author = bookAuthorInput.value.trim();
addBookBtn.disabled = !title || !author || !selectedEpubPath;
addBookBtnLabel.innerText = `Destination Path
${title} - ${author}`;
}
// Add input event listeners to update button state
bookTitleInput.addEventListener('input', updateAddButtonState);
bookAuthorInput.addEventListener('input', updateAddButtonState);
// Initialize the application when the page loads
document.addEventListener('DOMContentLoaded', init);