Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1790 lines (1648 loc) · 47.7 KB
/
Copy pathapp.js
File metadata and controls
1790 lines (1648 loc) · 47.7 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
const textInput = document.getElementById("textInput");
const docTitle = document.getElementById("docTitle");
const wordCountEl = document.getElementById("wordCount");
const progressEl = document.getElementById("progress");
const wordDisplay = document.getElementById("wordDisplay");
const leftSpan = wordDisplay.querySelector(".word-left");
const focusSpan = wordDisplay.querySelector(".word-focus");
const rightSpan = wordDisplay.querySelector(".word-right");
const speedRange = document.getElementById("speedRange");
const wpmValue = document.getElementById("wpmValue");
const sliderTrack = document.querySelector(".slider-track");
const readerPanel = document.getElementById("readerPanel");
const readerControls = document.getElementById("readerControls");
const toggleControlsBtn = document.getElementById("toggleControlsBtn");
const fullscreenBtn = document.getElementById("fullscreenBtn");
const customizeBtn = document.getElementById("customizeBtn");
const customizePanel = document.getElementById("customizePanel");
const readerDoc = document.getElementById("readerDoc");
const actionButtons = document.querySelectorAll("[data-action]");
const pauseButtons = document.querySelectorAll('[data-action="pause"]');
const pdfInput = document.getElementById("pdfInput");
const pdfStatus = document.getElementById("pdfStatus");
const epubInput = document.getElementById("epubInput");
const epubStatus = document.getElementById("epubStatus");
const ocrToggle = document.getElementById("ocrToggle");
const libraryList = document.getElementById("libraryList");
const libraryEmpty = document.getElementById("libraryEmpty");
const clearLibraryBtn = document.getElementById("clearLibraryBtn");
const historyLastRead = document.getElementById("historyLastRead");
const historySessions = document.getElementById("historySessions");
const historyTime = document.getElementById("historyTime");
const dropOverlay = document.getElementById("dropOverlay");
const inputPanel = document.querySelector(".input-panel");
const pdfjsLib = window.pdfjsLib;
const epubjsLib = window.ePub;
const focusHighlightToggle = document.getElementById("focusHighlightToggle");
const focusColorPicker = document.getElementById("focusColorPicker");
const focusColorButtons = document.querySelectorAll("[data-focus-color]");
const autoPaceToggle = document.getElementById("autoPaceToggle");
const autoPaceSettings = document.getElementById("autoPaceSettings");
const startPaceInput = document.getElementById("startPace");
const maxPaceInput = document.getElementById("maxPace");
const liveWpmEl = document.getElementById("liveWpm");
const contextView = document.getElementById("contextView");
const contextToggle = document.getElementById("contextToggle");
const contextNav = document.getElementById("contextNav");
const prevParagraphBtn = document.getElementById("prevParagraph");
const nextParagraphBtn = document.getElementById("nextParagraph");
const reader = document.querySelector(".reader");
let words = [];
let currentIndex = 0;
let timerId = null;
let isPlaying = false;
let wpm = Number(speedRange.value);
let isPseudoFullscreen = false;
let hasStarted = false;
let isPdfLoading = false;
let isEpubLoading = false;
let activeDoc = null;
let isSettingText = false;
let isOcrEnabled = false;
let saveTimer = null;
let libraryRefreshTimer = null;
let ocrWorker = null;
let ocrLoadingPromise = null;
let isAutoPaceEnabled = false;
let autoPaceStartWpm = 150;
let autoPaceMaxWpm = 400;
const AUTO_PACE_WORDS_PER_STEP = 25;
let sessionStartAt = null;
let focusHighlightEnabled = true;
let focusColor = "#ff3b30";
let isContextViewActive = false;
let originalText = "";
let contextParagraphs = [];
let currentParagraphIndex = 0;
let wordSizePaceNormalization = 1;
const WORD_SIZE_NEUTRAL_LENGTH = 5;
const WORD_SIZE_PACE_SLOPE = 0.055;
const WORD_SIZE_MIN_MULTIPLIER = 0.72;
const WORD_SIZE_MAX_MULTIPLIER = 1.35;
const PDF_WORKER_SRC =
"https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js";
const TESSERACT_SRC =
"https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js";
const DB_NAME = "focus-reader";
const DB_VERSION = 1;
const STORE_NAME = "documents";
const PREFS_KEY = "focusReaderPrefs";
if (pdfjsLib && pdfjsLib.GlobalWorkerOptions) {
pdfjsLib.GlobalWorkerOptions.workerSrc = PDF_WORKER_SRC;
}
function openDb() {
if (!("indexedDB" in window)) {
return Promise.reject(new Error("IndexedDB unavailable"));
}
return new Promise((resolve, reject) => {
const request = window.indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
const store = db.createObjectStore(STORE_NAME, { keyPath: "id" });
store.createIndex("updatedAt", "updatedAt");
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error || new Error("DB open failed"));
});
}
let dbPromise = null;
function getDb() {
if (!dbPromise) {
dbPromise = openDb().catch((error) => {
console.warn(error);
return null;
});
}
return dbPromise;
}
async function dbPut(doc) {
const db = await getDb();
if (!db) {
return;
}
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
tx.objectStore(STORE_NAME).put(doc);
});
}
async function dbGet(id) {
const db = await getDb();
if (!db) {
return null;
}
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readonly");
const request = tx.objectStore(STORE_NAME).get(id);
request.onsuccess = () => resolve(request.result || null);
request.onerror = () => reject(request.error);
});
}
async function dbGetAll() {
const db = await getDb();
if (!db) {
return [];
}
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readonly");
const request = tx.objectStore(STORE_NAME).getAll();
request.onsuccess = () => resolve(request.result || []);
request.onerror = () => reject(request.error);
});
}
async function dbDelete(id) {
const db = await getDb();
if (!db) {
return;
}
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
tx.objectStore(STORE_NAME).delete(id);
});
}
async function dbClear() {
const db = await getDb();
if (!db) {
return;
}
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
tx.objectStore(STORE_NAME).clear();
});
}
function hashText(text) {
let hash = 5381;
for (let i = 0; i < text.length; i += 1) {
hash = ((hash << 5) + hash) + text.charCodeAt(i);
hash = hash >>> 0;
}
return hash.toString(16);
}
function deriveTitle(text) {
const titleWords = text.trim().split(/\s+/).slice(0, 6);
return titleWords.length ? titleWords.join(" ") : "Untitled";
}
function formatTimestamp(timestamp) {
if (!timestamp) {
return "new";
}
return new Date(timestamp).toLocaleString(undefined, {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
}
function parseHtmlToText(html) {
if (!html) {
return "";
}
try {
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
return doc.body ? doc.body.textContent || "" : "";
} catch (_) {
return "";
}
}
function formatDuration(ms) {
if (!ms || ms <= 0) {
return "0m";
}
const totalSeconds = Math.round(ms / 1000);
const totalMinutes = Math.floor(totalSeconds / 60);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
if (totalMinutes > 0) {
return `${totalMinutes}m ${seconds}s`;
}
return `${seconds}s`;
}
function loadPrefs() {
if (!("localStorage" in window)) {
return {};
}
try {
const raw = window.localStorage.getItem(PREFS_KEY);
return raw ? JSON.parse(raw) : {};
} catch (error) {
console.warn(error);
return {};
}
}
function savePrefs() {
if (!("localStorage" in window)) {
return;
}
const payload = {
focusHighlightEnabled,
focusColor,
};
try {
window.localStorage.setItem(PREFS_KEY, JSON.stringify(payload));
} catch (error) {
console.warn(error);
}
}
function applyFocusColor() {
const root = document.documentElement;
const computed = window.getComputedStyle(root);
const textColor = computed.getPropertyValue("--text").trim() || "#ffffff";
const applied = focusHighlightEnabled ? focusColor : textColor;
root.style.setProperty("--focus", applied);
if (focusColorPicker) {
focusColorPicker.disabled = !focusHighlightEnabled;
}
}
function applyPrefs(prefs = {}) {
if (typeof prefs.focusHighlightEnabled === "boolean") {
focusHighlightEnabled = prefs.focusHighlightEnabled;
}
if (prefs.focusColor) {
focusColor = prefs.focusColor;
}
applyFocusColor();
if (focusHighlightToggle) {
focusHighlightToggle.checked = focusHighlightEnabled;
}
if (focusColorPicker) {
focusColorPicker.value = focusColor;
}
renderWordAtIndex(currentIndex);
}
function setFocusHighlightEnabled(enabled) {
focusHighlightEnabled = Boolean(enabled);
applyFocusColor();
savePrefs();
}
function setFocusColor(nextColor) {
focusColor = nextColor;
applyFocusColor();
savePrefs();
}
function tokenize(text) {
return text.trim().match(/\S+/g) ?? [];
}
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
function getWordCharacterCount(word) {
const lettersAndNumbers = word.match(/[A-Za-z0-9]/g);
return lettersAndNumbers ? lettersAndNumbers.length : 0;
}
function getRawWordSizeMultiplier(word) {
const charCount = getWordCharacterCount(word);
if (!charCount) {
return 1;
}
const unbounded = 1 + ((charCount - WORD_SIZE_NEUTRAL_LENGTH) * WORD_SIZE_PACE_SLOPE);
return clamp(unbounded, WORD_SIZE_MIN_MULTIPLIER, WORD_SIZE_MAX_MULTIPLIER);
}
function recalculateWordSizePaceNormalization() {
if (!words.length) {
wordSizePaceNormalization = 1;
return;
}
let totalMultiplier = 0;
for (const word of words) {
totalMultiplier += getRawWordSizeMultiplier(word);
}
const averageMultiplier = totalMultiplier / words.length;
if (!Number.isFinite(averageMultiplier) || averageMultiplier <= 0) {
wordSizePaceNormalization = 1;
return;
}
wordSizePaceNormalization = averageMultiplier;
}
function getWordSizePaceMultiplier(word) {
const rawMultiplier = getRawWordSizeMultiplier(word);
if (!Number.isFinite(wordSizePaceNormalization) || wordSizePaceNormalization <= 0) {
return rawMultiplier;
}
return rawMultiplier / wordSizePaceNormalization;
}
function updateReaderDocLabel() {
if (!readerDoc) {
return;
}
if (activeDoc && activeDoc.title) {
readerDoc.textContent = activeDoc.title;
return;
}
if (textInput.value.trim()) {
readerDoc.textContent = "Unsaved text";
return;
}
readerDoc.textContent = "No document loaded";
}
function updateHistoryPanel() {
if (!historyLastRead || !historySessions || !historyTime) {
return;
}
if (!activeDoc) {
historyLastRead.textContent = "—";
historySessions.textContent = "0";
historyTime.textContent = "0m";
return;
}
historyLastRead.textContent = formatTimestamp(activeDoc.lastReadAt);
historySessions.textContent = `${activeDoc.sessions || 0}`;
historyTime.textContent = formatDuration(activeDoc.totalReadMs || 0);
}
function getProgressPercent(index, total) {
if (!total) {
return 0;
}
return Math.min(100, Math.round((index / total) * 100));
}
function createDocumentFromText(text, options = {}) {
const now = Date.now();
const docTitleValue = (options.title || "").trim();
const derivedTitle = docTitleValue || deriveTitle(text);
const docWords = tokenize(text);
return {
id: hashText(text),
title: derivedTitle || "Untitled",
text,
source: options.source || "paste",
wordCount: docWords.length,
lastIndex: 0,
createdAt: now,
updatedAt: now,
lastReadAt: null,
wpm,
sessions: 0,
totalReadMs: 0,
meta: options.meta || {},
};
}
function applyDocumentState(doc, options = {}) {
if (activeDoc && sessionStartAt) {
endSession();
}
activeDoc = doc;
sessionStartAt = null;
if (activeDoc) {
activeDoc.sessions = activeDoc.sessions || 0;
activeDoc.totalReadMs = activeDoc.totalReadMs || 0;
}
if (docTitle && doc) {
docTitle.value = doc.title || "";
}
if (options.setText !== false && doc && typeof doc.text === "string") {
isSettingText = true;
textInput.value = doc.text;
isSettingText = false;
}
originalText = doc ? (doc.text || "") : "";
words = doc ? tokenize(doc.text || "") : [];
recalculateWordSizePaceNormalization();
currentIndex = doc ? Math.min(doc.lastIndex || 0, words.length) : 0;
updateStats();
if (words.length) {
renderWordAtIndex(currentIndex);
} else {
renderWord("");
}
if (doc && typeof doc.wpm === "number") {
wpm = doc.wpm;
speedRange.value = wpm.toString();
updateDial();
}
updateReaderDocLabel();
updateHistoryPanel();
updatePlayStateUI();
scheduleLibraryRefresh();
}
function scheduleLibraryRefresh() {
if (libraryRefreshTimer) {
return;
}
libraryRefreshTimer = window.setTimeout(() => {
libraryRefreshTimer = null;
refreshLibrary();
}, 400);
}
async function refreshLibrary() {
if (!libraryList || !libraryEmpty) {
return;
}
let docs = [];
try {
docs = await dbGetAll();
} catch (error) {
console.warn(error);
}
docs.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
libraryList.innerHTML = "";
if (!docs.length) {
libraryEmpty.style.display = "block";
return;
}
libraryEmpty.style.display = "none";
docs.forEach((doc) => {
const item = document.createElement("li");
item.className = "library-item";
if (activeDoc && doc.id === activeDoc.id) {
item.classList.add("active");
}
const info = document.createElement("div");
const name = document.createElement("p");
name.className = "library-name";
name.textContent = doc.title || "Untitled";
const meta = document.createElement("p");
meta.className = "library-meta";
const progress = getProgressPercent(doc.lastIndex || 0, doc.wordCount || 0);
const sessions = doc.sessions || 0;
const timeSpent = formatDuration(doc.totalReadMs || 0);
meta.textContent = `${progress}% | ${doc.wordCount || 0} words | ${formatTimestamp(doc.lastReadAt)} | ${sessions} sessions | ${timeSpent}`;
info.appendChild(name);
info.appendChild(meta);
const actions = document.createElement("div");
actions.className = "library-actions";
const resumeButton = document.createElement("button");
resumeButton.textContent = "Resume";
resumeButton.dataset.docAction = "resume";
resumeButton.dataset.docId = doc.id;
const restartButton = document.createElement("button");
restartButton.textContent = "Restart";
restartButton.dataset.docAction = "restart";
restartButton.dataset.docId = doc.id;
const deleteButton = document.createElement("button");
deleteButton.textContent = "Delete";
deleteButton.dataset.docAction = "delete";
deleteButton.dataset.docId = doc.id;
actions.appendChild(resumeButton);
actions.appendChild(restartButton);
actions.appendChild(deleteButton);
item.appendChild(info);
item.appendChild(actions);
libraryList.appendChild(item);
});
}
async function loadDocumentById(id, options = {}) {
if (!id) {
return;
}
const doc = await dbGet(id);
if (!doc) {
return;
}
if (options.restart) {
doc.lastIndex = 0;
doc.updatedAt = Date.now();
doc.lastReadAt = Date.now();
}
applyDocumentState(doc);
if (options.restart) {
await dbPut(doc);
}
}
function scheduleSaveProgress(force = false) {
if (!activeDoc) {
return;
}
if (saveTimer && !force) {
return;
}
if (saveTimer) {
window.clearTimeout(saveTimer);
}
saveTimer = window.setTimeout(() => {
saveTimer = null;
saveActiveDocumentProgress().catch((error) => console.warn(error));
}, force ? 0 : 600);
}
async function saveActiveDocumentProgress() {
if (!activeDoc) {
return;
}
activeDoc.lastIndex = currentIndex;
activeDoc.wordCount = words.length;
activeDoc.updatedAt = Date.now();
activeDoc.lastReadAt = Date.now();
activeDoc.wpm = wpm;
activeDoc.sessions = activeDoc.sessions || 0;
activeDoc.totalReadMs = activeDoc.totalReadMs || 0;
if (!activeDoc.title || !activeDoc.title.trim()) {
activeDoc.title = deriveTitle(activeDoc.text || "") || "Untitled";
}
await dbPut(activeDoc);
updateHistoryPanel();
scheduleLibraryRefresh();
}
async function ensureActiveDocumentFromText() {
const rawText = textInput.value.trim();
if (!rawText) {
return null;
}
const id = hashText(rawText);
let doc = null;
try {
doc = await dbGet(id);
} catch (error) {
console.warn(error);
}
if (!doc) {
doc = createDocumentFromText(rawText, {
title: docTitle ? docTitle.value : "",
source: "paste",
});
} else {
doc.text = rawText;
doc.wordCount = words.length;
if (docTitle && docTitle.value.trim()) {
doc.title = docTitle.value.trim();
}
doc.sessions = doc.sessions || 0;
doc.totalReadMs = doc.totalReadMs || 0;
}
applyDocumentState(doc, { setText: false });
await dbPut(doc);
return doc;
}
function updateStats() {
wordCountEl.textContent = words.length.toString();
const progress = getProgressPercent(currentIndex, words.length);
progressEl.textContent = `${progress}%`;
}
function updateDial() {
wpmValue.textContent = wpm.toString();
speedRange.value = wpm.toString();
}
function updateLiveWpm() {
if (!liveWpmEl) return;
if (isPlaying) {
liveWpmEl.textContent = `${wpm} WPM`;
liveWpmEl.classList.add("visible");
} else {
liveWpmEl.classList.remove("visible");
}
}
function jumpWords(amount) {
if (!words.length) return;
const wasPlaying = isPlaying;
if (wasPlaying) {
pauseReading();
}
const nextIndex = Math.min(
words.length - 1,
Math.max(0, currentIndex + amount),
);
currentIndex = nextIndex;
renderWordAtIndex(currentIndex);
updateStats();
scheduleSaveProgress();
}
function rewindSeconds(seconds) {
if (!words.length) return;
const wordsBack = Math.max(1, Math.round((wpm / 60) * seconds));
jumpWords(-wordsBack);
}
function stepWord(direction) {
if (!words.length) return;
const wasPlaying = isPlaying;
if (wasPlaying) {
pauseReading();
}
if (direction === "back" && currentIndex > 0) {
currentIndex -= 1;
} else if (direction === "forward" && currentIndex < words.length - 1) {
currentIndex += 1;
}
renderWordAtIndex(currentIndex);
updateStats();
scheduleSaveProgress();
}
function calculateAutoPaceWpm() {
if (!isAutoPaceEnabled || !words.length) {
return wpm;
}
const totalWords = words.length;
const progress = currentIndex / totalWords;
const wpmRange = autoPaceMaxWpm - autoPaceStartWpm;
const newWpm = Math.round(autoPaceStartWpm + (wpmRange * progress));
return Math.min(newWpm, autoPaceMaxWpm);
}
function updateAutoPace() {
if (!isAutoPaceEnabled) {
return;
}
const newWpm = calculateAutoPaceWpm();
if (newWpm !== wpm) {
wpm = newWpm;
updateDial();
}
}
function updatePlayStateUI() {
let label = "Pause";
if (!isPlaying && hasStarted) {
label = "Resume";
}
pauseButtons.forEach((button) => {
button.textContent = label;
});
}
function setPlayingState(nextState) {
isPlaying = nextState;
updatePlayStateUI();
updateLiveWpm();
}
function beginSession() {
if (!activeDoc || sessionStartAt) {
return;
}
sessionStartAt = Date.now();
activeDoc.sessions = (activeDoc.sessions || 0) + 1;
activeDoc.lastReadAt = Date.now();
updateHistoryPanel();
scheduleSaveProgress(true);
}
function endSession() {
if (!activeDoc || !sessionStartAt) {
return;
}
const duration = Date.now() - sessionStartAt;
sessionStartAt = null;
activeDoc.totalReadMs = (activeDoc.totalReadMs || 0) + duration;
activeDoc.updatedAt = Date.now();
activeDoc.lastReadAt = Date.now();
dbPut(activeDoc).catch((error) => console.warn(error));
updateHistoryPanel();
scheduleLibraryRefresh();
}
function setPdfStatus(message, isError = false) {
if (!pdfStatus) {
return;
}
pdfStatus.textContent = message;
pdfStatus.classList.toggle("error", isError);
}
function setEpubStatus(message, isError = false) {
if (!epubStatus) {
return;
}
epubStatus.textContent = message;
epubStatus.classList.toggle("error", isError);
}
function loadOcrScript() {
if (window.Tesseract) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = TESSERACT_SRC;
script.onload = () => resolve();
script.onerror = () => reject(new Error("Failed to load OCR"));
document.head.appendChild(script);
});
}
async function getOcrWorker() {
if (ocrWorker) {
return ocrWorker;
}
if (ocrLoadingPromise) {
return ocrLoadingPromise;
}
ocrLoadingPromise = (async () => {
await loadOcrScript();
const worker = await window.Tesseract.createWorker("eng", 1, {
logger: (message) => {
if (message && message.status) {
setPdfStatus(`OCR ${message.status} ${Math.round((message.progress || 0) * 100)}%`);
}
},
});
ocrWorker = worker;
return worker;
})();
return ocrLoadingPromise;
}
async function runOcrOnPage(page, pageNumber, totalPages) {
const worker = await getOcrWorker();
const viewport = page.getViewport({ scale: 2 });
const canvas = document.createElement("canvas");
canvas.width = viewport.width;
canvas.height = viewport.height;
const context = canvas.getContext("2d");
await page.render({ canvasContext: context, viewport }).promise;
setPdfStatus(`OCR page ${pageNumber} of ${totalPages}`);
const result = await worker.recognize(canvas);
canvas.width = 0;
canvas.height = 0;
return result.data && result.data.text ? result.data.text : "";
}
function extractSectionText(contents) {
if (!contents) {
return "";
}
if (typeof contents === "string") {
return parseHtmlToText(contents);
}
// epub.js returns a Document - check body first
if (contents.body && contents.body.textContent) {
return contents.body.textContent || "";
}
if (contents.documentElement && contents.documentElement.textContent) {
return contents.documentElement.textContent || "";
}
if (contents.textContent) {
return contents.textContent || "";
}
if (contents.ownerDocument && contents.ownerDocument.body) {
return contents.ownerDocument.body.textContent || "";
}
return "";
}
function getFocusIndex(word) {
const letterIndexes = [];
for (let i = 0; i < word.length; i += 1) {
if (/\p{L}/u.test(word[i])) {
letterIndexes.push(i);
}
}
if (!letterIndexes.length) {
return -1;
}
const center = Math.floor((letterIndexes.length - 1) / 2);
return letterIndexes[center];
}
function renderWord(word) {
if (!word) {
leftSpan.textContent = "";
focusSpan.textContent = "";
rightSpan.textContent = "";
return;
}
const focusIndex = getFocusIndex(word);
if (focusIndex === -1) {
leftSpan.textContent = word;
focusSpan.textContent = "";
rightSpan.textContent = "";
return;
}
leftSpan.textContent = word.slice(0, focusIndex);
focusSpan.textContent = word[focusIndex];
rightSpan.textContent = word.slice(focusIndex + 1);
}
function renderWordAtIndex(index) {
if (!words.length || index < 0 || index >= words.length) {
renderWord("");
return;
}
const word = words[index];
if (!word) {
renderWord("");
return;
}
renderWord(word);
}
function buildParagraphsData() {
if (!originalText) {
contextParagraphs = [];
return;
}
// Normalize text: convert single newlines to spaces, keep double newlines as paragraph breaks
// This handles PDFs where every line ends with \n but they're part of the same paragraph
const normalized = originalText
.replace(/\r\n/g, '\n') // Normalize Windows line endings
.replace(/\n{3,}/g, '\n\n') // Collapse multiple newlines to double
.replace(/([^\n])\n([^\n])/g, '$1 $2'); // Single newlines become spaces
// Split into paragraphs by double newline
const rawParagraphs = normalized.split(/\n\n+/).filter(p => p.trim());
// Build paragraph data with word offsets
// We need to map back to the original word indices from tokenize(originalText)
const allWords = words; // Use the global words array that was tokenized from originalText
let wordOffset = 0;
contextParagraphs = rawParagraphs.map((text, index) => {
const paraWords = tokenize(text);
const startIndex = wordOffset;
wordOffset += paraWords.length;
return {
text,
words: paraWords,
startIndex,
endIndex: wordOffset - 1,
index
};
});
// If word counts don't match, fall back to treating entire text as one paragraph
if (wordOffset !== allWords.length) {
contextParagraphs = [{
text: originalText,
words: allWords,
startIndex: 0,
endIndex: allWords.length - 1,
index: 0
}];
}
}
function findParagraphIndexForWord(wordIndex) {
for (let i = 0; i < contextParagraphs.length; i++) {
const para = contextParagraphs[i];
if (wordIndex >= para.startIndex && wordIndex <= para.endIndex) {
return i;
}
}
return 0;
}
function renderContextView(highlightWordIndex) {
if (!contextView || !contextParagraphs.length) {
if (contextView) {
contextView.innerHTML = "<p><em>No context available</em></p>";
}
return;
}
const para = contextParagraphs[currentParagraphIndex];
if (!para) {
contextView.innerHTML = "<p><em>No context available</em></p>";
return;
}
// Determine which word to highlight within this paragraph
let localHighlight = -1;
if (highlightWordIndex >= para.startIndex && highlightWordIndex <= para.endIndex) {
localHighlight = highlightWordIndex - para.startIndex;
}
// Build HTML with highlighted word
const parts = [];
for (let i = 0; i < para.words.length; i++) {
if (i === localHighlight) {
parts.push(`<span class="highlight">${para.words[i]}</span>`);
} else {
parts.push(para.words[i]);
}
}
contextView.innerHTML = `<p>${parts.join(" ")}</p>`;
// Update nav button states
updateContextNavButtons();
}
function updateContextNavButtons() {
if (!prevParagraphBtn || !nextParagraphBtn) return;
prevParagraphBtn.disabled = currentParagraphIndex <= 0;
nextParagraphBtn.disabled = currentParagraphIndex >= contextParagraphs.length - 1;
}
function goToPrevParagraph() {
if (currentParagraphIndex > 0) {
currentParagraphIndex -= 1;
const para = contextParagraphs[currentParagraphIndex];
// Update currentIndex to first word of this paragraph (accounting for the +1 offset)
currentIndex = para.startIndex + 1;
renderContextView(para.startIndex);
updateStats();
}
}
function goToNextParagraph() {
if (currentParagraphIndex < contextParagraphs.length - 1) {
currentParagraphIndex += 1;
const para = contextParagraphs[currentParagraphIndex];
// Update currentIndex to first word of this paragraph (accounting for the +1 offset)
currentIndex = para.startIndex + 1;
renderContextView(para.startIndex);
updateStats();
}
}