Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2657 lines (2328 loc) · 102 KB
/
Copy pathapp.js
File metadata and controls
2657 lines (2328 loc) · 102 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ==============================================================================
* BiblioDrift Core Logic - Main Application Entry Point
* ==============================================================================
*
* Overview:
* ---------
* This file serves as the primary orchestrator for the BiblioDrift application.
* It ties together the DOM manipulation, state management, 3D rendering interactions,
* and API communications (both Google Books API and our custom Python backend).
*
* Key Components:
* ---------------
* 1. SafeStorage:
* A robust wrapper around `localStorage` with an `IndexedDB` fallback mechanism.
* This component is critical for offline-first capabilities and prevents the
* entire app from crashing when iOS/Safari or restrictive browser quotas prevent
* standard `localStorage` operations.
* - Automatically handles QuotaExceeded exceptions.
* - Provides asynchronous data restoration algorithms.
* - Integrates closely with the LibraryManager to store thousands of books safely.
*
* 2. LibraryManager:
* The central state machine over the user's book collection.
* - Shelf Types: Manages three distinctive shelves: 'want', 'current', 'finished'.
* - Concurrency Control: Handles race conditions when syncing local states with
* the backend utilizing optimistic locking techniques.
* - Merging Strategy: In the event of a conflict between the client data and
* server data, it attempts a non-destructive merge, retaining the state with
* the highest integer version map.
*
* 3. BookRenderer:
* An interface bridge to the DOM. Handles instantiation of HTML templates for
* individual 3D book instances, binding their unique event listeners, and
* applying their generated CSS styles and thematic properties.
* It integrates directly with `LibraryManager` to reflect real-time progress updates.
*
* 4. ThemeManager:
* Observes User Preferences and seamlessly toggles the UI's color palette between
* predefined themes (e.g., dark mode and light mode, wood mode), persisting
* these preferences to SafeStorage for a seamless experience across reloads.
*
* API Architecture Details:
* -------------------------
* - Google Books API: Facilitates the search and retrieval of rich book metadata
* including volume summaries, author info, and high-quality thumbnail images.
* - Local Proxy/Backend: Certain complex interactions such as Machine Learning
* sentiment analysis (fetchAIVibe) are offloaded to `MOOD_API_BASE` to bypass
* client-side compute limitations and securely handle secret API keys.
*
* Security & Data Integrity Considerations:
* -----------------------------------------
* - Data Sanitization: All text rendered from external APIs is strictly passed
* through the `escapeHTML` utility safely converting brackets to entities to
* prevent XSS (Cross-Site Scripting) vectors.
* - CSRF Protection: Interacts closely with the server-supplied `csrf_access_token`
* to securely validate state-mutating requests (POST, PUT, DELETE) preventing
* Cross Site Request Forgery attacks against logged-in users.
*
* Coding Standards and Development Guidelines:
* --------------------------------------------
* 1. Offline-First Philosophy: Ensure that actions (add, remove, update) are
* optimistically applied to local state before waiting for server resolution.
* 2. Safe Storage Wrapper: Always use `SafeStorage.set()` instead of native
* `localStorage.setItem()`.
* 3. Centralized Styling: For broad CSS manipulations, modify standard tokens in
* `index.css` rather than directly overriding inline styles to maintain a
* dynamic and cohesive theme strategy.
*
* File Structure:
* ---------------
* - [000-100]: Initialization and Utility Wrappers
* - [100-300]: SafeStorage Implementation
* - [300-800]: BookRenderer Class and 3D interactions
* - [800-1300]: LibraryManager state machine and synchronization
* - [1300+]: UI Controllers, Events, and Application Bootstrap
* ==============================================================================
*/
// API_BASE and MOOD_API_BASE are declared globally in config.js (loaded first).
// Do NOT re-declare them here — use the globals from config.js directly.
const IS_DEV = typeof window !== 'undefined' && ['localhost', '127.0.0.1'].includes(window.location.hostname);
const delay = (ms) => new Promise(res => setTimeout(res, ms));
let GOOGLE_API_KEY = '';
/**
* Utility to extract a cookie value by name.
*/
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
}
async function loadConfig() {
try {
const res = await fetch(`${MOOD_API_BASE}/config`, { credentials: 'include' });
if (res.ok) {
const data = await res.json();
GOOGLE_API_KEY = data.google_books_key || '';
if (window.GoogleBooksClient) {
window.GoogleBooksClient.setKeys([
data.google_books_key,
data.google_books_key_secondary
]);
}
if (IS_DEV) {
console.log("Config loaded");
}
}
} catch (e) {
console.warn("Failed to load backend config", e);
}
}
// Toast Notification Helper
function showToast(message, type = 'info') {
const toast = document.createElement('div');
toast.className = `toast-notification ${type}`;
toast.innerHTML = `
<i class="fa-solid ${type === 'error' ? 'fa-circle-exclamation' : 'fa-info-circle'}"></i>
<span>${message}</span>
`;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.animation = 'fadeOut 0.3s ease-in forwards';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
function clearStoredAuthState() {
SafeStorage.remove('bibliodrift_user');
SafeStorage.remove('bibliodrift_token');
SafeStorage.remove('isLoggedIn');
}
function parseStoredUser() {
const userStr = SafeStorage.get('bibliodrift_user');
if (!userStr) return null;
try {
return JSON.parse(userStr);
} catch (error) {
return null;
}
}
function renderAuthNavigation(authLink, tooltip, isAuthenticated) {
if (!authLink) return;
if (isAuthenticated) {
authLink.innerHTML = '<i class="fa-solid fa-user"></i> Profile';
authLink.href = 'profile.html';
authLink.classList.remove('active');
if (tooltip) tooltip.innerHTML = '<i class="fa-solid fa-id-card"></i> View Profile';
return;
}
authLink.textContent = 'Sign In';
authLink.href = 'auth.html';
if (tooltip) tooltip.innerHTML = '<i class="fa-solid fa-key"></i> Access account';
}
let authSessionPromise = null;
async function verifyStoredAuthSession() {
if (authSessionPromise) {
return authSessionPromise;
}
authSessionPromise = (async () => {
const token = SafeStorage.get('bibliodrift_token');
const storedUser = parseStoredUser();
if (!token) {
if (storedUser || SafeStorage.get('isLoggedIn') === 'true') {
clearStoredAuthState();
}
return null;
}
if (token === 'demo-token-12345') {
return storedUser;
}
try {
const response = await fetch(`${MOOD_API_BASE}/auth/verify`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
if (response.status === 401 || response.status === 422) {
clearStoredAuthState();
}
return null;
}
const data = await response.json();
const verifiedUser = data.user || storedUser;
if (verifiedUser) {
SafeStorage.set('bibliodrift_user', JSON.stringify(verifiedUser));
}
SafeStorage.set('isLoggedIn', 'true');
return verifiedUser;
} catch (error) {
console.warn('Auth verification failed; using cached session state if available.', error);
return storedUser;
}
})();
return authSessionPromise;
}
window.verifyStoredAuthSession = verifyStoredAuthSession;
window.renderAuthNavigation = renderAuthNavigation;
/**
* Robust Wrapper for Storage (LocalStorage + IndexedDB Fallback)
* Prevents application data loss and handles browser storage wipes/quotas.
*/
const SafeStorage = {
_dbName: 'BiblioDriftDB',
_storeName: 'library_backup',
/**
* Attempts to request persistent storage from the browser.
* This prevents the browser from clearing storage when disk space is low.
*/
async requestPersistence() {
if (navigator.storage && navigator.storage.persist) {
try {
const isPersisted = await navigator.storage.persist();
if (IS_DEV) {
console.log(`[Storage] Persistent status: ${isPersisted}`);
}
} catch (e) {
console.warn("[Storage] Persist request failed", e);
}
}
},
/**
* Internal: Opens the IndexedDB for backup.
*/
async _openDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this._dbName, 1);
request.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(this._storeName)) {
db.createObjectStore(this._storeName);
}
};
request.onsuccess = (e) => resolve(e.target.result);
request.onerror = (e) => reject(e.target.error);
});
},
/**
* Attempts to save data to localStorage with IndexedDB backup.
* @param {string} key
* @param {string} value
* @returns {boolean} Success status
*/
set(key, value) {
// 1. Primary: LocalStorage
try {
localStorage.setItem(key, value);
} catch (error) {
const isQuotaError =
error instanceof DOMException && (
error.code === 22 ||
error.code === 1014 ||
error.name === 'QuotaExceededError' ||
error.name === 'NS_ERROR_DOM_QUOTA_REACHED');
if (isQuotaError) {
showToast("Local storage full! Saving to secure backup.", "info");
} else {
console.error("LocalStorage Error:", error);
}
}
// 2. Secondary: IndexedDB (Durable Backup for Library)
if (key === 'bibliodrift_library') {
this._saveToDB(key, value);
}
return true;
},
async _saveToDB(key, value) {
try {
const db = await this._openDB();
const transaction = db.transaction(this._storeName, 'readwrite');
const store = transaction.objectStore(this._storeName);
store.put(value, key);
} catch (e) {
console.error("IndexedDB Backup Failed", e);
}
showToast("Local storage full! Please sync to cloud and clear cache.", "error");
return false;
},
/**
* Safely retrieves data from localStorage.
*/
get(key) {
try {
const value = localStorage.getItem(key);
return value;
} catch (e) {
return null;
}
},
/**
* Retrieves data with IndexedDB fallback if LocalStorage is wiped.
*/
async getAsync(key) {
let val = this.get(key);
if (!val && key === 'bibliodrift_library') {
try {
const db = await this._openDB();
const transaction = db.transaction(this._storeName, 'readonly');
const store = transaction.objectStore(this._storeName);
val = await new Promise((resolve) => {
const request = store.get(key);
request.onsuccess = () => resolve(request.result);
request.onerror = () => resolve(null);
});
if (val) {
if (IS_DEV) console.log("[Storage] Restored from IndexedDB backup");
// Try to restore to LocalStorage for future sync calls
try { localStorage.setItem(key, val); } catch (e) { }
}
} catch (e) {
console.warn("Backup retrieval failed", e);
}
}
return val;
},
/**
* Safely removes data from storage.
* @param {string} key
*/
remove(key) {
try {
localStorage.removeItem(key);
if (key === 'bibliodrift_library') {
this._saveToDB(key, null);
}
return true;
} catch (e) {
return false;
}
},
/**
* Safely clears all localStorage.
*/
clear() {
try {
localStorage.clear();
this.setMeta({});
return true;
} catch (e) {
return false;
}
}
};
const MOCK_BOOKS = [
{
id: "mock-dune",
volumeInfo: {
title: "Dune",
authors: ["Frank Herbert"],
description: "A sweeping science fiction epic set on the desert planet Arrakis. Dune explores complex themes of politics, religion, and man's relationship with nature. Paul Atreides must navigate a treacherous path to becoming the mysterious Muad'Dib.",
imageLinks: { thumbnail: "../assets/images/dune.jpg" }
}
},
{
id: "mock-1984",
volumeInfo: {
title: "1984",
authors: ["George Orwell"],
description: "Orwell's chilling prophecy of a totalitarian future where Big Brother is always watching. A profound exploration of surveillance, truth, and the resilience of the human spirit.",
imageLinks: { thumbnail: "../assets/images/1984.jpg" }
}
},
{
id: "mock-hobbit",
volumeInfo: {
title: "The Hobbit",
authors: ["J.R.R. Tolkien"],
description: "In a hole in the ground there lived a hobbit. Join Bilbo Baggins on an unexpected journey across Middle-earth, encountering dragons, dwarves, and a rigorous test of courage.",
imageLinks: { thumbnail: "../assets/images/hobbit.jpg" }
}
},
{
id: "mock-pride",
volumeInfo: {
title: "Pride and Prejudice",
authors: ["Jane Austen"],
description: "A timeless romance of manners and misunderstanding. Elizabeth Bennet's wit matches Mr. Darcy's pride in this sharp social commentary that remains one of the most loved novels in English literature.",
imageLinks: { thumbnail: "../assets/images/pride.jpg" }
}
},
{
id: "mock-gatsby",
volumeInfo: {
title: "The Great Gatsby",
authors: ["F. Scott Fitzgerald"],
description: "The quintessential novel of the Jazz Age. Jay Gatsby's obsessive love for Daisy Buchanan drives a tragic tale of wealth, illusion, and the American Dream.",
imageLinks: { thumbnail: "../assets/images/gatsby.jpg" }
}
},
{
id: "mock-sapiens",
volumeInfo: {
title: "Sapiens",
authors: ["Yuval Noah Harari"],
description: "A groundbreaking narrative of humanity's creation and evolution. Harari explores the ways in which biology and history have defined us and enhanced our understanding of what it means to be 'human'.",
imageLinks: { thumbnail: "../assets/images/sapiens.jpg" }
}
},
{
id: "mock-hail-mary",
volumeInfo: {
title: "Project Hail Mary",
authors: ["Andy Weir"],
description: "A lone astronaut must save the earth from disaster in this gripping tale of survival and scientific discovery. Full of humor and hard science, it is a celebration of human ingenuity.",
imageLinks: { thumbnail: "../assets/images/hail_mary.jpg" }
}
}
];
function normalizeQueryTerms(query) {
return String(query || '')
.toLowerCase()
.replace(/[^a-z0-9\s]/g, ' ')
.split(/\s+/)
.filter(Boolean);
}
function scoreMockBook(book, queryTerms) {
const volumeInfo = book.volumeInfo || {};
const haystack = [
volumeInfo.title || '',
(volumeInfo.authors || []).join(' '),
volumeInfo.description || '',
(volumeInfo.categories || []).join(' ')
].join(' ').toLowerCase();
return queryTerms.reduce((score, term) => score + (haystack.includes(term) ? 1 : 0), 0);
}
function getFallbackBooks(query, maxResults = 5) {
const queryTerms = normalizeQueryTerms(query);
const ranked = MOCK_BOOKS
.map(book => ({ book, score: scoreMockBook(book, queryTerms) }))
.sort((a, b) => b.score - a.score);
const matches = ranked.filter(item => item.score > 0).map(item => item.book);
const pool = matches.length > 0 ? matches : MOCK_BOOKS;
return pool.slice(0, maxResults);
}
class BookRenderer {
constructor(libraryManager = null) {
this.libraryManager = libraryManager;
}
renderSkeletons(container, count = 5, type = 'card') {
if (!container) return;
let html = '';
if (type === 'card') {
html = Array(count).fill(0).map(() => `
<div class="book-skeleton skeleton"></div>
`).join('');
} else if (type === 'spine') {
html = Array(count).fill(0).map(() => `
<div class="spine-skeleton skeleton"></div>
`).join('');
}
container.innerHTML = html;
}
async createBookElement(bookData, shelf = null) {
const { id, volumeInfo } = bookData;
const progress = typeof bookData.progress === 'number' ? bookData.progress : 0;
const title = volumeInfo.title || "Untitled";
const authors = volumeInfo.authors ? volumeInfo.authors.join(", ") : "Unknown Author";
const thumb = volumeInfo.imageLinks ? volumeInfo.imageLinks.thumbnail : 'https://via.placeholder.com/128x196?text=No+Cover';
const originalDescription = volumeInfo.description ? volumeInfo.description.substring(0, 100) + "..." : "A mysterious tome waiting to be opened.";
const categories = volumeInfo.categories || [];
const vibe = this.generateVibe(originalDescription, categories);
const spineColors = ['#5D4037', '#4E342E', '#3E2723', '#2C2420', '#8D6E63'];
const randomSpine = spineColors[Math.floor(Math.random() * spineColors.length)];
const scene = document.createElement('div');
scene.className = 'book-scene';
// Load flip sound
const flipSound = new Audio('../assets/sounds/page-flip.mp3');
flipSound.preload = 'auto';
flipSound.volume = 0.5;
const escapeHTML = (str) => {
if (!str) return "";
return String(str)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
const safeTitle = escapeHTML(title);
const safeAuthors = escapeHTML(authors);
const safeOriginalDescription = escapeHTML(originalDescription);
const safeVibe = escapeHTML(vibe);
const safeThumb = escapeHTML(thumb.replace('http:', 'https:'));
scene.innerHTML = `
<div class="book" data-id="${escapeHTML(id)}">
<div class="book__face book__face--front">
<img src="${safeThumb}" alt="${safeTitle}">
</div>
<div class="book__face book__face--spine" style="background: ${randomSpine}"></div>
<div class="book__face book__face--right"></div>
<div class="book__face book__face--top"></div>
<div class="book__face book__face--bottom"></div>
<div class="book__face book__face--back">
<div style="overflow-y: auto; height: 100%; padding-right: 5px; scrollbar-width: thin;">
<div style="font-weight: bold; font-size: 0.9rem; margin-bottom: 0.5rem; color: var(--text-main);">${safeTitle}</div>
<div class="handwritten-note" style="margin-bottom: 0.8rem; font-style: italic; color: var(--wood-dark);">${safeVibe}</div>
${bookData.moods && bookData.moods.length > 0 ? `
<div class="book-mood-tags" style="margin-bottom: 0.8rem; display: flex; flex-wrap: wrap; gap: 4px;">
${bookData.moods.map(m => `<span style="font-size: 0.6rem; background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 10px;"><i class="fa-solid ${this.getMoodIcon(m)}"></i> ${m}</span>`).join('')}
</div>
` : ''}
<div class="book-blurb" data-book-id="${escapeHTML(id)}" style="font-size: 0.8rem; line-height: 1.4; color: var(--text-muted); text-align: justify; min-height: 60px;">${safeOriginalDescription}</div>
</div>
${shelf === 'current' ? `
<div class="reading-progress">
<input type="range" min="0" max="100" value="${progress}" class="progress-slider" />
<small>${progress}% read</small>
</div>` : ''}
<div class="book-actions">
<button class="btn-icon add-btn" title="Add to Library"><i class="fa-regular fa-heart"></i></button>
<button class="btn-icon info-btn" title="Read Details"><i class="fa-solid fa-info"></i></button>
<button class="btn-icon share-btn" title="Share Book"><i class="fa-solid fa-share-nodes"></i></button>
<button class="btn-icon flip-back-btn" title="Flip Back"><i class="fa-solid fa-rotate-left"></i></button>
</div>
</div>
</div>
<div class="glass-overlay">
<strong>${safeTitle}</strong><br><small>${safeAuthors}</small>
</div>
`;
// Fetch AI-generated blurb asynchronously
const blurbElement = scene.querySelector('.book-blurb');
if (blurbElement) {
this.fetchAIBlurb(id, title, authors, volumeInfo.description || "", categories)
.then(aiBlurb => {
if (aiBlurb && blurbElement) {
blurbElement.textContent = aiBlurb;
}
})
.catch(err => {
// Silently keep fallback description
});
}
// Interaction: Progress Slider
const slider = scene.querySelector('.progress-slider');
if (slider) {
slider.addEventListener('change', (e) => {
const newProgress = parseInt(e.target.value);
if (this.libraryManager) {
this.libraryManager.updateBook(id, { progress: newProgress });
}
// Update small tag
const small = slider.nextElementSibling;
if (small) small.textContent = `${newProgress}% read`;
});
}
// Interaction: Flip
const bookEl = scene.querySelector('.book');
scene.addEventListener('click', (e) => {
if (!e.target.closest('.btn-icon') && !e.target.closest('.reading-progress')) {
bookEl.classList.toggle('flipped');
// Play sound
flipSound.play().catch(e => {
if (IS_DEV) {
console.log("Audio play failed", e);
}
});
}
});
// Interaction: Add to Library Logic
const addBtn = scene.querySelector('.add-btn');
const updateBtn = () => {
addBtn.innerHTML = this.libraryManager.findBook(id) ? '<i class="fa-solid fa-check"></i>' : '<i class="fa-regular fa-heart"></i>';
};
updateBtn();
addBtn.addEventListener('click', (e) => {
e.stopPropagation();
if (this.libraryManager.findBook(id)) {
this.libraryManager.removeBook(id);
} else {
this.libraryManager.addBook(bookData, shelf || 'want');
}
updateBtn();
});
// Info Button
scene.querySelector('.info-btn').addEventListener('click', (e) => {
e.stopPropagation();
this.openModal(bookData);
});
// Share Button
scene.querySelector('.share-btn').addEventListener('click', (e) => {
e.stopPropagation();
const shareText = `Check out this book: ${title} by ${authors}`;
navigator.clipboard.writeText(shareText).then(() => {
showToast('Book details copied to clipboard!', 'success');
}).catch(err => {
console.error('Failed to copy text: ', err);
showToast('Failed to copy book details.', 'error');
});
});
// Flip Back Button
scene.querySelector('.flip-back-btn').addEventListener('click', (e) => {
e.stopPropagation();
bookEl.classList.remove('flipped');
flipSound.play().catch(err => {
if (IS_DEV) {
console.log("Audio play failed", err);
}
});
});
// Async fetch AI Vibe - Hydrate the UI
this.fetchAIVibe(title, authors, volumeInfo.description || "").then(aiVibe => {
if (aiVibe) {
// Strip any accidental prefix the AI might return
const cleanVibe = aiVibe.replace(/^(Bookseller's Note:|Note:|Recommendation:)\s*/i, "");
const noteEl = scene.querySelector('.handwritten-note');
if (noteEl) {
noteEl.innerHTML = cleanVibe;
noteEl.classList.add('fade-in'); // Optional animation hook
}
}
});
return scene;
}
async fetchAIVibe(title, author, description) {
try {
const res = await fetch(`${MOOD_API_BASE}/generate-note`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ title, author, description })
});
if (res.ok) {
const data = await res.json();
return data.data?.vibe || null;
}
} catch (e) {
// Silently fail to use fallback
}
return null;
}
async fetchAIBlurb(bookId, title, author, description, categories = []) {
try {
const res = await fetch(`${MOOD_API_BASE}/generate-note`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ bookId, title, author, description, categories })
});
if (res.ok) {
const data = await res.json();
return data.data?.blurb || null;
}
} catch (e) {
// Silently fail to use fallback
}
return null;
}
generateVibe(text, categories = []) {
// Fallback vibes if AI hasn't loaded yet.
const lowerText = text.toLowerCase();
const lowerCats = categories.join(' ').toLowerCase();
// 1. Context-aware fallbacks
if (lowerCats.includes('classic') || lowerText.includes('classic')) return "A timeless tale that defined a genre.";
if (lowerCats.includes('romance') || lowerText.includes('love')) return "A heartwarming story of connection.";
if (lowerCats.includes('mystery') || lowerText.includes('murder') || lowerText.includes('detective')) return "Full of twists that keep you guessing.";
if (lowerCats.includes('fantasy') || lowerText.includes('magic')) return "A magical escape to another world.";
if (lowerCats.includes('fiction') || lowerText.includes('novel')) return "A compelling narrative voice.";
if (lowerCats.includes('history') || lowerText.includes('war')) return "A journey into the past.";
if (lowerCats.includes('science') || lowerText.includes('space')) return "Opens your mind to new possibilities.";
// 2. Generic fallbacks (Deterministic hash)
const vibes = [
"Perfect for a rainy afternoon.",
"A quiet companion for coffee.",
"Intense and thought-provoking.",
"Will make you laugh and cry.",
"Best devoured in one sitting.",
"Prepare to be surprised."
];
// Simple hash to pick a stable vibe for this book text
let hash = 0;
for (let i = 0; i < text.length; i++) {
hash = ((hash << 5) - hash) + text.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return vibes[Math.abs(hash) % vibes.length];
}
openModal(book) {
const modal = document.getElementById('book-details-modal');
if (!modal) return;
document.getElementById('modal-img').src = book.volumeInfo.imageLinks?.thumbnail.replace('http:', 'https:') || '';
document.getElementById('modal-title').textContent = book.volumeInfo.title;
document.getElementById('modal-author').textContent = book.volumeInfo.authors?.join(", ") || "Unknown Author";
const summaryEl = document.getElementById('modal-summary');
if (summaryEl) {
// Show skeletons while AI is "thinking"
summaryEl.innerHTML = `
<div class="text-skeleton skeleton"></div>
<div class="text-skeleton skeleton" style="width: 90%"></div>
`;
// Fetch the AI vibe to populate the Insight box
this.fetchAIVibe(book.volumeInfo.title, book.volumeInfo.authors?.join(", ") || "", book.volumeInfo.description || "").then(vibe => {
if (vibe) {
const cleanVibe = vibe.replace(/^(Bookseller's Note:|Note:|Recommendation:)\s*/i, "");
summaryEl.innerHTML = `<p class="fade-in">${cleanVibe}</p>`;
} else {
// Fallback to description if AI vibe fails
summaryEl.textContent = book.volumeInfo.description || "No description available.";
}
});
}
const addBtn = document.getElementById('modal-add-btn');
const shareBtn = document.getElementById('modal-share-btn');
const isInLibrary = this.libraryManager && typeof this.libraryManager.findBook === 'function' && this.libraryManager.findBook(book.id);
if (addBtn) {
addBtn.onclick = null;
addBtn.classList.toggle('library-remove-btn', isInLibrary);
addBtn.innerHTML = isInLibrary
? '<i class="fa-solid fa-trash"></i> Remove from Library'
: '<i class="fa-regular fa-heart"></i> Add to Library';
addBtn.onclick = async () => {
if (!this.libraryManager) return;
if (isInLibrary) {
if (confirm('Are you sure you want to remove this book from your library?')) {
await this.libraryManager.removeBook(book.id);
modal.close();
}
return;
}
await this.libraryManager.addBook(book, 'want');
addBtn.innerHTML = '<i class="fa-solid fa-trash"></i> Remove from Library';
addBtn.classList.add('library-remove-btn');
};
}
if (shareBtn) {
shareBtn.onclick = () => {
const shareText = `Check out this book: ${book.volumeInfo.title} by ${book.volumeInfo.authors?.join(", ") || "Unknown Author"}`;
navigator.clipboard.writeText(shareText).then(() => {
showToast('Book title and author copied!', 'success');
}).catch(err => {
console.error('Failed to copy text: ', err);
showToast('Failed to copy book details.', 'error');
});
};
}
// Preview Button — opens the Google Books Embedded Viewer
const previewBtn = document.getElementById('modal-preview-btn');
if (previewBtn) {
previewBtn.onclick = () => {
if (window.BookPreview && book.id) {
window.BookPreview.open(book.id, book.volumeInfo.title || 'Book Preview');
}
};
}
modal.showModal();
document.getElementById('closeModalBtn').onclick = () => modal.close();
// Emotion Tagging UI
const emotionContainer = document.createElement('div');
emotionContainer.className = 'emotion-tagging-section';
emotionContainer.innerHTML = `
<h3 class="modal-section-title">How does this book make you feel?</h3>
<div class="emotion-tags-container">
${['Melancholic', 'Cozy', 'Tense', 'Inspiring', 'Whimsical', 'Dark', 'Adventurous'].map(mood => {
const isActive = book.moods && book.moods.includes(mood);
return `<span class="emotion-tag ${isActive ? 'active' : ''}" data-mood="${mood}">
<i class="fa-solid ${this.getMoodIcon(mood)}"></i> ${mood}
</span>`;
}).join('')}
</div>
`;
// Insert before the buttons
const modalBody = modal.querySelector('.modal-body') || modal.querySelector('.book-details-content');
const actions = modal.querySelector('.modal-actions') || modal.querySelector('.book-actions-section');
if (actions) {
// Remove existing tagging section if re-opening
const existing = actions.parentNode.querySelector('.emotion-tagging-section');
if (existing) existing.remove();
actions.parentNode.insertBefore(emotionContainer, actions);
} else if (modalBody) {
// Fallback
const existing = modalBody.querySelector('.emotion-tagging-section');
if (existing) existing.remove();
modalBody.appendChild(emotionContainer);
}
// Add tag toggle listeners
emotionContainer.querySelectorAll('.emotion-tag').forEach(tag => {
tag.onclick = async () => {
const mood = tag.dataset.mood;
if (!book.moods) book.moods = [];
const index = book.moods.indexOf(mood);
if (index > -1) {
book.moods.splice(index, 1);
tag.classList.remove('active');
} else {
book.moods.push(mood);
tag.classList.add('active');
}
if (this.libraryManager) {
await this.libraryManager.updateBook(book.id, { moods: book.moods });
}
};
});
}
getMoodIcon(mood) {
const icons = {
'Melancholic': 'fa-cloud-showers-heavy',
'Cozy': 'fa-mug-hot',
'Tense': 'fa-bolt',
'Inspiring': 'fa-lightbulb',
'Whimsical': 'fa-wand-magic-sparkles',
'Dark': 'fa-moon',
'Adventurous': 'fa-compass'
};
return icons[mood] || 'fa-tag';
}
async renderCuratedSection(query, elementId, maxResults = 5) {
const container = document.getElementById(elementId);
if (!container) return;
// Show skeletons while loading
this.renderSkeletons(container, maxResults);
try {
const client = window.GoogleBooksClient;
const data = client
? await client.fetchVolumes(query, { maxResults, extraParams: '&printType=books' })
: await (async () => {
const keyParam = GOOGLE_API_KEY ? `&key=${GOOGLE_API_KEY}` : '';
const encodedQuery = encodeURIComponent(query);
const res = await fetch(`${API_BASE}?q=${encodedQuery}&maxResults=${maxResults}&printType=books${keyParam}`);
if (!res.ok) {
throw new Error(`API Error: ${res.statusText}`);
}
return await res.json();
})();
if (data.items && data.items.length > 0) {
await this.renderBookCards(container, data.items.slice(0, maxResults));
} else {
const fallbackBooks = getFallbackBooks(query, maxResults);
if (fallbackBooks.length > 0) {
await this.renderBookCards(container, fallbackBooks);
} else {
container.innerHTML = `
<div class="empty-state">
<i class="fa-solid fa-box-open"></i>
<p>No books found. The shelves are empty.</p>
</div>`;
}
}
} catch (err) {
console.error("Failed to fetch books", err);
const fallbackBooks = getFallbackBooks(query, maxResults);
if (fallbackBooks.length > 0) {
await this.renderBookCards(container, fallbackBooks);
return;
}
showToast("Failed to load bookshelf.", "error");
container.innerHTML = `
<div class="empty-state">
<i class="fa-solid fa-triangle-exclamation"></i>
<p>Bookshelf Empty (API connection failed)</p>
</div>`;
}
}
async renderMoodCategorySection(categoryConfig, elementId, maxResults = 5) {
const container = document.getElementById(elementId);
if (!container) return;
this.renderSkeletons(container, maxResults);
try {
const res = await fetch(`${MOOD_API_BASE}/category-books`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
category: categoryConfig.category,
vibe_description: categoryConfig.vibeDescription,
count: maxResults
})
});
if (!res.ok) {
throw new Error(`Category API Error: ${res.status}`);
}
const payload = await res.json();
const categoryBooks = payload?.data?.books || [];
if (categoryBooks.length === 0) {
throw new Error(`No books returned for category: ${categoryConfig.category}`);
}
const resolvedBooks = await this.resolveCategoryBooks(categoryBooks);
if (resolvedBooks.length > 0) {
await this.renderBookCards(container, resolvedBooks.slice(0, maxResults));
return;
}
throw new Error(`Could not resolve Google Books matches for category: ${categoryConfig.category}`);
} catch (err) {
console.error(`Failed to load category shelf "${categoryConfig.category}"`, err);
await this.renderCuratedSection(categoryConfig.fallbackQuery, elementId, maxResults);
}
}
async resolveCategoryBooks(categoryBooks) {
const resolvedBooks = [];
for (const item of categoryBooks) {
const title = String(item?.title || '').trim();
const author = String(item?.author || '').trim();
if (!title) continue;
const searchQuery = author
? `intitle:${title} inauthor:${author}`