-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1061 lines (974 loc) · 44.6 KB
/
Copy pathindex.html
File metadata and controls
1061 lines (974 loc) · 44.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title>Audiobook Reader</title>
<!-- Privacy, enforced by the browser rather than promised by us.
connect-src 'none' blocks every outbound request (fetch/XHR/WebSocket/beacon),
so this page physically cannot transmit a reader's document anywhere; everything
else is pinned to same-origin files shipped in this repo. If a future edit ever
added a CDN, an analytics tag, or an API call, it would fail loudly instead of
quietly leaking. Keep it that way. -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; worker-src 'self' blob:; manifest-src 'self'; connect-src 'none'; form-action 'none'; base-uri 'none'; object-src 'none'" />
<!-- iOS / installable web-app -->
<meta name="theme-color" content="#0f1115" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="Audiobook" />
<link rel="apple-touch-icon" href="icon.svg" />
<link rel="icon" href="icon.svg" />
<link rel="manifest" href="manifest.webmanifest" />
<!-- Document parsers (vendored locally so the app works fully offline) -->
<script src="vendor/pdf.min.js"></script>
<script src="vendor/mammoth.browser.min.js"></script>
<style>
:root {
--bg: #0f1115;
--panel: #171a21;
--panel-2: #1f2430;
--text: #e7e9ee;
--muted: #9aa3b2;
--accent: #6c8cff;
--accent-2: #4a6bff;
--highlight: #3a4a8c;
--border: #2a2f3a;
}
* { box-sizing: border-box; }
body {
margin: 0;
padding: env(safe-area-inset-top) env(safe-area-inset-right) 0 env(safe-area-inset-left);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.6;
-webkit-text-size-adjust: 100%;
}
header {
padding: 18px 24px;
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
gap: 12px;
}
header h1 { font-size: 18px; margin: 0; font-weight: 600; }
header .sub { color: var(--muted); font-size: 13px; }
.wrap { max-width: 880px; margin: 0 auto; padding: 24px; }
/* Drop zone */
#drop {
border: 2px dashed var(--border);
border-radius: 14px;
padding: 48px 24px;
text-align: center;
color: var(--muted);
cursor: pointer;
transition: border-color .15s, background .15s;
background: var(--panel);
}
#drop.drag { border-color: var(--accent); background: var(--panel-2); color: var(--text); }
#drop strong { color: var(--text); }
#drop .formats { font-size: 12px; margin-top: 8px; }
/* Controls */
.controls {
position: sticky; top: 0; z-index: 5;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
padding: 14px 16px;
margin: 18px 0;
display: none;
gap: 14px;
flex-wrap: wrap;
align-items: center;
}
.controls.show { display: flex; }
button.ctl {
background: var(--accent-2);
color: white; border: none;
border-radius: 10px;
padding: 10px 16px;
font-size: 14px; font-weight: 600;
cursor: pointer;
}
button.ctl:hover { background: var(--accent); }
button.ctl.secondary { background: var(--panel-2); color: var(--text); border: 1px solid var(--border); }
button.ctl:disabled { opacity: .45; cursor: default; }
.field { display: flex; flex-direction: column; gap: 3px; font-size: 11px; color: var(--muted); }
.field select, .field input[type=range] { accent-color: var(--accent); }
.saved-tag { color: var(--accent); }
.voice-row { display: flex; gap: 6px; align-items: center; }
button.refresh { padding: 7px 11px; font-size: 15px; line-height: 1; }
#voiceFilter {
background: var(--panel-2); color: var(--text);
border: 1px solid var(--border); border-radius: 8px;
padding: 6px 8px; font-size: 12px; max-width: 240px; margin-bottom: 4px;
}
.vcount { color: var(--muted); font-size: 11px; }
optgroup { color: var(--muted); }
option { color: var(--text); }
#voiceHint {
display: none;
background: #2a2310; border: 1px solid #5c4a14; color: #ffd479;
border-radius: 10px; padding: 10px 14px; font-size: 13px; margin: 14px 0 0;
}
#voiceHint a { color: #ffe6a8; }
select {
background: var(--panel-2); color: var(--text);
border: 1px solid var(--border); border-radius: 8px;
padding: 7px 8px; font-size: 13px; max-width: 240px;
}
.rate-val { color: var(--text); font-variant-numeric: tabular-nums; }
/* Text view */
#status { color: var(--muted); font-size: 13px; margin: 10px 2px; min-height: 18px; }
#docTitle { font-size: 15px; font-weight: 600; margin: 4px 2px 0; }
#reader {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
padding: 28px 30px;
font-size: 18px;
display: none;
max-height: 65vh;
overflow-y: auto;
}
#reader.show { display: block; }
/* Structural styling */
.b-title { font-size: 27px; font-weight: 700; margin: 24px 0 10px; line-height: 1.3; }
.b-title:first-child { margin-top: 0; }
.b-sub { font-size: 21px; font-weight: 600; color: #c9d2e3; margin: 20px 0 8px; line-height: 1.35; }
.b-text { margin: 0 0 14px; }
.sent { cursor: pointer; border-radius: 4px; padding: 1px 2px; transition: background .1s; }
.sent:hover { background: var(--panel-2); }
.sent.active { background: var(--highlight); color: #fff; }
.err { color: #ff8080; }
/* Privacy / install panel — the first thing a new user should be able to check */
#about {
margin: 14px 0 0;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 12px;
padding: 12px 16px;
font-size: 13px;
color: var(--muted);
}
#about summary {
cursor: pointer; color: var(--text);
font-weight: 600; font-size: 13px;
}
#about .about-body { padding-top: 6px; }
#about p { margin: 8px 0; }
#about ul { margin: 6px 0; padding-left: 20px; }
#about li { margin: 3px 0; }
#about strong { color: var(--text); }
#about a { color: var(--accent); }
#about code {
background: var(--panel-2); border: 1px solid var(--border);
border-radius: 4px; padding: 1px 5px; font-size: 12px;
}
#about .fine { font-size: 12px; opacity: .8; }
footer { text-align: center; color: var(--muted); font-size: 12px; padding: 24px; }
kbd { background: var(--panel-2); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; font-size: 11px; }
/* ---------- Phone layout ---------- */
@media (max-width: 600px) {
header { padding: 12px 16px; flex-wrap: wrap; gap: 2px; }
header h1 { font-size: 17px; }
header .sub { display: none; }
.wrap { padding: 14px 14px calc(20px + env(safe-area-inset-bottom)); }
#drop { padding: 30px 16px; }
.desktop-only { display: none; }
.controls { position: static; gap: 12px; padding: 14px; }
/* Each control stacks to its own full-width row; buttons stay big & tappable. */
.field { flex: 1 1 100%; font-size: 12px; }
.controls > button.ctl { flex: 1 1 auto; }
button.ctl { padding: 13px 18px; font-size: 16px; }
button.refresh { flex: 0 0 auto; padding: 11px 14px; }
.voice-row { width: 100%; }
select, #voiceFilter { max-width: none; width: 100%; font-size: 16px; padding: 10px; }
input[type=range] { width: 100%; height: 30px; }
.vcount { font-size: 12px; }
#reader { padding: 20px 18px; font-size: 18px; max-height: none; }
.b-title { font-size: 23px; }
.b-sub { font-size: 19px; }
.sent { padding: 2px 2px; } /* slightly larger tap area per sentence */
footer { padding: 20px 16px; }
}
</style>
</head>
<body>
<header>
<h1>🎧 Audiobook Reader</h1>
<span class="sub">Drop a document, press play — your browser reads it aloud.</span>
</header>
<div class="wrap">
<div id="drop">
<strong>Tap to choose a file</strong><span class="desktop-only"> or drag one here</span>
<div class="formats">Supported: PDF · DOCX · TXT · Markdown | legacy .DOC not supported</div>
</div>
<input type="file" id="file" hidden
accept=".pdf,.docx,.txt,.md,.markdown,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,text/markdown" />
<details id="about">
<summary>🔒 Is this private? · How to install it</summary>
<div class="about-body">
<p><strong>Your documents never leave your device.</strong> Files are opened, read and
spoken entirely inside your browser. There is no server, no account, no sign-up,
no analytics, and no upload.</p>
<p><strong>You don't have to take our word for it.</strong> This page tells your browser
to block <em>every</em> outgoing network connection (<code>connect-src 'none'</code>).
Even if this app wanted to send your file somewhere, your browser would refuse to
let it. The PDF and Word readers are bundled in too — nothing is loaded from
anyone else's server.</p>
<p><strong>It works offline.</strong> After your first visit the whole app is saved on
your device. Switch on Airplane Mode and it still reads your books — which is the
simplest proof that nothing is being sent anywhere.</p>
<p><strong>Install it like an app:</strong></p>
<ul>
<li><strong>iPhone / iPad</strong> — open in Safari, tap Share, then <em>Add to Home Screen</em>.</li>
<li><strong>Android</strong> — Chrome menu, then <em>Install app</em>.</li>
<li><strong>Mac / Windows</strong> — Chrome or Edge, install icon in the address bar.</li>
</ul>
<p class="fine">The one thing that touches the network is downloading the app itself the
first time you open it — whoever hosts it sees that request, exactly like any other
website. Your documents are never part of it. Prefer to trust nobody?
<a href="https://github.com/Iffrit-coder/audiobook-reader">Read the source or host your own copy</a>.</p>
</div>
</details>
<div class="controls" id="controls">
<button class="ctl" id="play">▶ Play</button>
<button class="ctl secondary" id="stop" disabled>⏹ Stop</button>
<div class="field">
Voice <span class="saved-tag">· saved as default</span>
<input type="text" id="voiceFilter" placeholder="filter… e.g. jamie" />
<div class="voice-row">
<select id="voice"></select>
<button class="ctl secondary refresh" id="refreshVoices" title="Re-scan installed voices">↻</button>
</div>
<span id="voiceCount" class="vcount"></span>
</div>
<div class="field">
Speed <span class="rate-val" id="rateVal">1.0×</span>
<input type="range" id="rate" min="0.5" max="2" step="0.1" value="1" />
</div>
<div class="field">
Pitch
<input type="range" id="pitch" min="0" max="2" step="0.1" value="1" />
</div>
</div>
<div id="voiceHint"></div>
<div id="docTitle"></div>
<div id="status"></div>
<div id="reader"></div>
</div>
<footer>
Everything runs locally in your browser. Nothing is uploaded.
Tip: click any sentence to start reading from there. <kbd>Space</kbd> play/pause.
</footer>
<script>
// pdf.js worker
if (window.pdfjsLib) {
pdfjsLib.GlobalWorkerOptions.workerSrc = "vendor/pdf.worker.min.js";
}
const $ = (id) => document.getElementById(id);
const dropEl = $("drop"), fileEl = $("file"), controls = $("controls");
const readerEl = $("reader"), statusEl = $("status"), docTitleEl = $("docTitle");
const playBtn = $("play"), stopBtn = $("stop");
const voiceSel = $("voice"), rateEl = $("rate"), rateVal = $("rateVal"), pitchEl = $("pitch");
const voiceHint = $("voiceHint");
const voiceFilter = $("voiceFilter"), voiceCount = $("voiceCount");
const synth = window.speechSynthesis;
// Pause lengths (ms) inserted after the last sentence of a block.
const PAUSE = { title: 850, subtitle: 550, text: 300, beforeHeading: 500 };
let units = []; // [{ text, type, lastInBlock }]
let spanEls = []; // matching <span> elements
let idx = 0; // current unit index
let speaking = false, paused = false, inGap = false;
let pauseTimer = null, nextIndex = null;
let genId = 0; // bumped on every cancel; stale utterance handlers bail
let currentDocId = null; // identifies the loaded doc so progress maps to it
// ---------- Preferences (default voice / speed / pitch) ----------
const PREFS_KEY = "audiobookReaderPrefs";
let prefs = {};
try { prefs = JSON.parse(localStorage.getItem(PREFS_KEY)) || {}; } catch (_) { prefs = {}; }
if (prefs.rate) rateEl.value = prefs.rate;
if (prefs.pitch) pitchEl.value = prefs.pitch;
rateVal.textContent = parseFloat(rateEl.value).toFixed(1) + "×";
function savePrefs() {
const opt = voiceSel.selectedOptions[0];
prefs.voice = opt ? opt.dataset.name : prefs.voice;
prefs.rate = rateEl.value;
prefs.pitch = pitchEl.value;
localStorage.setItem(PREFS_KEY, JSON.stringify(prefs));
}
// ---------- Persist & restore the last document (IndexedDB) ----------
// The raw file bytes live in IndexedDB (it handles large PDFs); the reading
// position lives in localStorage. On launch we reload both automatically.
const DB_NAME = "audiobookReader", STORE = "docs", DOC_KEY = "lastDoc";
const PROG_KEY = "audiobookReaderProgress";
function idbOpen() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => req.result.createObjectStore(STORE);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
function idbReq(mode, fn) {
return idbOpen().then(db => new Promise((resolve, reject) => {
const tx = db.transaction(STORE, mode);
const r = fn(tx.objectStore(STORE));
tx.oncomplete = () => resolve(r && r.result);
tx.onerror = () => reject(tx.error);
}));
}
const idbPut = (key, val) => idbReq("readwrite", s => s.put(val, key));
const idbGet = (key) => idbReq("readonly", s => s.get(key));
const idbDel = (key) => idbReq("readwrite", s => s.delete(key));
const docId = (file) => `${file.name}:${file.size}`;
function saveProgress(i) {
if (!currentDocId) return;
try { localStorage.setItem(PROG_KEY, JSON.stringify({ docId: currentDocId, idx: i })); } catch (_) {}
}
function loadProgress() {
try { return JSON.parse(localStorage.getItem(PROG_KEY)); } catch (_) { return null; }
}
let lastProgSave = 0;
function maybeSaveProgress(i) { // throttle writes during playback
const t = Date.now();
if (t - lastProgSave > 2000) { lastProgSave = t; saveProgress(i); }
}
async function saveLastDoc(file) {
try {
const buf = await file.arrayBuffer();
await idbPut(DOC_KEY, { name: file.name, type: file.type, size: file.size, buf, savedAt: Date.now() });
} catch (_) {}
}
async function restoreLastDoc() {
let rec;
try { rec = await idbGet(DOC_KEY); } catch (_) { return; }
if (!rec || !rec.buf) return;
const file = new File([rec.buf], rec.name, { type: rec.type || "" });
await loadFile(file, { restoring: true });
if (!units.length) return;
const prog = loadProgress();
let resumed = "";
if (prog && prog.docId === currentDocId && prog.idx > 0 && prog.idx < units.length) {
idx = prog.idx;
highlight(idx);
resumed = " · ▶ resumes where you left off";
}
setStatus("📂 Restored “" + rec.name + ".” " + statusEl.textContent + resumed);
}
async function forgetLastDoc() {
stopSpeaking();
try { await idbDel(DOC_KEY); } catch (_) {}
try { localStorage.removeItem(PROG_KEY); } catch (_) {}
units = []; spanEls = []; idx = 0; currentDocId = null;
readerEl.innerHTML = "";
readerEl.classList.remove("show");
controls.classList.remove("show");
docTitleEl.textContent = "";
forgetBtn.style.display = "none";
setStatus("Saved document cleared — choose a new file to begin.");
}
// "Forget" control, revealed once a document is loaded.
const forgetBtn = document.createElement("button");
forgetBtn.textContent = "✕ Forget saved file";
forgetBtn.className = "ctl secondary";
forgetBtn.style.cssText = "display:none; font-size:12px; padding:6px 10px; margin:8px 2px 0;";
forgetBtn.addEventListener("click", forgetLastDoc);
docTitleEl.insertAdjacentElement("afterend", forgetBtn);
// ---------- Background / lock-screen playback ----------
// Continuous playback with the screen fully off is an OS-level limit for
// browser speech on iOS. These make it as resilient as the platform allows:
// a Wake Lock keeps the screen on while reading, a silent looping audio track
// holds an audio session, and MediaSession adds lock-screen / headphone /
// Now-Playing controls.
function silentWavURL() { // build a valid 1s silent WAV
const rate = 8000, n = rate, buf = new ArrayBuffer(44 + n), v = new DataView(buf);
const str = (o, s) => { for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i)); };
str(0, "RIFF"); v.setUint32(4, 36 + n, true); str(8, "WAVE"); str(12, "fmt ");
v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
v.setUint32(24, rate, true); v.setUint32(28, rate, true); v.setUint16(32, 1, true);
v.setUint16(34, 8, true); str(36, "data"); v.setUint32(40, n, true);
for (let i = 0; i < n; i++) v.setUint8(44 + i, 128); // 128 = silence (8-bit PCM)
return URL.createObjectURL(new Blob([buf], { type: "audio/wav" }));
}
let silentAudio = null, wakeLock = null;
function startAudioSession() {
try {
if (!silentAudio) {
silentAudio = new Audio(silentWavURL());
silentAudio.loop = true; silentAudio.preload = "auto";
silentAudio.setAttribute("playsinline", "");
}
const p = silentAudio.play();
if (p && p.catch) p.catch(() => {});
} catch (_) {}
}
function stopAudioSession() { try { silentAudio && silentAudio.pause(); } catch (_) {} }
async function acquireWakeLock() {
try { if ("wakeLock" in navigator && !wakeLock) wakeLock = await navigator.wakeLock.request("screen"); } catch (_) {}
}
function releaseWakeLock() { try { wakeLock && wakeLock.release(); } catch (_) {} wakeLock = null; }
function headingAfter(i) { for (let k = i + 1; k < units.length; k++) if (units[k].type !== "text") return k; return null; }
function headingBefore(i) { for (let k = i - 1; k >= 0; k--) if (units[k].type !== "text") return k; return null; }
function setMediaState(state) {
if ("mediaSession" in navigator) { try { navigator.mediaSession.playbackState = state; } catch (_) {} }
}
function setupMediaSession(title) {
if (!("mediaSession" in navigator)) return;
try {
navigator.mediaSession.metadata = new MediaMetadata({
title: title || "Document", artist: "Audiobook Reader", album: "On-device narration",
});
const H = (name, fn) => { try { navigator.mediaSession.setActionHandler(name, fn); } catch (_) {} };
H("play", () => { if (!speaking) startSpeaking(); else if (paused) resumeSpeaking(); });
H("pause", () => { if (speaking && !paused) pauseSpeaking(); });
H("stop", () => stopSpeaking());
H("previoustrack", () => { const h = headingBefore(idx); restartFrom(h == null ? Math.max(0, idx - 1) : h); });
H("nexttrack", () => { const h = headingAfter(idx); if (h != null) restartFrom(h); });
H("seekbackward", () => restartFrom(Math.max(0, idx - 1)));
H("seekforward", () => restartFrom(Math.min(units.length - 1, idx + 1)));
} catch (_) {}
}
// ---------- File handling ----------
dropEl.addEventListener("click", () => fileEl.click());
fileEl.addEventListener("change", (e) => { if (e.target.files[0]) loadFile(e.target.files[0]); });
["dragover", "dragenter"].forEach(ev =>
dropEl.addEventListener(ev, (e) => { e.preventDefault(); dropEl.classList.add("drag"); }));
["dragleave", "drop"].forEach(ev =>
dropEl.addEventListener(ev, (e) => { e.preventDefault(); dropEl.classList.remove("drag"); }));
dropEl.addEventListener("drop", (e) => { if (e.dataTransfer.files[0]) loadFile(e.dataTransfer.files[0]); });
function setStatus(msg, isErr) {
statusEl.innerHTML = isErr ? `<span class="err">${msg}</span>` : msg;
}
async function loadFile(file, opts = {}) {
stopSpeaking();
const name = file.name;
const ext = name.split(".").pop().toLowerCase();
docTitleEl.textContent = "📄 " + name;
setStatus("Reading file…");
readerEl.classList.remove("show");
controls.classList.remove("show");
try {
let blocks = [];
if (ext === "pdf") blocks = await extractPdf(file);
else if (ext === "docx") blocks = await extractDocx(file);
else if (ext === "md" || ext === "markdown") blocks = extractMarkdown(await file.text());
else if (ext === "txt") blocks = extractPlainText(await file.text());
else if (ext === "doc")
throw new Error("Legacy .doc files aren't supported. Re-save as .docx or .pdf and try again.");
else throw new Error("Unsupported file type: ." + ext);
blocks = blocks.filter(b => b.text && b.text.trim());
if (!blocks.length) throw new Error("No readable text found (a scanned/image-only PDF has no text layer).");
buildReader(blocks);
const words = units.reduce((a, u) => a + u.text.split(/\s+/).length, 0);
const heads = blocks.filter(b => b.type !== "text").length;
setStatus(`Loaded ${units.length} sentences · ${heads} heading${heads === 1 ? "" : "s"} · ~${words.toLocaleString()} words · ~${Math.ceil(words / 150)} min at 1×.`);
controls.classList.add("show");
readerEl.classList.add("show");
currentDocId = docId(file);
forgetBtn.style.display = "inline-block";
setupMediaSession(file.name);
if (!opts.restoring) { saveLastDoc(file); saveProgress(0); } // remember this file for next launch
} catch (err) {
setStatus(err.message || String(err), true);
}
}
// ---------- Extractors → array of { type:'title'|'subtitle'|'text', text } ----------
async function extractPdf(file) {
const buf = await file.arrayBuffer();
const pdf = await pdfjsLib.getDocument({ data: buf }).promise;
const numPages = pdf.numPages;
const lines = []; // { text, size, page }
for (let p = 1; p <= numPages; p++) {
setStatus(`Reading PDF… page ${p}/${numPages}`);
const page = await pdf.getPage(p);
const content = await page.getTextContent();
let items = [], size = 0;
const flush = () => {
const text = items.join(" ").replace(/\s+/g, " ").trim();
if (text) lines.push({ text, size, page: p });
items = []; size = 0;
};
for (const it of content.items) {
if (it.str) items.push(it.str);
const sz = Math.round((it.transform && it.transform[3]) || it.height || 0);
if (sz) size = Math.max(size, sz);
if (it.hasEOL) flush();
}
flush();
}
// Determine body font size = the size that covers the most characters.
const tally = {};
lines.forEach(l => { tally[l.size] = (tally[l.size] || 0) + l.text.length; });
let body = 0, most = -1;
for (const s in tally) if (tally[s] > most) { most = tally[s]; body = +s; }
// ---- Detect repeated running headers / footers / download stamps ----
// Normalize so page numbers and dates don't defeat matching across pages.
const norm = (t) => t.toLowerCase().replace(/\d+/g, " ").replace(/[^a-z ]+/g, " ").replace(/\s+/g, " ").trim();
const SOURCE_RX = /(download|gutenberg|e-?book|copyright|©|retriev|accessed|https?|www\.|all rights reserved|licen[sc]e)/i;
const stats = {}; // norm -> { pages:Set, minSize }
lines.forEach(l => {
const n = norm(l.text);
if (n.length < 4) return;
const s = stats[n] || (stats[n] = { pages: new Set(), minSize: Infinity });
s.pages.add(l.page);
s.minSize = Math.min(s.minSize, l.size);
});
// Boilerplate = recurs on a large share of pages AND is either small type
// (the user's footer is "small text") or an obvious source/download phrase.
const threshold = Math.max(3, Math.ceil(numPages * 0.4));
const boilerplate = new Set(
Object.keys(stats).filter((n) => {
const s = stats[n];
if (s.pages.size < threshold) return false;
return (body && s.minSize < body) || SOURCE_RX.test(n);
})
);
// Standalone page numbers ("12", "Page 12", "- 12 -") are noise too.
const isPageNumber = (t) => /^[\s.\-–—|]*(?:page\s*)?\d{1,4}[\s.\-–—|]*$/i.test(t);
const classify = (size) => {
if (!body) return "text";
if (size >= body * 1.45) return "title";
if (size >= body * 1.15) return "subtitle";
return "text";
};
// Merge consecutive body lines into paragraphs; each heading is its own block.
const blocks = [];
let para = [];
const flushPara = () => { if (para.length) { blocks.push({ type: "text", text: para.join(" ") }); para = []; } };
for (const l of lines) {
if (isPageNumber(l.text) || boilerplate.has(norm(l.text))) continue; // drop footer/header/page-no
const t = classify(l.size);
if (t === "text") para.push(l.text);
else { flushPara(); blocks.push({ type: t, text: l.text }); }
}
flushPara();
return blocks;
}
async function extractDocx(file) {
const buf = await file.arrayBuffer();
// convertToHtml preserves heading structure (mammoth maps Word styles → h1/h2/...).
const res = await mammoth.convertToHtml({ arrayBuffer: buf });
const doc = new DOMParser().parseFromString(res.value, "text/html");
const blocks = [];
doc.body.querySelectorAll("h1, h2, h3, h4, h5, h6, p, li").forEach(el => {
const text = el.textContent.trim();
if (!text) return;
const tag = el.tagName.toLowerCase();
let type = "text";
if (tag === "h1") type = "title";
else if (tag[0] === "h") type = "subtitle"; // h2–h6
blocks.push({ type, text });
});
return blocks;
}
function cleanMd(s) {
return s
.replace(/!\[[^\]]*\]\([^)]*\)/g, "") // images
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1") // links → text
.replace(/[*_~`]+/g, "") // emphasis / code marks
.replace(/\s+/g, " ")
.trim();
}
function extractMarkdown(raw) {
const lines = raw.replace(/\r/g, "").split("\n");
const blocks = [];
let para = [];
const flushPara = () => { if (para.length) { blocks.push({ type: "text", text: cleanMd(para.join(" ")) }); para = []; } };
for (const line of lines) {
const h = line.match(/^(#{1,6})\s+(.+?)\s*#*$/);
if (h) { flushPara(); blocks.push({ type: h[1].length === 1 ? "title" : "subtitle", text: cleanMd(h[2]) }); }
else if (!line.trim()) flushPara();
else para.push(line.trim());
}
flushPara();
return blocks;
}
function extractPlainText(raw) {
const chunks = raw.replace(/\r/g, "").split(/\n{2,}/);
const blocks = [];
let firstHeading = true;
for (let chunk of chunks) {
chunk = chunk.replace(/\n/g, " ").replace(/\s+/g, " ").trim();
if (!chunk) continue;
// Heuristic: a short standalone line with no terminal punctuation reads like a heading.
const looksHeading = chunk.length < 60 && !/[.?!,;:]$/.test(chunk) && chunk.split(" ").length <= 10;
if (looksHeading) {
blocks.push({ type: firstHeading ? "title" : "subtitle", text: chunk });
firstHeading = false;
} else {
blocks.push({ type: "text", text: chunk });
}
}
return blocks;
}
// ---------- Sentence splitting + render ----------
// Loss-less: split only on . ! ? that are followed by whitespace/end, so
// decimals (3.5), abbreviations, and symbols are never broken or dropped.
function splitSentences(text) {
text = text.replace(/\s+/g, " ").trim();
if (!text) return [];
const out = [];
const re = /[.!?]+(?=\s|$)/g;
let last = 0, m;
while ((m = re.exec(text)) !== null) {
const end = m.index + m[0].length;
out.push(text.slice(last, end).trim());
last = end;
}
if (last < text.length) out.push(text.slice(last).trim());
return out.filter(Boolean);
}
// ---------- Math / symbol → speech ----------
// Applied ONLY to the spoken string; the on-screen text keeps real symbols.
const MATH_SYM = {
"≤": "less than or equal to", "≥": "greater than or equal to",
"≠": "not equal to", "≈": "approximately equal to", "≅": "approximately equal to",
"≡": "equivalent to", "≪": "much less than", "≫": "much greater than",
"±": "plus or minus", "∓": "minus or plus",
"×": "times", "÷": "divided by", "⋅": "times", "∗": "times", "−": "minus",
"√": "the square root of", "∛": "the cube root of",
"∞": "infinity", "∝": "proportional to",
"∑": "the sum of", "∏": "the product of", "∫": "the integral of",
"∂": "the partial derivative of", "∇": "del", "∆": "delta", "Δ": "delta",
"∈": "in", "∉": "not in", "⊂": "subset of", "⊆": "subset of or equal to",
"⊃": "superset of", "⊇": "superset of or equal to",
"∪": "union", "∩": "intersection", "∅": "the empty set",
"∀": "for all", "∃": "there exists", "∄": "there does not exist",
"∴": "therefore", "∵": "because", "⊥": "perpendicular to", "∥": "parallel to",
"→": "to", "⇒": "implies", "↔": "if and only if", "⇔": "if and only if", "←": "from",
"°": "degrees", "′": "prime", "″": "double prime",
"π": "pi", "τ": "tau", "θ": "theta", "λ": "lambda", "μ": "mu", "µ": "mu",
"σ": "sigma", "Σ": "sigma", "α": "alpha", "β": "beta", "γ": "gamma",
"δ": "delta", "ε": "epsilon", "ω": "omega", "Ω": "omega", "φ": "phi", "ϕ": "phi",
"ρ": "rho", "η": "eta", "ξ": "xi", "ζ": "zeta", "ψ": "psi", "χ": "chi",
};
const MATH_FRAC = {
"½": "one half", "⅓": "one third", "⅔": "two thirds", "¼": "one quarter",
"¾": "three quarters", "⅕": "one fifth", "⅖": "two fifths", "⅗": "three fifths",
"⅘": "four fifths", "⅙": "one sixth", "⅚": "five sixths", "⅛": "one eighth",
"⅜": "three eighths", "⅝": "five eighths", "⅞": "seven eighths",
"⅐": "one seventh", "⅑": "one ninth", "⅒": "one tenth",
};
const SUP = { "⁰": "0", "¹": "1", "⁴": "4", "⁵": "5", "⁶": "6", "⁷": "7", "⁸": "8", "⁹": "9", "ⁿ": "n" };
const SUB = { "₀": "0", "₁": "1", "₂": "2", "₃": "3", "₄": "4", "₅": "5", "₆": "6", "₇": "7", "₈": "8", "₉": "9" };
function mathToSpeech(s) {
// Caret exponents: x^2 → "x squared", x^n → "x to the power of n"
s = s.replace(/\^\s*2\b/g, " squared").replace(/\^\s*3\b/g, " cubed");
s = s.replace(/([A-Za-z0-9)\]])\s*\^\s*\{?\s*(-?\d+(?:\.\d+)?|[A-Za-z])\s*\}?/g, "$1 to the power of $2");
// Multi-char ASCII operators (before single-char ones)
s = s.replace(/>=/g, " greater than or equal to ")
.replace(/<=/g, " less than or equal to ")
.replace(/!=/g, " not equal to ")
.replace(/==/g, " equals ")
.replace(/=>/g, " implies ")
.replace(/->/g, " to ");
// Number ranges with dashes: 10–20 → "10 to 20"
s = s.replace(/(\d)\s*[–—]\s*(\d)/g, "$1 to $2");
// Division by slash — but leave dates/paths (runs with 2+ slashes) alone
s = s.replace(/\d+(?:\.\d+)?(?:\s*\/\s*\d+(?:\.\d+)?)+/g,
(m) => /\/.*\//.test(m) ? m : m.replace(/\s*\/\s*/, " divided by "));
s = s.replace(/(\d)\s*\*\s*(\d)/g, "$1 times $2");
s = s.replace(/(\d)\s*\+\s*(\d)/g, "$1 plus $2").replace(/ \+ /g, " plus ");
// Single-char comparison operators
s = s.replace(/</g, " less than ").replace(/>/g, " greater than ").replace(/=/g, " equals ");
s = s.replace(/%/g, " percent ");
// Superscripts / subscripts
s = s.replace(/²/g, " squared").replace(/³/g, " cubed");
s = s.replace(/[⁰¹⁴⁵⁶⁷⁸⁹ⁿ]+/g, (m) => " to the power of " + [...m].map(c => SUP[c] || "").join(""));
s = s.replace(/[₀₁₂₃₄₅₆₇₈₉]+/g, (m) => " sub " + [...m].map(c => SUB[c] || "").join(""));
// Vulgar fractions
for (const [sym, word] of Object.entries(MATH_FRAC)) s = s.split(sym).join(` ${word} `);
// Remaining symbols / Greek letters
for (const [sym, word] of Object.entries(MATH_SYM)) s = s.split(sym).join(` ${word} `);
return s.replace(/\s+([,.;:!?])/g, "$1").replace(/\s+/g, " ").trim();
}
function buildReader(blocks) {
units = []; spanEls = []; readerEl.innerHTML = "";
blocks.forEach(b => {
const sents = splitSentences(b.text);
if (!sents.length) return;
let container;
if (b.type === "title") { container = document.createElement("div"); container.className = "b-title"; }
else if (b.type === "subtitle") { container = document.createElement("div"); container.className = "b-sub"; }
else { container = document.createElement("p"); container.className = "b-text"; }
sents.forEach((s, si) => {
const myIndex = units.length;
const span = document.createElement("span");
span.className = "sent";
span.textContent = s + " ";
span.addEventListener("click", () => restartFrom(myIndex));
container.appendChild(span);
units.push({ text: s, type: b.type, lastInBlock: si === sents.length - 1 });
spanEls.push(span);
});
readerEl.appendChild(container);
});
idx = 0;
}
// ---------- Voices ----------
let allVoices = [];
// A voice counts as enhanced if its NAME says so (macOS: "Jamie (Enhanced)")
// OR its voiceURI marks it (iOS: "com.apple.voice.enhanced.en-GB.Daniel").
const isEnhanced = (v) => {
const name = (v && v.name) || "";
const uri = (v && v.voiceURI) || "";
return /\((Enhanced|Premium)\)/i.test(name) || /\b(enhanced|premium)\b/i.test(name) ||
/(enhanced|premium)/i.test(uri);
};
// Build the <select> (grouped: Enhanced/Premium pinned on top), honoring the filter box.
function renderVoiceOptions() {
const filter = voiceFilter.value.trim().toLowerCase();
const keep = voiceSel.selectedOptions[0]?.dataset.name;
voiceSel.innerHTML = "";
const enh = [], eng = [], other = [];
allVoices.forEach((v, i) => {
if (filter && !`${v.name} ${v.lang}`.toLowerCase().includes(filter)) return;
const e = { v, i };
if (isEnhanced(v)) enh.push(e);
else if (v.lang.toLowerCase().startsWith("en")) eng.push(e);
else other.push(e);
});
const addGroup = (label, arr) => {
if (!arr.length) return;
const og = document.createElement("optgroup");
og.label = label;
arr.forEach(({ v, i }) => {
const enh = isEnhanced(v);
const opt = document.createElement("option");
opt.value = i;
opt.dataset.name = v.name;
opt.dataset.enhanced = enh ? "1" : "";
// Tag enhanced voices whose name doesn't already say so (the iOS case).
const tag = enh && !/\((Enhanced|Premium)\)/i.test(v.name) ? " — Enhanced" : "";
opt.textContent = `${v.name} (${v.lang})${tag}`;
og.appendChild(opt);
});
voiceSel.appendChild(og);
};
addGroup("★ Enhanced & Premium", enh);
addGroup("English", eng);
addGroup("Other languages", other);
// Keep the current selection visible if it survived the filter.
if (keep) {
const m = [...voiceSel.options].find(o => o.dataset.name === keep);
if (m) voiceSel.value = m.value;
}
}
function restoreVoiceSelection() {
const opts = [...voiceSel.options];
if (!opts.length) return;
if (prefs.voice) {
const m = opts.find(o => o.dataset.name === prefs.voice);
if (m) { voiceSel.value = m.value; return; }
}
// First-run default: best English voice available → enhanced first.
const enEnh = opts.find(o => o.dataset.enhanced === "1" && /\(en/i.test(o.textContent));
const anyEnh = opts.find(o => o.dataset.enhanced === "1");
const anyEn = opts.find(o => /\(en/i.test(o.textContent));
const pick = enEnh || anyEnh || anyEn || opts[0];
if (pick) voiceSel.value = pick.value;
}
function updateVoiceCount() {
const n = allVoices.length;
const e = allVoices.filter(isEnhanced).length;
voiceCount.textContent = n
? `${n} voices available${e ? ` · ${e} enhanced/premium` : " · none enhanced"}`
: "loading voices…";
}
let voiceSig = "";
function populateVoices() {
const voices = synth.getVoices();
if (!voices.length) return;
// Skip needless rebuilds (onvoiceschanged can fire repeatedly), which would
// otherwise disrupt the open dropdown / active filter while the user is choosing.
const sig = voices.length + "|" + voices.map(v => v.name).join(",");
if (sig === voiceSig) return;
voiceSig = sig;
allVoices = voices;
renderVoiceOptions();
restoreVoiceSelection();
updateVoiceCount();
}
voiceFilter.addEventListener("input", renderVoiceOptions);
// Detect browsers that under-expose macOS system voices (Chromium-based:
// Chrome, Comet, Edge, Brave, Arc…). Safari surfaces all installed voices.
function isSafari() {
const ua = navigator.userAgent;
return /^((?!chrome|chromium|crios|edg|android).)*safari/i.test(ua);
}
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
function updateVoiceHint() {
const voices = synth.getVoices();
const hasPremium = voices.some(isEnhanced);
if (voices.length && !hasPremium) {
voiceHint.innerHTML = isIOS
? '⚠︎ No <strong>Enhanced</strong> voices detected. On iPhone/iPad, download one in ' +
'<strong>Settings → Accessibility → Spoken Content → Voices → English</strong> ' +
'(pick a voice marked Enhanced or Premium), then reload this page and tap ↻. ' +
'Note: iOS doesn’t always expose its high-quality voices to web apps, and every iOS ' +
'browser shares the same engine — so switching browsers won’t change this.'
: '⚠︎ No <strong>Enhanced/Premium</strong> voices are visible in this browser. On macOS, ' +
'<strong>Safari exposes only a limited set without them</strong>; <strong>Chromium-based ' +
'browsers (Comet, Chrome, Edge) expose the full system list</strong> including voices like ' +
'Jamie (Enhanced). Open this page in one of those. ' +
'(Download voices via System Settings → Accessibility → Spoken Content → Manage Voices.)';
voiceHint.style.display = "block";
} else {
voiceHint.style.display = "none";
}
}
// Voices often load asynchronously; poll briefly until they appear.
let voiceTries = 0;
function ensureVoices() {
populateVoices();
updateVoiceHint();
if (!synth.getVoices().length && voiceTries++ < 20) setTimeout(ensureVoices, 250);
}
ensureVoices();
synth.onvoiceschanged = () => { populateVoices(); updateVoiceHint(); };
$("refreshVoices").addEventListener("click", () => {
voiceTries = 0;
ensureVoices();
});
voiceSel.addEventListener("change", savePrefs);
rateEl.addEventListener("input", () => { rateVal.textContent = parseFloat(rateEl.value).toFixed(1) + "×"; });
rateEl.addEventListener("change", savePrefs);
pitchEl.addEventListener("change", savePrefs);
// ---------- Speech ----------
function speakFrom(i) {
if (i >= units.length) { stopSpeaking(); setStatus("✓ Finished."); return; }
idx = i;
const gen = genId;
const u = new SpeechSynthesisUtterance(mathToSpeech(units[i].text));
const voices = synth.getVoices();
const v = voices[parseInt(voiceSel.value, 10)];
if (v) u.voice = v;
u.rate = parseFloat(rateEl.value);
u.pitch = parseFloat(pitchEl.value);
u.onstart = () => { if (gen === genId) { highlight(i); maybeSaveProgress(i); } };
u.onend = () => onUtteranceEnd(i, gen);
u.onerror = () => onUtteranceEnd(i, gen);
synth.speak(u);
}
function onUtteranceEnd(i, gen) {
// Ignore events from utterances that were superseded by a cancel.
if (gen !== genId || !speaking) return;
if (units[i].lastInBlock) {
// Pause proportionally; a bit longer if the next block is a heading.
let ms = PAUSE[units[i].type] || PAUSE.text;
const next = units[i + 1];
if (next && next.type !== "text") ms = Math.max(ms, PAUSE.beforeHeading);
inGap = true; nextIndex = i + 1;
pauseTimer = setTimeout(() => {
pauseTimer = null;
if (paused) return; // resume() will continue the gap
inGap = false;
const n = nextIndex; nextIndex = null;
if (speaking) speakFrom(n);
}, ms);
} else {
speakFrom(i + 1);
}
}
function highlight(i) {
spanEls.forEach(s => s.classList.remove("active"));
const el = spanEls[i];
if (el) {
el.classList.add("active");
el.scrollIntoView({ block: "center", behavior: "smooth" });
}
}
function startSpeaking() {
if (!units.length) return;
speaking = true; paused = false;
playBtn.textContent = "⏸ Pause";
stopBtn.disabled = false;
startAudioSession(); acquireWakeLock(); setMediaState("playing");
speakFrom(idx);
}
function pauseSpeaking() {
paused = true;
playBtn.textContent = "▶ Resume";
if (inGap) { clearTimeout(pauseTimer); pauseTimer = null; } // hold inside a gap
else synth.pause();
setMediaState("paused"); releaseWakeLock(); saveProgress(idx);
}
function resumeSpeaking() {
paused = false;
playBtn.textContent = "⏸ Pause";
startAudioSession(); acquireWakeLock(); setMediaState("playing");
if (inGap) { inGap = false; const n = nextIndex; nextIndex = null; speakFrom(n); }
else synth.resume();
}
function stopSpeaking() {
speaking = false; paused = false; inGap = false; nextIndex = null;
clearTimeout(pauseTimer); pauseTimer = null;
genId++; // invalidate any in-flight utterance handlers
synth.cancel();
playBtn.textContent = "▶ Play";
stopBtn.disabled = true;
spanEls.forEach(s => s.classList.remove("active"));
stopAudioSession(); releaseWakeLock(); setMediaState("none");
}
function restartFrom(i) {
clearTimeout(pauseTimer); pauseTimer = null;
inGap = false; nextIndex = null;