-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1094 lines (973 loc) · 28.9 KB
/
app.js
File metadata and controls
1094 lines (973 loc) · 28.9 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
/*
Readr v1.9.0
*/
import * as Books from "./features/books.js";
import * as Sessions from "./features/sessions.js";
import { attachSearchUI } from "./features/search-ui.js";
import { initSettings } from "./features/settings.js";
import { smartSearch, tokenize, highlightText } from "./utils/search.js";
import {
wireImportExport,
wireSessionsImportExport,
} from "./ui/wire-import-export.js";
import { normalizeStatus } from "./utils/constants.js";
import { initTooltip, initBackupTooltip } from "./features/tooltip.js";
import {
initProfile,
renderProfileUI,
updateBookGoalsUI,
} from "./features/profile.js";
import * as Analytics from "./features/analytics.js";
import { initCharts, renderCharts } from "./features/charts.js";
import { initSnapshot, renderSnapshotCard } from "./features/snapshot.js";
import * as Badges from "./features/badges.js";
const searchUI = attachSearchUI({
render: () => Books.render(),
getBooks: () => books,
});
// After imports or any mutation to the book set:
// SearchUI.refresh();
// Make available for modules that want to announce status
window.searchUI = searchUI;
async function init() {
// Load core state (books, logs, profile, etc.)
loadBooks();
loadLogs();
loadProfile();
// normalize legacy statuses before first render
migrateStatusesToReading(books, saveBooks);
// Analytics: central stats for charts/profile/sessions
Analytics.initAnalytics();
Analytics.loadAnalyticsData({ books, sessions: logs });
// Badges: light gamification layer on top of analytics
Badges.initBadges({
adapters: {
getTotals: Analytics.getTotals,
getStreaks: Analytics.getStreaks,
getPerBookStats: Analytics.getPerBookStats,
getBooks: () => books,
getLogs: () => logs,
getDailyGoal: () => profile.dailyGoal || null,
dayKey,
showToast,
},
});
buildBookOptions(); // to populate the log form
// Hand Books everything it needs (data + helpers) in a narrow adapter
const adapters = {
get books() {
return books;
},
saveBooks,
buildBookOptions,
buildFilterOptions,
updateBookGoalsUI,
withUndo,
smartSearch,
tokenize,
highlightText,
Analytics,
};
await Books.init({ adapters, ui: searchUI });
Sessions.init({
adapters: {
get logs() {
return logs;
},
saveLogs,
getBookTitleById,
dayKey,
withUndo,
showToast,
renderProfileUI, // so sessions can update the goals widget
renderBooks: Books.render,
getGoalType,
getGoalValue,
Analytics,
getShortcutsEnabled,
},
});
initSettings({
adapters: {
wireImportExport,
wireSessionsImportExport,
showToast,
checkForUpdatesNow,
renderBooks: Books.render,
// Import handler should reload state and refresh UI:
onImport: () => {
loadBooks();
loadLogs();
loadProfile();
buildBookOptions();
// Analytics + charts refresh
Analytics.initAnalytics();
Analytics.loadAnalyticsData({ books, sessions: logs });
renderCharts();
// Books owns filters; rendering will show new data
renderProfileUI();
Books.render();
Sessions.render();
},
// Reset profile & data live here so Settings stays decoupled
resetProfile: () => {
localStorage.removeItem(PROFILE_KEY);
localStorage.removeItem("themeMode");
profile = {
id: "me",
dailyGoal: null,
bookGoals: { monthly: 0, yearly: 0 },
};
themeMode = "system";
applyAppearance(themeMode);
saveProfile();
renderProfileUI();
showToast("Profile reset.", "success");
},
resetData: () => {
localStorage.removeItem(BOOKS_KEY);
localStorage.removeItem(LOGS_KEY);
books = [];
logs = [];
saveBooks();
saveLogs();
buildBookOptions();
Books.render();
renderProfileUI();
Sessions.render();
},
getShortcutsEnabled,
toggleShortcuts: (enabled) => setShortcutsEnabled(enabled),
},
});
initProfile({
adapters: {
get books() {
return books;
},
get logs() {
return logs;
},
get profile() {
return profile;
},
dayKey,
Analytics,
getBadgeCatalog: Badges.getBadgeCatalog,
getUnlockedBadges: Badges.getUnlockedBadges,
},
});
initCharts({
adapters: {
getTotals: Analytics.getTotals,
getPerBookStats: Analytics.getPerBookStats,
getPerDayStats: Analytics.getPerDayStats,
getTrend: Analytics.getTrend,
getTrendSummary: Analytics.getTrendSummary,
getBookTitleById,
getChartTheme: () => getEffectiveMode(),
},
});
initSnapshot({
adapters: {
getBookTitleById,
getBadges: Badges.getUnlockedBadges,
getTheme: () =>
document.body.classList.contains("mode-dark") ? "dark" : "light",
showToast,
},
});
initTooltip({
adapters: { logs, getBookTitleById, dayKey },
});
initBackupTooltip();
// Goal reminders (settings + scheduler + ARIA live)
initGoalRemindersUI();
// Expose minimal hooks for a11y smoke
window.render = Books.render;
window.books = books;
window.saveBooks = saveBooks;
}
// ------------------------
// Storage Keys
// ------------------------
const BOOKS_KEY = "readinglog.v1";
const LOGS_KEY = "readinglog.logs.v1";
const PROFILE_KEY = "readinglog.profile.v1";
const GOAL_REMINDERS_KEY = "readinglog.goal-reminders.v1";
const SHORTCUTS_KEY = "readr:shortcuts:v1";
// ------------------------
// App State
// ------------------------
let books = [];
let logs = [];
let profile = {
id: "me",
dailyGoal: null,
bookGoals: { monthly: 0, yearly: 0 },
};
function getGoalType() {
// default to "pages" if no goal is set yet
return profile?.dailyGoal?.type || "pages";
}
function getGoalValue() {
// default to 0 if no goal is set yet
return profile?.dailyGoal?.value || 0;
}
// Goal reminders: "off" | "daily" | "weekly"
let goalReminderMode = localStorage.getItem(GOAL_REMINDERS_KEY) || "off";
let goalReminderTimeoutId = null;
// Keyboard shortcuts (settings-toggleable)
let shortcutsEnabled = loadShortcutsPref();
// Keep the mini help line under the log form in sync with the setting
function syncShortcutsHint() {
const hint = document.getElementById("shortcuts-hint");
if (!hint) return;
if (shortcutsEnabled) {
hint.hidden = false;
// Re-set the text each time so aria-live will announce the change
hint.innerHTML =
"Shortcuts on: Press <kbd>N</kbd> to add a session, <kbd>H</kbd> to jump to Session History search, use <kbd>\u2191</kbd>/<kbd>\u2193</kbd> to move between rows, <kbd>Enter</kbd> to edit, and <kbd>Esc</kbd> to return to search.";
} else {
hint.hidden = true;
}
}
// Initial sync once DOM + state are ready
syncShortcutsHint();
// -----------------------
// Theme (light/dark/system with live OS sync)
// -----------------------
const body = document.body;
const media =
window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)");
if (media && !media.addEventListener && media.addListener) {
media.addListener(() => {
if (themeMode === "system") {
applyAppearance("system");
}
});
}
let themeMode = localStorage.getItem("themeMode") || "system"; // "light" | "dark" | "system"
applyAppearance(themeMode);
// Resolve "system" to actual mode
function getEffectiveMode(mode = themeMode) {
if (mode === "system") {
return media && media.matches ? "dark" : "light";
}
return mode;
}
function applyAppearance(mode) {
const effective = getEffectiveMode(mode);
body.classList.remove("mode-light", "mode-dark");
body.classList.add(effective === "dark" ? "mode-dark" : "mode-light");
const modeBtnLocal = document.getElementById("mode-toggle");
if (modeBtnLocal) {
// Show what you'll switch to
const next = nextThemeMode(themeMode);
modeBtnLocal.textContent =
next === "light"
? "Switch to Light"
: next === "dark"
? "Switch to Dark"
: "Switch to System";
modeBtnLocal.setAttribute(
"aria-label",
`Theme: ${themeMode} (click to change)`
);
}
}
function nextThemeMode(current) {
return current === "light" ? "dark" : current === "dark" ? "system" : "light";
}
// Live update when OS theme changes and we're in "system"
if (media && media.addEventListener) {
media.addEventListener("change", () => {
if (themeMode === "system") {
applyAppearance("system");
}
});
}
const modeBtn = document.getElementById("mode-toggle");
if (modeBtn) {
modeBtn.addEventListener("click", () => {
themeMode = nextThemeMode(themeMode);
localStorage.setItem("themeMode", themeMode);
applyAppearance(themeMode);
});
}
// -----------------------
// UI Wiring
// -----------------------
const bookForm = document.getElementById("book-form");
if (bookForm) {
bookForm.addEventListener("submit", (e) => {
e.preventDefault();
const title = document.getElementById("title").value.trim();
const author = document.getElementById("author").value.trim();
const genre = document.getElementById("genre")?.value.trim() || "";
const status = document.getElementById("status").value;
const plannedMonth =
document.getElementById("plannedMonth")?.value || undefined;
if (!title || !author) {
return;
}
const now = new Date().toISOString();
books.push({
id: Date.now(),
title,
author,
genre,
status,
plannedMonth,
createdAt: now,
updatedAt: now,
...(status === "finished" ? { finishedAt: now } : {}),
});
saveBooks();
buildBookOptions(); // keep log form in sync
Books.render();
e.target.reset();
});
}
// Handle "Add Session"
const logForm = document.getElementById("log-form");
if (logForm) {
logForm.addEventListener("submit", (e) => {
e.preventDefault();
const bookId = +document.getElementById("log-book").value;
const pages = document.getElementById("log-pages").value;
const mins = document.getElementById("log-mins").value;
const notesEl = document.getElementById("log-notes");
const notes = notesEl?.value.trim() || "";
const dateEl = document.getElementById("log-date");
const date = dateEl?.value || dayKey();
if (!bookId) {
return;
}
logs.push({
id: Date.now(),
bookId,
date, // "YYYY-MM-DD"
pagesRead: pages ? +pages : undefined,
minutes: mins ? +mins : undefined,
notes: notes || undefined,
});
saveLogs();
// If pages were logged and book is "planned", bump to "reading"
const i = books.findIndex((book) => book.id === bookId);
if (i !== -1 && books[i].status === "planned") {
books[i].status = "reading";
books[i].updatedAt = new Date().toISOString();
if (!books[i].startedAt) {
books[i].startedAt = new Date().toISOString();
}
saveBooks();
}
// Reset form & refresh UI
e.target.reset();
// default date back to today
if (dateEl) {
dateEl.value = dayKey(); // keep it on local "today"
}
if (notesEl) {
notesEl.value = "";
}
renderProfileUI();
Books.render();
Sessions.render();
});
}
// -----------------------
// Keyboard Shortcuts (global)
// -----------------------
document.addEventListener("keydown", (e) => {
if (!shortcutsEnabled) return;
if (e.defaultPrevented) return;
if (e.altKey || e.ctrlKey | e.metaKey) return;
const target = e.target;
const tag = target && target.tagName;
if (
tag === "INPUT" ||
tag === "TEXTAREA" ||
tag === "SELECT" ||
target?.isContentEditable
) {
// Don't hijack typing inside fields
return;
}
// "N" → jump to Add Reading Session form
if (e.key === "n" || e.key === "N") {
const form = document.getElementById("log-form");
const bookSelect = document.getElementById("log-book");
if (!form | !bookSelect) return;
e.preventDefault();
form.scrollIntoView({ behavior: "smooth", block: "center" });
bookSelect.focus();
return;
}
// "H" → jump to Session History search
if (e.key === "h" || e.key === "H") {
const search = document.getElementById("history-search");
if (!search) return;
e.preventDefault();
const historySection = document.getElementById("session-history");
if (historySection) {
historySection.scrollIntoView({ behavior: "smooth", block: "center" });
}
search.focus();
return;
}
});
// Save goal button
const saveGoalBtn = document.getElementById("save-goal");
if (saveGoalBtn) {
saveGoalBtn.addEventListener("click", () => {
const type = document.getElementById("goal-type").value;
const input = document.getElementById("goal-value");
const raw = +input.value;
let err = document.getElementById("goal-error");
if (!err) {
err = document.createElement("div");
err.id = "goal-error";
err.className = "error-text";
err.setAttribute("role", "alert");
document.getElementById("goal-value").parentElement.appendChild(err);
}
if (!Number.isFinite(raw) || raw < 1) {
showToast("Please enter a number ≥ 1.", "error", { timeout: 4000 });
input.focus();
return;
}
err.textContent = "";
const value = Math.max(1, raw);
profile.dailyGoal = { type, value };
saveProfile();
renderProfileUI();
const unit = type === "minutes" ? "minutes" : "pages";
announceGoalUpdate(`Daily goal set to ${value} ${unit} per day.`);
});
}
const decBtn = document.getElementById("goal-dec");
const incBtn = document.getElementById("goal-inc");
if (decBtn || incBtn) {
const input = document.getElementById("goal-value");
const coerce = (value) => Math.max(1, Math.floor(Number(value) || 1));
const setGoalValue = (next) => {
if (!profile.dailyGoal) {
const typeSel = document.getElementById("goal-type");
profile.dailyGoal = {
type: typeSel?.value === "minutes" ? "minutes" : "pages",
value: 20,
};
}
profile.dailyGoal.value = coerce(next);
input.value = String(profile.dailyGoal.value);
saveProfile();
renderProfileUI();
};
decBtn?.addEventListener("click", () =>
setGoalValue((profile?.dailyGoal?.value || input.value || 1) - 1)
);
incBtn?.addEventListener("click", () =>
setGoalValue((profile?.dailyGoal?.value || input.value || 1) + 1)
);
}
const saveBookGoalsBtn = document.getElementById("save-book-goals");
if (saveBookGoalsBtn) {
saveBookGoalsBtn.addEventListener("click", () => {
const m = Math.max(
0,
+document.getElementById("goal-monthly-books").value || 0
);
const y = Math.max(
0,
+document.getElementById("goal-yearly-books").value || 0
);
profile.bookGoals = { monthly: m, yearly: y };
saveProfile();
renderProfileUI();
announceGoalUpdate(`Book goals updated: ${m} this month, ${y} this year.`);
});
}
// Quick toggle between pages/minutes in the widget
const quickToggle = document.getElementById("quick-toggle-metric");
if (quickToggle) {
quickToggle.addEventListener("click", () => {
// If no goal yet, create a sane default and flip
if (!profile.dailyGoal) {
profile.dailyGoal = { type: "pages", value: 20 };
}
const next = profile.dailyGoal.type === "minutes" ? "pages" : "minutes";
profile.dailyGoal = { ...profile.dailyGoal, type: next };
saveProfile();
// Mirror the UI <select> so both stay in sync
const goalTypeSel = document.getElementById("goal-type");
if (goalTypeSel) {
goalTypeSel.value = next;
}
// Update aria-pressed state for the toggle
quickToggle.setAttribute(
"aria-pressed",
next === "minutes" ? "true" : "false"
);
renderProfileUI();
});
}
// ---------- Tooltip: helpers ----------
function getBookTitleById(id) {
const book = books.find((x) => x.id === id);
return book ? book.title : "Unknown book";
}
// -----------------------
// Aria sync
// -----------------------
function setThemeAriaState() {
const btn = document.getElementById("mode-toggle");
if (!btn) return;
// Consider "checked" when the effective theme is dark
const isDark =
typeof getEffectiveMode === "function"
? getEffectiveMode(themeMode) === "dark"
: document.body.classList.contains("mode-dark");
btn.setAttribute("aria-checked", String(isDark));
}
if (typeof applyAppearance === "function") {
const _applyAppearance = applyAppearance;
applyAppearance = function (mode) {
// Update the global theme (body classes, etc.)
_applyAppearance(mode);
// Keep the theme toggle button ARIA state in sync
setThemeAriaState();
// Keep the Shareable Snapshot card + logo in sync with the new theme
try {
renderSnapshotCard();
} catch (err) {
// Snapshot might not be initialized yet; ignore silently in that case
if (console?.debug) {
console.debug("Snapshot theme sync skipped:", err);
}
}
};
// Run once on initial load so ARIA + snapshot are correct
setThemeAriaState();
try {
renderSnapshotCard();
} catch {}
}
// -----------------------
// Extra helpers
// -----------------------
async function checkForUpdatesNow() {
const reg = await navigator.serviceWorker.getRegistration();
await reg?.update(); // triggers updatefound if a new SW is available
}
// -----------------------
// Undo helper (single-step, toast-driven)
// -----------------------
function withUndo({ label = "Action", apply, revert, details = [] }) {
// 1. Perform the change
apply?.();
// 2. Offer undo for a short time window
showToast(label, "info", {
actions: [
{
label: "Undo",
className: "r-btn r-btn--sm",
onClick: () => {
revert?.();
renderProfileUI();
Books.render();
showToast("Undone", "success", { timeout: 1500 });
},
},
],
details,
timeout: 6000,
});
}
// -----------------------
// Goal reminders + ARIA live helper
// -----------------------
function announceGoalUpdate(message) {
const region = document.getElementById("sr-goal-updates");
if (region) {
region.textContent = message || "";
}
}
function nextReminderMode(current) {
if (current === "off") return "daily";
if (current === "daily") return "weekly";
return "off";
}
function initGoalRemindersUI() {
const btn = document.getElementById("goal-reminders");
if (!btn) {
// Even if the button isn't present, still schedule reminders
scheduleGoalReminder();
return;
}
// Normalize stored value
if (!["off", "daily", "weekly"].includes(goalReminderMode)) {
goalReminderMode = "off";
}
const labelEl = btn.querySelector(".goal-reminders__label");
const stateEl = btn.querySelector(".goal-reminders__state");
const syncButton = () => {
let stateLabel;
if (goalReminderMode === "daily") {
stateLabel = "Daily";
} else if (goalReminderMode === "weekly") {
stateLabel = "Weekly";
} else {
stateLabel = "Off";
}
if (labelEl && stateEl) {
// New pill-style markup
labelEl.textContent = "goal-reminders";
stateEl.textContent = stateLabel;
} else {
// Fallback: simple text-only button
btn.textContent = `Goal reminders: ${stateLabel}`;
}
btn.setAttribute(
"aria-checked",
goalReminderMode === "off" ? "false" : "true"
);
};
syncButton();
scheduleGoalReminder();
btn.addEventListener("click", async () => {
goalReminderMode = nextReminderMode(goalReminderMode);
localStorage.setItem(GOAL_REMINDERS_KEY, goalReminderMode);
syncButton();
scheduleGoalReminder();
const message =
goalReminderMode === "off"
? "Goal reminders turned off."
: `Goal reminders set to ${goalReminderMode}.`;
announceGoalUpdate(message);
// Settings-saved toast
showToast(message, "success");
// Request browser notification permission on opt-in
if (
goalReminderMode !== "off" &&
"Notification" in window &&
Notification.permission === "default"
) {
try {
const permission = await Notification.requestPermission();
if (permission !== "granted") {
showToast(
"Browser notifications are blocked. You'll still see in-app reminders.",
"warning",
{ timeout: 5000 }
);
}
} catch {
/* ignore */
}
}
});
}
function scheduleGoalReminder() {
if (goalReminderTimeoutId) {
clearTimeout(goalReminderTimeoutId);
goalReminderTimeoutId = null;
}
if (goalReminderMode === "off") return;
const now = new Date();
const target = new Date(now);
target.setSeconds(0, 0);
if (goalReminderMode === "daily") {
// Next 8pm local
target.setHours(20, 0, 0, 0);
if (target <= now) target.setDate(target.getDate() + 1);
} else if (goalReminderMode === "weekly") {
// Next Sunday 8pm local
const day = target.getDay(); // 0 = Sunday...6 = Saturday
const daysToNextSunday = (7 - day) & 7 || 7;
target.setDate(target.getDate() + daysToNextSunday);
target.setHours(20, 0, 0, 0);
}
const delay = Math.max(5000, target - now); // safeguard: at least 5s
goalReminderTimeoutId = setTimeout(() => {
fireGoalReminder();
scheduleGoalReminder();
}, delay);
}
function fireGoalReminder() {
const message = "Time to check your reading goals for today.";
if ("Notification" in window && Notification.permission === "granted") {
try {
new Notification("Readr — Goal reminder", {
body: message,
tag: "readr-goal-reminder",
});
} catch {
// fall back to toast + SR
showToast(message, "info", { timeout: 8000 });
}
} else {
showToast(message, "info", { timeout: 8000 });
}
announceGoalUpdate(message);
}
function loadShortcutsPref() {
try {
const raw = localStorage.getItem(SHORTCUTS_KEY);
if (raw === null) {
// Defailt ON for non-touch devices, OFF for touch
return !("ontouchstart" in window);
}
if (raw === "true" || raw === "false") return raw === "true";
return !!JSON.parse(raw);
} catch {
return true;
}
}
function setShortcutsEnabled(next) {
shortcutsEnabled = !!next;
try {
localStorage.setItem(SHORTCUTS_KEY, JSON.stringify(shortcutsEnabled));
} catch {
// ignore quota errors
}
// Update the mini help line visibility/content + live region
syncShortcutsHint();
}
function getShortcutsEnabled() {
return shortcutsEnabled;
}
// -----------------------
// Toasts
// -----------------------
function showToast(
message,
type = "info",
{ actions = [], details = [], timeout = 3000 } = {}
) {
const host = document.getElementById("toasts");
if (!host) return;
const el = document.createElement("div");
el.className = `toast ${
/^(info|success|error|warning)$/.test(type) ? type : "info"
} enter`;
el.setAttribute("role", "status");
const msg = document.createElement("span");
msg.textContent = String(message);
const actionsBox = document.createElement("div");
actionsBox.className = "actions";
el.appendChild(msg);
if (Array.isArray(details) && details.length) {
const small = document.createElement("small");
details.forEach((line, i) => {
if (i) {
small.appendChild(document.createElement("br"));
}
small.appendChild(document.createTextNode(String(line)));
});
el.appendChild(small);
}
el.appendChild(actionsBox);
actions.forEach(({ label, onClick, className = "r-btn r-btn--sm" }) => {
const b = document.createElement("button");
b.type = "button";
b.className = className;
b.textContent = label;
b.addEventListener(
"click",
() => {
onClick?.();
dismiss(0);
},
{ once: true }
);
actionsBox.appendChild(b);
});
host.appendChild(el);
let hideTimer = null;
const dismiss = (delay = 120) => {
clearTimeout(hideTimer);
el.classList.remove("enter");
el.classList.add("exit");
setTimeout(() => el.remove(), delay);
};
if (timeout > 0) {
hideTimer = setTimeout(() => dismiss(), timeout);
}
return { dismiss };
}
// Populate the book dropdown
function buildBookOptions() {
const select = document.getElementById("log-book");
if (!select) {
return;
}
select.innerHTML = "";
books.forEach((book) => {
const opt = document.createElement("option");
opt.value = String(book.id);
opt.textContent = `${book.title} - ${book.author}`;
select.appendChild(opt);
});
}
function buildFilterOptions() {}
// -----------------------
// Storage Helpers
// -----------------------
function loadBooks() {
try {
books = JSON.parse(localStorage.getItem(BOOKS_KEY)) || [];
} catch {
books = [];
}
}
function saveBooks() {
localStorage.setItem(BOOKS_KEY, JSON.stringify(books));
// Keep analytics in sync
if (Analytics && typeof Analytics.loadAnalyticsData === "function") {
Analytics.loadAnalyticsData({ books, sessions: logs });
}
renderCharts();
renderSnapshotCard();
// Evaluate badges whenever books change (e.g., book finished)
if (Badges && typeof Badges.evaluateBadges === "function") {
Badges.evaluateBadges();
}
}
function loadLogs() {
try {
logs = JSON.parse(localStorage.getItem(LOGS_KEY)) || [];
} catch {
logs = [];
}
}
function saveLogs() {
localStorage.setItem(LOGS_KEY, JSON.stringify(logs));
// Keep analytics in sync
if (Analytics && typeof Analytics.loadAnalyticsData === "function") {
Analytics.loadAnalyticsData({ books, sessions: logs });
}
renderCharts();
renderSnapshotCard();
// Evaluate badges whenever sessions/logs change
if (Badges && typeof Badges.evaluateBadges === "function") {
Badges.evaluateBadges();
}
}
function loadProfile() {
try {
const raw = localStorage.getItem(PROFILE_KEY);
if (raw) {
profile = JSON.parse(raw);
}
} catch {
/* keep defaults */
}
}
function saveProfile() {
localStorage.setItem(PROFILE_KEY, JSON.stringify(profile));
}
// -----------------------
// Data Helpers
// -----------------------
function dayKey(date = new Date()) {
const dayStart = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
);
return dayStart.toISOString().slice(0, 10); // YYYY-MM-DD
}
function monthKey(date = new Date()) {
return date.toISOString().slice(0, 7); // "YYYY-MM"
}
export { books, saveBooks };
function migrateStatusesToReading(books, saveBooks) {
if (!Array.isArray(books) || !books.length) return;
let changed = false;
for (const b of books) {