Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
4781 lines (4207 loc) · 196 KB
/
Copy pathapp.js
File metadata and controls
4781 lines (4207 loc) · 196 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.
if (typeof window.IS_DEV === 'undefined') {
window.IS_DEV = typeof window !== 'undefined' && ['localhost', '127.0.0.1', '::1'].includes(window.location.hostname);
}
const IS_DEV = window.IS_DEV;
const moodAnalysisCache = new Map();
const APP_ROUTE = window.location.pathname.endsWith('/app.html') ? 'app.html' : 'app.html';
// ── No-results empty state helpers ──
function showNoResults() {
const el = document.getElementById('no-results-state');
if (el) el.style.display = 'flex';
}
function hideNoResults() {
const el = document.getElementById('no-results-state');
if (el) el.style.display = 'none';
}
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
/**
* Centralized Publish-Subscribe State Store
*/
class Store {
constructor(initialState = {}) {
this.state = initialState;
this.listeners = [];
}
getState() { return this.state; }
setState(updater) {
const newState = typeof updater === 'function' ? updater(this.state) : updater;
this.state = { ...this.state, ...newState };
this.notify();
}
subscribe(listener) {
this.listeners.push(listener);
return () => { this.listeners = this.listeners.filter(l => l !== listener); };
}
notify() { this.listeners.forEach(listener => listener(this.state)); }
}
window.appStore = new Store({
user: null,
libraryBooks: { current: [], want: [], finished: [] },
currentTheme: localStorage.getItem('bibliodrift_theme') || 'light'
});
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;
}
const CollectionAPI = {
getHeaders() {
const headers = { 'Content-Type': 'application/json' };
const csrf = getCookie('csrf_access_token');
if (csrf) {
headers['X-CSRF-TOKEN'] = csrf;
}
return headers;
},
async createCollection(userId, name, description = '', isPublic = false) {
const res = await fetch(`${MOOD_API_BASE}/api/v1/collections`, {
method: 'POST',
headers: this.getHeaders(),
credentials: 'include',
body: JSON.stringify({ user_id: parseInt(userId), name, description, is_public: isPublic })
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.error || `HTTP ${res.status}`);
}
return await res.json();
},
async getCollections(userId) {
const res = await fetch(`${MOOD_API_BASE}/api/v1/collections?user_id=${userId}`, {
method: 'GET',
headers: this.getHeaders(),
credentials: 'include'
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.error || `HTTP ${res.status}`);
}
const data = await res.json();
return data.collections || [];
},
async getCollection(id) {
const res = await fetch(`${MOOD_API_BASE}/api/v1/collections/${id}`, {
method: 'GET',
headers: this.getHeaders(),
credentials: 'include'
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.error || `HTTP ${res.status}`);
}
const data = await res.json();
return data.collection;
},
async updateCollection(id, name, description, isPublic) {
const payload = {};
if (name !== undefined) payload.name = name;
if (description !== undefined) payload.description = description;
if (isPublic !== undefined) payload.is_public = isPublic;
const res = await fetch(`${MOOD_API_BASE}/api/v1/collections/${id}`, {
method: 'PUT',
headers: this.getHeaders(),
credentials: 'include',
body: JSON.stringify(payload)
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.error || `HTTP ${res.status}`);
}
return await res.json();
},
async deleteCollection(id) {
const res = await fetch(`${MOOD_API_BASE}/api/v1/collections/${id}`, {
method: 'DELETE',
headers: this.getHeaders(),
credentials: 'include'
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.error || `HTTP ${res.status}`);
}
return await res.json();
},
async addBookToCollection(collectionId, userId, bookId, title, authors = '', thumbnail = '') {
const res = await fetch(`${MOOD_API_BASE}/api/v1/collections/${collectionId}/books`, {
method: 'POST',
headers: this.getHeaders(),
credentials: 'include',
body: JSON.stringify({
user_id: parseInt(userId),
google_books_id: bookId,
title: title,
authors: Array.isArray(authors) ? authors.join(', ') : authors,
thumbnail: thumbnail
})
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.error || `HTTP ${res.status}`);
}
return await res.json();
},
async removeBookFromCollection(collectionId, bookId) {
const res = await fetch(`${MOOD_API_BASE}/api/v1/collections/${collectionId}/books/${bookId}`, {
method: 'DELETE',
headers: this.getHeaders(),
credentials: 'include'
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.error || `HTTP ${res.status}`);
}
return await res.json();
}
};
window.CollectionAPI = CollectionAPI;
// Example click handler for your custom "Save for Offline" icon
async function handleDownloadToggle(bookCard, bookData) {
const isAlreadyDownloaded = await window.db.downloadedBooks.get(bookData.id);
if (isAlreadyDownloaded) {
const success = await window.removeOfflineBook(bookData.id);
if (success) bookCard.classList.remove('is-downloaded');
} else {
const success = await window.saveBookOffline(bookData);
if (success) bookCard.classList.add('is-downloaded');
}
}
// 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');
window.appStore.setState({ user: null });
authSessionPromise = null;
}
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');
authLink.setAttribute('aria-label', 'View profile');
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();
const thinksLoggedIn = SafeStorage.get('isLoggedIn') === 'true';
if (token === 'demo-token-12345') {
return storedUser;
}
// Real logins use HttpOnly JWT cookies (see backend JWT_TOKEN_LOCATION). Optional CSRF cookie is readable by JS.
const shouldProbe = thinksLoggedIn || storedUser || getCookie('csrf_access_token');
if (!shouldProbe) {
return null;
}
try {
const headers = {
...(token ? { 'Authorization': `Bearer ${token}` } : {})
};
const csrf = getCookie('csrf_access_token');
if (csrf) {
headers['X-CSRF-TOKEN'] = csrf;
}
const response = await fetch(`${MOOD_API_BASE}/auth/verify`, {
method: 'GET',
headers,
credentials: 'include',
});
if (response.ok) {
const data = await response.json();
const verifiedUser = data.user || storedUser;
if (verifiedUser) {
SafeStorage.set('bibliodrift_user', JSON.stringify(verifiedUser));
window.appStore.setState({ user: verifiedUser });
}
SafeStorage.set('isLoggedIn', 'true');
return verifiedUser || null;
}
if (response.status === 401 || response.status === 422) {
clearStoredAuthState();
}
return null;
} catch (error) {
console.warn('Auth verification failed (network error); 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 COVER_IMAGE_NAME_OVERRIDES = {
'The Shadow of the Wind': 'The Shadow of The Wind.jpg'
};
function getCoverImagePath(title) {
if (!title) {
return '../assets/images/cover-placeholder.jpg';
}
const fileName = COVER_IMAGE_NAME_OVERRIDES[title] || String(title || '')
.trim()
.replace(/[\/\?%\*:|"<>]/g, '') + '.jpg';
return `../assets/images/${fileName}`;
}
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" }
}
}
];
const HARDCODED_CATEGORY_BOOKS = {
'dark academia': [
{
id: 'hardcoded-dark-academia-1',
volumeInfo: {
title: 'The Secret History',
authors: ['Donna Tartt'],
description: 'A haunting campus thriller that follows a group of classics students whose obsession with beauty and secrecy leads to murder and madness.',
imageLinks: { thumbnail: getCoverImagePath('The Secret History') },
categories: ['Dark Academia', 'Mystery', 'Campus']
}
},
{
id: 'hardcoded-dark-academia-2',
volumeInfo: {
title: 'If We Were Villains',
authors: ['M.L. Rio'],
description: 'A Shakespeare-obsessed troupe of actors at an elite conservatory is undone by jealousy, rivalry, and the weight of their own tragic art.',
imageLinks: { thumbnail: getCoverImagePath('If We Were Villains') },
categories: ['Dark Academia', 'Thriller', 'Psychological']
}
},
{
id: 'hardcoded-dark-academia-3',
volumeInfo: {
title: 'The Magicians',
authors: ['Lev Grossman'],
description: 'A darker coming-of-age story set at a magical college, where genius, privilege and boredom collide with dangerous consequences.',
imageLinks: { thumbnail: getCoverImagePath('The Magicians') },
categories: ['Dark Academia', 'Fantasy', 'College']
}
}
],
'mystery': [
{
id: 'hardcoded-mystery-1',
volumeInfo: {
title: 'The Girl with the Dragon Tattoo',
authors: ['Stieg Larsson'],
description: 'A dark, atmospheric thriller about family secrets, corruption, and an unlikely detective duo in Sweden.',
imageLinks: { thumbnail: getCoverImagePath('The Girl with the Dragon Tattoo') },
categories: ['Mystery', 'Thriller']
}
},
{
id: 'hardcoded-mystery-2',
volumeInfo: {
title: 'The Woman in White',
authors: ['Wilkie Collins'],
description: 'A Victorian classic of suspense, mistaken identity, and eerie conspiracies that helped invent the modern mystery novel.',
imageLinks: { thumbnail: getCoverImagePath('The Woman in White') },
categories: ['Mystery', 'Classic']
}
},
{
id: 'hardcoded-mystery-3',
volumeInfo: {
title: 'The Hound of the Baskervilles',
authors: ['Arthur Conan Doyle'],
description: 'Sherlock Holmes and Dr. Watson investigate a supernatural legend on the foggy moors of England.',
imageLinks: { thumbnail: getCoverImagePath('The Hound of the Baskervilles') },
categories: ['Mystery', 'Detective']
}
}
],
'india': [
{
id: 'hardcoded-indian-1',
volumeInfo: {
title: "Midnight's Children",
authors: ['Salman Rushdie'],
description: "A magical realist saga that follows children born at the moment of India's independence and the country's turbulent early years.",
imageLinks: { thumbnail: getCoverImagePath("Midnight's Children") },
categories: ['Literary Fiction', 'India']
}
},
{
id: 'hardcoded-indian-2',
volumeInfo: {
title: 'The God of Small Things',
authors: ['Arundhati Roy'],
description: 'A rich, lyrical novel about forbidden love and family secrets in Kerala.',
imageLinks: { thumbnail: getCoverImagePath('The God of Small Things') },
categories: ['Literary Fiction', 'India']
}
},
{
id: 'hardcoded-indian-3',
volumeInfo: {
title: 'The White Tiger',
authors: ['Aravind Adiga'],
description: 'A darkly comic social thriller following a man who rises out of poverty to become a successful entrepreneur.',
imageLinks: { thumbnail: getCoverImagePath('The White Tiger') },
categories: ['Literary Fiction', 'India']
}
}
],
'classic fiction': [
{
id: 'hardcoded-classic-1',
volumeInfo: {
title: 'To Kill a Mockingbird',
authors: ['Harper Lee'],
description: 'A powerful story of justice and childhood in the American South, told through the eyes of Scout Finch.',
imageLinks: { thumbnail: getCoverImagePath('To Kill a Mockingbird') },
categories: ['Classic', 'Fiction']
}
},
{
id: 'hardcoded-classic-2',
volumeInfo: {
title: 'Jane Eyre',
authors: ['Charlotte Brontë'],
description: 'A gothic romance about resilience, love, and a heroine who refuses to be defined by society.',
imageLinks: { thumbnail: getCoverImagePath('Jane Eyre') },
categories: ['Classic', 'Romance']
}
},
{
id: 'hardcoded-classic-3',
volumeInfo: {
title: 'Brave New World',
authors: ['Aldous Huxley'],
description: 'A dystopian classic examining technology, conformity, and the loss of individuality.',
imageLinks: { thumbnail: getCoverImagePath('Brave New World') },
categories: ['Classic', 'Dystopian']
}
}
],
'fiction': [
{
id: 'hardcoded-fiction-1',
volumeInfo: {
title: 'The Night Circus',
authors: ['Erin Morgenstern'],
description: 'A magical competition between two illusionists becomes a love story set in a mysterious traveling circus.',
imageLinks: { thumbnail: getCoverImagePath('The Night Circus') },
categories: ['Fantasy', 'Fiction']
}
},
{
id: 'hardcoded-fiction-2',
volumeInfo: {
title: 'The Shadow of the Wind',
authors: ['Carlos Ruiz Zafón'],
description: 'A young boy uncovers a mysterious book and enters a labyrinth of secrets in post-war Barcelona.',
imageLinks: { thumbnail: getCoverImagePath('The Shadow of the Wind') },
categories: ['Mystery', 'Fiction']
}
},
{
id: 'hardcoded-fiction-3',
volumeInfo: {
title: 'Never Let Me Go',
authors: ['Kazuo Ishiguro'],
description: 'A haunting tale of love and memory at an English boarding school with a dark, speculative undercurrent.',
imageLinks: { thumbnail: getCoverImagePath('Never Let Me Go') },
categories: ['Fiction', 'Speculative']
}
}
]
};
function getHardcodedBooksByTheme(query, maxResults = 5) {
const normalized = String(query || '').toLowerCase();
for (const theme of Object.keys(HARDCODED_CATEGORY_BOOKS)) {
if (normalized.includes(theme)) {
return HARDCODED_CATEGORY_BOOKS[theme].slice(0, maxResults);
}
}
return [];
}
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 hardcoded = getHardcodedBooksByTheme(query, maxResults);
if (hardcoded.length > 0) {
return hardcoded;
}
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
? volumeInfo.imageLinks.thumbnail
: getCoverImagePath(title);
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 encodedThumb = thumb ? encodeURI(thumb).replace(/'/g, '%27') : 'https://via.placeholder.com/128x196?text=No+Cover';
const spineColors = ['#5D4037', '#4E342E', '#3E2723', '#2C2420', '#8D6E63'];
const randomSpine = spineColors[Math.floor(Math.random() * spineColors.length)];
const cleanId = title.toLowerCase().trim().replace(/[^a-z0-9]/g, '_');
const spineImagePath = `assets/images/${cleanId}_spine.jpg`;
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(encodedThumb.replace('http:', 'https:'));
scene.innerHTML = `
<div class="book" data-id="${escapeHTML(id)}">
<div class="book__face book__face--front">
<img src="${safeThumb}" alt="Cover of '${safeTitle}' by ${safeAuthors || 'Unknown Author'}">
</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: #2c2420;">${safeTitle}</div>
<div class="handwritten-note" style="margin-bottom: 0.8rem; font-style: italic; color: #5d4037;">${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>
<button class="read-details-btn" title="Read Details">
<i class="fa-solid fa-circle-info"></i> Read Details
</button>
${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 share-btn" title="Share Book"><i class="fa-solid fa-share-nodes"></i></button>
<button class="btn-icon mood-btn" title="Explore Mood"><i class="fa-solid fa-wand-magic-sparkles"></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="book-pages-3d"></div>
<div class="glass-overlay">
<strong>${safeTitle}</strong><br><small>${safeAuthors}</small>
</div>
`;
// 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')) {
if (bookEl) {
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();
});
const frontImage = scene.querySelector('.book__face--front img');
if (frontImage) {
frontImage.onerror = () => {
const fallback = encodedThumb.startsWith('../assets/images/')
? 'https://via.placeholder.com/128x196?text=No+Cover'
: getCoverImagePath(title);
if (frontImage.src !== fallback) {
frontImage.src = fallback;
} else {
frontImage.onerror = null;
}
};
}
// Info Button
scene.querySelector('.read-details-btn').addEventListener('click', (e) => {