forked from luzhenhua/NCE-Flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlesson.js
More file actions
executable file
·2428 lines (2231 loc) · 96.4 KB
/
lesson.js
File metadata and controls
executable file
·2428 lines (2231 loc) · 96.4 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
/**
* NCE Flow · lesson.js · iOS-Optimized Edition
*/
(() => {
// --------------------------
// 工具 & 解析
// --------------------------
const LINE_RE = /^((?:\[\d+:\d+(?:\.\d+)?\])+)(.*)$/;
const TIME_RE = /\[(\d+):(\d+(?:\.\d+)?)\]/g;
const META_RE = /^\[(al|ar|ti|by):(.+)\]$/i;
function timeTagsToSeconds(tags) {
const m = /\[(\d+):(\d+(?:\.\d+)?)\]/.exec(tags);
if (!m) return 0;
return parseInt(m[1], 10) * 60 + parseFloat(m[2]);
}
function hasCJK(s) { return /[\u3400-\u9FFF\uF900-\uFAFF]/.test(s) }
async function fetchText(url) { const r = await fetch(url); if (!r.ok) throw new Error('Fetch failed ' + url); return await r.text(); }
async function loadLrc(url) {
const text = await fetchText(url);
const rows = text.replace(/\r/g, '').split('\n');
const meta = { al: '', ar: '', ti: '', by: '' };
const items = [];
for (let i = 0; i < rows.length; i++) {
const raw = rows[i].trim(); if (!raw) continue;
const mm = raw.match(META_RE); if (mm) { meta[mm[1].toLowerCase()] = mm[2].trim(); continue; }
const m = raw.match(LINE_RE); if (!m) continue;
const tags = m[1];
const start = timeTagsToSeconds(tags);
let body = m[2].trim();
let en = body, cn = '';
if (body.includes('|')) { const parts = body.split('|'); en = parts[0].trim(); cn = (parts[1] || '').trim(); }
else if (i + 1 < rows.length) {
const m2 = rows[i + 1].trim().match(LINE_RE);
if (m2 && m2[1] === tags) {
const text2 = m2[2].trim();
if (hasCJK(text2)) { cn = text2; i++; }
}
}
items.push({ start, en, cn });
}
for (let i = 0; i < items.length; i++) items[i].end = i + 1 < items.length ? items[i + 1].start : 0;
return { meta, items };
}
function qs(sel) { return document.querySelector(sel); }
function once(target, type, timeoutMs = 2000) {
return new Promise((resolve, reject) => {
let to = 0;
const on = (e) => { cleanup(); resolve(e); };
const cleanup = () => { target.removeEventListener(type, on); if (to) clearTimeout(to); };
target.addEventListener(type, on, { once: true });
if (timeoutMs > 0) to = setTimeout(() => { cleanup(); reject(new Error(type + ' timeout')); }, timeoutMs);
});
}
const raf = (cb) => requestAnimationFrame(cb);
const raf2 = (cb) => requestAnimationFrame(() => requestAnimationFrame(cb));
// iOS / iPadOS / 触屏 Mac Safari
const ua = navigator.userAgent || '';
const isIOSLike = /iPad|iPhone|iPod/.test(ua) || (/Macintosh/.test(ua) && 'ontouchend' in document);
// --------------------------
// 主流程
// --------------------------
document.addEventListener('DOMContentLoaded', () => {
try { if ('scrollRestoration' in history) history.scrollRestoration = 'manual'; } catch (_) { }
window.scrollTo(0, 0);
let hash = decodeURIComponent(location.hash.slice(1));
if (!hash) { location.href = 'book.html'; return; }
// 支持 hash 中的 query 参数 (e.g., #NCE1/1?line=10)
let queryParams = {};
if (hash.includes('?')) {
const parts = hash.split('?');
hash = parts[0]; // 重置 hash 为纯路径
const search = parts[1];
if (search) {
search.split('&').forEach(pair => {
const [k, v] = pair.split('=');
if (k) queryParams[decodeURIComponent(k)] = decodeURIComponent(v || '');
});
}
}
const [book, ...rest] = hash.split('/');
const base = rest.join('/');
const inModern = /\/modern\//.test(location.pathname);
const prefix = inModern ? '../' : '';
const mp3 = `${prefix}${book}/${base}.mp3`;
const lrc = `${prefix}${book}/${base}.lrc`;
const titleEl = qs('#lessonTitle');
const subEl = qs('#lessonSub');
const listEl = qs('#sentences');
const audio = qs('#player');
const backLink = qs('#backLink');
const settingsBtn = qs('#settingsBtn');
const settingsOverlay = qs('#settingsOverlay');
const settingsPanel = qs('#settingsPanel');
const settingsClose = qs('#settingsClose');
const settingsDone = qs('#settingsDone');
const autoStopOverlay = qs('#autoStopOverlay');
const autoStopPanel = qs('#autoStopPanel');
const autoStopClose = qs('#autoStopClose');
const autoStopCancel = qs('#autoStopCancel');
const autoStopSave = qs('#autoStopSave');
const autoStopOn = qs('#autoStopOn');
const autoStopOff = qs('#autoStopOff');
const autoStopCountInput = qs('#autoStopCount');
const prevLessonLink = qs('#prevLesson');
const nextLessonLink = qs('#nextLesson');
const speedButton = qs('#speed');
const backToTopBtn = qs('#backToTop');
// --------------------------
// 移动端浏览器:自动隐藏上下栏(非 PWA)
// --------------------------
(function initAutoHideBars() {
try {
const isStandalone = (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) || (window.navigator && window.navigator.standalone === true);
const isCoarse = window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
if (isStandalone || !isCoarse) return;
const body = document.body;
if (!body) return;
let hidden = false;
let lastY = window.scrollY || 0;
let idleTimer = 0;
const HIDE_CLASS = 'ui-bars-hidden';
const show = () => {
if (hidden) { body.classList.remove(HIDE_CLASS); hidden = false; }
resetIdle();
};
const hide = () => {
const y = window.scrollY || 0;
if (y < 40) return;
if (!hidden) { body.classList.add(HIDE_CLASS); hidden = true; }
};
const resetIdle = () => {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(() => hide(), 2200);
};
const onScroll = () => {
const y = window.scrollY || 0;
const dy = y - lastY;
if (Math.abs(dy) < 8) { resetIdle(); lastY = y; return; }
if (dy > 0) hide(); else show();
lastY = y;
};
window.addEventListener('scroll', onScroll, { passive: true });
['touchstart', 'pointerdown'].forEach(t => document.addEventListener(t, show, { passive: true }));
document.addEventListener('focusin', show, { passive: true });
resetIdle();
} catch (_) { }
})();
// 本地存储键
const RECENT_KEY = 'nce_recents';
const LASTPOS_KEY = 'nce_lastpos';
const SENTENCE_FAV_KEY = 'nce_sentence_favs_v1';
const MODE_KEY = 'readMode';
const FOLLOW_KEY = 'autoFollow';
const AFTER_PLAY_KEY = 'afterPlay';
const REVEALED_SENTENCES_KEY = 'nce_revealed_sentences';
const SKIP_INTRO_KEY = 'skipIntro';
const SHADOW_REPEAT_KEY = 'shadowRepeatCount';
const SHADOW_GAP_KEY = 'shadowGapMode';
const AUTO_STOP_ENABLED_KEY = 'autoStopEnabled';
const AUTO_STOP_COUNT_KEY = 'autoStopCount';
const AUTO_NEXT_PLAYED_KEY = 'nce_auto_next_played_lessons';
function loadSentenceFavs() {
try {
const raw = localStorage.getItem(SENTENCE_FAV_KEY);
const arr = raw ? JSON.parse(raw) : [];
if (!Array.isArray(arr)) return [];
return arr.filter(x => x && typeof x.id === 'string' && typeof x.en === 'string');
} catch (_) { return []; }
}
function saveSentenceFavs(arr) {
try { localStorage.setItem(SENTENCE_FAV_KEY, JSON.stringify(arr || [])); } catch (_) { }
}
function sentenceFavId(i) { return `${book}/${base}::${i}`; }
// 状态
let items = [];
let idx = -1;
let segmentEnd = 0;
let segmentTimer = 0;
let segmentRaf = 0;
let isScheduling = false;
let scheduleTime = 0;
let internalPause = false;
let segmentStartWallclock = 0;
let prevLessonHref = '';
let nextLessonHref = '';
let _lastSavedAt = 0;
let loopReplayPending = false; // 标记是否正在等待循环重播
let playSeq = 0; // 防止异步 seek 回调串线
// iOS 特有状态
let iosUnlocked = false; // 是否已“解锁音频”
let iosUnlockPauseTimer = 0; // 解锁用的延迟 pause(可取消)
let metadataReady = false; // 是否已 loadedmetadata
let _userVolume = Math.max(0, Math.min(1, audio.volume || 1));
// 音频 seek 兼容:当服务器不支持 Range 时,回退为 Blob URL(可在本地 http.server 正常点读)
let audioBlobUrl = '';
let audioBlobPromise = null;
let usingBlobSrc = false;
let warnedNoRange = false;
// 句子清单(收藏)
let sentenceFavs = loadSentenceFavs();
let sentenceFavSet = new Set(sentenceFavs.map(x => x.id));
// 速率
const rates = [1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 0.75, 1.0];
const DEFAULT_RATE = 1.0;
let savedRate = parseFloat(localStorage.getItem('audioPlaybackRate'));
if (isNaN(savedRate) || !rates.includes(savedRate)) savedRate = DEFAULT_RATE;
let currentRateIndex = Math.max(0, rates.indexOf(savedRate));
// 读取模式/跟随/播完后
let readMode = localStorage.getItem(MODE_KEY) || 'continuous'; // 'continuous' | 'single' | 'listen' | 'shadow'
const storedAutoFollow = localStorage.getItem(FOLLOW_KEY);
let autoFollow = storedAutoFollow === null ? true : storedAutoFollow === 'true'; // 默认开启自动跟随
let afterPlay = localStorage.getItem(AFTER_PLAY_KEY) || 'none'; // 'none' | 'single' | 'all' | 'next'
let revealedSentences = new Set(); // 听读模式下已显示的句子索引
let skipIntro = localStorage.getItem(SKIP_INTRO_KEY) === 'true'; // 是否跳过开头
let firstContentIndex = 0; // 第一句正文的索引
let shadowStartIndex = 0; // 跟读模式的正文起点
const SHADOW_GAP_RATIOS = { short: 0.8, medium: 1.0, long: 1.3 };
function normalizeShadowRepeat(value) {
const n = parseInt(value, 10);
if (!Number.isFinite(n)) return 2;
return Math.min(9, Math.max(1, n));
}
function normalizeAutoStopCount(value) {
const n = parseInt(value, 10);
if (!Number.isFinite(n)) return 3;
return Math.min(50, Math.max(1, n));
}
function getAutoNextPlayedLessons() {
try {
const raw = sessionStorage.getItem(AUTO_NEXT_PLAYED_KEY);
const n = parseInt(raw, 10);
return Number.isFinite(n) && n >= 0 ? n : 0;
} catch (_) { return 0; }
}
function setAutoNextPlayedLessons(n) {
try { sessionStorage.setItem(AUTO_NEXT_PLAYED_KEY, String(Math.max(0, n | 0))); } catch (_) { }
}
function resetAutoNextPlayedLessons() {
try { sessionStorage.removeItem(AUTO_NEXT_PLAYED_KEY); } catch (_) { }
}
let shadowRepeatTotal = normalizeShadowRepeat(localStorage.getItem(SHADOW_REPEAT_KEY));
let shadowRepeatRemaining = shadowRepeatTotal;
let shadowGapMode = localStorage.getItem(SHADOW_GAP_KEY) || 'medium';
if (!Object.prototype.hasOwnProperty.call(SHADOW_GAP_RATIOS, shadowGapMode)) shadowGapMode = 'medium';
let shadowGapTimer = 0;
let shadowAutoPause = false;
let autoStopEnabled = localStorage.getItem(AUTO_STOP_ENABLED_KEY) === 'true';
let autoStopCount = normalizeAutoStopCount(localStorage.getItem(AUTO_STOP_COUNT_KEY));
let autoStopDraftEnabled = autoStopEnabled;
let autoStopDraftCount = autoStopCount;
function loadAutoStopSettings() {
autoStopEnabled = localStorage.getItem(AUTO_STOP_ENABLED_KEY) === 'true';
autoStopCount = normalizeAutoStopCount(localStorage.getItem(AUTO_STOP_COUNT_KEY));
autoStopDraftEnabled = autoStopEnabled;
autoStopDraftCount = autoStopCount;
}
function saveAutoStopSettings({ enabled, count }) {
autoStopEnabled = !!enabled;
autoStopCount = normalizeAutoStopCount(count);
autoStopDraftEnabled = autoStopEnabled;
autoStopDraftCount = autoStopCount;
try { localStorage.setItem(AUTO_STOP_ENABLED_KEY, autoStopEnabled.toString()); } catch (_) { }
try { localStorage.setItem(AUTO_STOP_COUNT_KEY, String(autoStopCount)); } catch (_) { }
resetAutoNextPlayedLessons();
}
// 兼容旧版本:从旧的 loopMode 和 autoContinue 迁移
if (!localStorage.getItem(AFTER_PLAY_KEY)) {
const oldLoopMode = localStorage.getItem('loopMode');
const oldAutoContinue = localStorage.getItem('autoContinue');
if (oldAutoContinue === 'auto') {
afterPlay = 'next';
} else if (oldLoopMode === 'single') {
afterPlay = 'single';
} else if (oldLoopMode === 'all') {
afterPlay = 'all';
} else {
afterPlay = 'none';
}
try { localStorage.setItem(AFTER_PLAY_KEY, afterPlay); } catch (_) { }
}
// 自动续集时强制开启自动跟随(避免续播后定位生硬)
if (afterPlay === 'next' && !autoFollow) {
autoFollow = true;
try { localStorage.setItem(FOLLOW_KEY, 'true'); } catch (_) { }
}
// --------------------------
// Back to top button
// --------------------------
(function initBackToTop() {
if (!backToTopBtn) return;
const update = () => {
const y = window.scrollY || document.documentElement.scrollTop || 0;
const threshold = Math.min(320, window.innerHeight * 0.6);
const show = y > threshold;
backToTopBtn.classList.toggle('show', show);
backToTopBtn.setAttribute('aria-hidden', show ? 'false' : 'true');
backToTopBtn.tabIndex = show ? 0 : -1;
};
let ticking = false;
const onScroll = () => {
if (ticking) return;
ticking = true;
raf(() => { ticking = false; update(); });
};
backToTopBtn.addEventListener('click', () => {
try { window.scrollTo({ top: 0, behavior: 'smooth' }); }
catch (_) { window.scrollTo(0, 0); }
// 重置播放位置,使空格键从第一句开始
idx = -1;
// 移除所有句子的高亮状态
listEl.querySelectorAll('.sentence.active').forEach(el => el.classList.remove('active'));
});
window.addEventListener('scroll', onScroll, { passive: true });
window.addEventListener('resize', onScroll, { passive: true });
update();
})();
// --------------------------
// iOS 解锁:首次任意交互即解锁
// --------------------------
function unlockAudioSync() {
if (iosUnlocked) return;
try {
audio.muted = true; // 保证解锁过程无声
const p = audio.play(); // 在同一用户手势栈内发起
iosUnlocked = true;
// 立即排队暂停与还原 mute(避免可闻 blip)
if (iosUnlockPauseTimer) clearTimeout(iosUnlockPauseTimer);
iosUnlockPauseTimer = setTimeout(() => {
iosUnlockPauseTimer = 0;
try { audio.pause(); } catch (_) { }
audio.muted = false;
}, 0);
} catch (_) { iosUnlocked = false; }
}
function cancelIOSUnlockPause() {
if (!iosUnlockPauseTimer) return;
clearTimeout(iosUnlockPauseTimer);
iosUnlockPauseTimer = 0;
try { audio.muted = false; } catch (_) { }
}
if (isIOSLike) {
const evs = ['pointerdown', 'touchstart', 'click'];
const onceUnlock = (e) => { unlockAudioSync(); evs.forEach(t => document.removeEventListener(t, onceUnlock, true)); };
evs.forEach(t => document.addEventListener(t, onceUnlock, { capture: true, passive: true, once: true }));
}
// 确保 metadata 已就绪(iOS 上 seek 前最好等)
async function ensureMetadata() {
if (metadataReady) return;
try { await once(audio, 'loadedmetadata', 5000); metadataReady = true; }
catch (_) { /* 忽略,后续 seek 仍会尽力 */ }
}
// --------------------------
// 跳过开头:智能识别逻辑
// --------------------------
/**
* 判断是否应该跳过某一行(高置信度检测)
* @param {Object} item - 句子对象 {start, en, cn}
* @param {number} index - 句子索引
* @returns {boolean} - true 表示应该跳过
*/
function shouldSkipLine(item, index, opts = {}) {
const en = item.en.trim();
const cn = item.cn ? item.cn.trim() : '';
const skipQuestions = !!opts.skipQuestions;
if (!en) return true; // 空行跳过
// 规则1: 跳过 "Lesson X" + "第X课" 格式(已被解析分离)
if (/^Lesson\s+\d+$/i.test(en) && /^第\d+课$/.test(cn)) {
return true;
}
// 规则2: 跳过 "Listen to the tape then answer this question." (100% 置信度)
if (/Listen to the tape/i.test(en)) {
return true;
}
// 规则3: 跳过开头的课程标题(基于时间和内容特征)
// 标题特征:有中文翻译,不是问句
// 时间分布:标题(1.5-3s), 问题(7-15s,最早7.22s)
if (cn && en.length < 80 && cn.length < 80) {
// 情况1:时间 < 7秒 → 一定是标题,直接跳过
if (item.start < 7) {
return true;
}
// 情况2:时间 7-10秒 → 可能是标题或问题
// 只有不是问号结尾才跳过(保护问题)
if (item.start < 10 && !en.endsWith('?')) {
return true;
}
}
// 可选:跟读模式下跳过提示问题(通常以问号结尾,在 7-15 秒)
const isQuestion = en.endsWith('?') || cn.endsWith('?');
if (skipQuestions && isQuestion && item.start < 20 && index < 6) {
return true;
}
// 默认不跳过听力理解问题
return false;
}
/**
* 找到第一句正文的索引(高置信度)
* @param {Array} items - 所有句子
* @returns {number} - 第一句正文的索引,如果无法确定则返回 0
*/
function findFirstContentIndex(items, opts = {}) {
if (!items || items.length === 0) return 0;
// 只检查前 10 行,避免误判
const checkLimit = Math.min(10, items.length);
let skipCount = 0;
for (let i = 0; i < checkLimit; i++) {
if (shouldSkipLine(items[i], i, opts)) {
skipCount++;
} else {
// 找到了第一句正文
// 但需要确保至少跳过了 1 行(避免误判导致什么都不跳)
if (skipCount > 0) {
console.log(`[跳过开头] 智能识别成功:跳过前 ${skipCount} 行,从索引 ${i} 开始播放`);
return i;
} else {
// 第一行就是正文,不跳过
console.log('[跳过开头] 第一行即为正文,不跳过');
return 0;
}
}
}
// 如果前 10 行都被标记为跳过,说明识别可能有问题,保守起见不跳过
console.log('[跳过开头] 未能确定第一句正文位置,为安全起见从头开始');
return 0;
}
// --------------------------
// UI 反映/设置
// --------------------------
function reflectReadMode() {
const isContinuous = readMode === 'continuous';
const isListen = readMode === 'listen';
const isSingle = readMode === 'single';
const isShadow = readMode === 'shadow';
const continuousRadio = document.getElementById('readModeContinuous');
const singleRadio = document.getElementById('readModeSingle');
const listenRadio = document.getElementById('readModeListen');
const shadowRadio = document.getElementById('readModeShadow');
if (continuousRadio && singleRadio && listenRadio && shadowRadio) {
continuousRadio.checked = isContinuous;
singleRadio.checked = isSingle;
listenRadio.checked = isListen;
shadowRadio.checked = isShadow;
}
// 控制播完后选项的启用/禁用状态
const afterPlaySingleRadio = document.getElementById('afterPlaySingle');
const afterPlaySingleLabel = document.querySelector('label[for="afterPlaySingle"]');
const afterPlayAllRadio = document.getElementById('afterPlayAll');
const afterPlayAllLabel = document.querySelector('label[for="afterPlayAll"]');
const afterPlayNextRadio = document.getElementById('afterPlayNext');
const afterPlayNextLabel = document.querySelector('label[for="afterPlayNext"]');
if (isContinuous) {
// 连读模式:禁用"单句循环"(因为连读是自动播放下一句,和单句循环冲突)
if (afterPlaySingleRadio) afterPlaySingleRadio.disabled = true;
if (afterPlaySingleLabel) {
afterPlaySingleLabel.style.opacity = '0.5';
afterPlaySingleLabel.style.cursor = 'not-allowed';
}
// 启用"整篇循环"和"自动下一课"
if (afterPlayAllRadio) afterPlayAllRadio.disabled = false;
if (afterPlayAllLabel) {
afterPlayAllLabel.style.opacity = '';
afterPlayAllLabel.style.cursor = '';
}
if (afterPlayNextRadio) afterPlayNextRadio.disabled = false;
if (afterPlayNextLabel) {
afterPlayNextLabel.style.opacity = '';
afterPlayNextLabel.style.cursor = '';
}
// 如果当前是单句循环,自动切换到本课结束
if (afterPlay === 'single') {
setAfterPlay('none');
}
} else if (isSingle) {
// 点读模式:启用"单句循环",禁用"整篇循环"和"自动下一课"
// (因为点读模式播完就停,不会自动播完整篇)
if (afterPlaySingleRadio) afterPlaySingleRadio.disabled = false;
if (afterPlaySingleLabel) {
afterPlaySingleLabel.style.opacity = '';
afterPlaySingleLabel.style.cursor = '';
}
if (afterPlayAllRadio) afterPlayAllRadio.disabled = true;
if (afterPlayAllLabel) {
afterPlayAllLabel.style.opacity = '0.5';
afterPlayAllLabel.style.cursor = 'not-allowed';
}
if (afterPlayNextRadio) afterPlayNextRadio.disabled = true;
if (afterPlayNextLabel) {
afterPlayNextLabel.style.opacity = '0.5';
afterPlayNextLabel.style.cursor = 'not-allowed';
}
// 如果当前是整篇循环或自动下一课,自动切换到本课结束
if (afterPlay === 'all' || afterPlay === 'next') {
setAfterPlay('none');
}
} else if (isListen) {
// 听读模式:所有"播完后"选项都可用
// - 单句循环:用于反复听某一句做听力训练
// - 整篇循环/自动下一课:自动播放模式
if (afterPlaySingleRadio) afterPlaySingleRadio.disabled = false;
if (afterPlaySingleLabel) {
afterPlaySingleLabel.style.opacity = '';
afterPlaySingleLabel.style.cursor = '';
}
if (afterPlayAllRadio) afterPlayAllRadio.disabled = false;
if (afterPlayAllLabel) {
afterPlayAllLabel.style.opacity = '';
afterPlayAllLabel.style.cursor = '';
}
if (afterPlayNextRadio) afterPlayNextRadio.disabled = false;
if (afterPlayNextLabel) {
afterPlayNextLabel.style.opacity = '';
afterPlayNextLabel.style.cursor = '';
}
} else if (isShadow) {
// 跟读模式:禁用"单句循环"(跟读已内置循环)
if (afterPlaySingleRadio) afterPlaySingleRadio.disabled = true;
if (afterPlaySingleLabel) {
afterPlaySingleLabel.style.opacity = '0.5';
afterPlaySingleLabel.style.cursor = 'not-allowed';
}
// 启用"整篇循环"和"自动下一课"
if (afterPlayAllRadio) afterPlayAllRadio.disabled = false;
if (afterPlayAllLabel) {
afterPlayAllLabel.style.opacity = '';
afterPlayAllLabel.style.cursor = '';
}
if (afterPlayNextRadio) afterPlayNextRadio.disabled = false;
if (afterPlayNextLabel) {
afterPlayNextLabel.style.opacity = '';
afterPlayNextLabel.style.cursor = '';
}
if (afterPlay === 'single') {
setAfterPlay('none');
}
}
// 更新听读模式的 UI
updateListenModeUI();
const shadowSettingsGroup = document.getElementById('shadowSettingsGroup');
const shadowRepeatInput = document.getElementById('shadowRepeat');
const shadowGapShort = document.getElementById('shadowGapShort');
const shadowGapMedium = document.getElementById('shadowGapMedium');
const shadowGapLong = document.getElementById('shadowGapLong');
const shadowEnabled = isShadow;
if (shadowSettingsGroup) shadowSettingsGroup.classList.toggle('is-disabled', !shadowEnabled);
if (shadowRepeatInput) shadowRepeatInput.disabled = !shadowEnabled;
if (shadowGapShort) shadowGapShort.disabled = !shadowEnabled;
if (shadowGapMedium) shadowGapMedium.disabled = !shadowEnabled;
if (shadowGapLong) shadowGapLong.disabled = !shadowEnabled;
}
function reflectFollowMode() {
const followOnRadio = document.getElementById('followOn');
const followOffRadio = document.getElementById('followOff');
if (followOnRadio && followOffRadio) {
followOnRadio.checked = autoFollow;
followOffRadio.checked = !autoFollow;
}
}
function reflectAfterPlay() {
const afterPlayNoneRadio = document.getElementById('afterPlayNone');
const afterPlaySingleRadio = document.getElementById('afterPlaySingle');
const afterPlayAllRadio = document.getElementById('afterPlayAll');
const afterPlayNextRadio = document.getElementById('afterPlayNext');
if (afterPlayNoneRadio && afterPlaySingleRadio && afterPlayAllRadio && afterPlayNextRadio) {
afterPlayNoneRadio.checked = afterPlay === 'none';
afterPlaySingleRadio.checked = afterPlay === 'single';
afterPlayAllRadio.checked = afterPlay === 'all';
afterPlayNextRadio.checked = afterPlay === 'next';
}
}
function reflectAutoStopSettings() {
if (autoStopOn && autoStopOff) {
autoStopOn.checked = !!autoStopDraftEnabled;
autoStopOff.checked = !autoStopDraftEnabled;
}
if (autoStopCountInput) {
autoStopCountInput.value = String(autoStopDraftCount);
autoStopCountInput.disabled = !autoStopDraftEnabled;
autoStopCountInput.style.opacity = autoStopDraftEnabled ? '' : '0.6';
}
}
function reflectSkipIntro() {
const skipIntroOnRadio = document.getElementById('skipIntroOn');
const skipIntroOffRadio = document.getElementById('skipIntroOff');
if (skipIntroOnRadio && skipIntroOffRadio) {
skipIntroOnRadio.checked = skipIntro;
skipIntroOffRadio.checked = !skipIntro;
}
}
function reflectShadowSettings() {
const repeatInput = document.getElementById('shadowRepeat');
const gapShort = document.getElementById('shadowGapShort');
const gapMedium = document.getElementById('shadowGapMedium');
const gapLong = document.getElementById('shadowGapLong');
if (repeatInput) repeatInput.value = String(shadowRepeatTotal);
if (gapShort) gapShort.checked = shadowGapMode === 'short';
if (gapMedium) gapMedium.checked = shadowGapMode === 'medium';
if (gapLong) gapLong.checked = shadowGapMode === 'long';
}
reflectReadMode(); reflectFollowMode(); reflectAfterPlay(); reflectSkipIntro();
reflectShadowSettings();
reflectAutoStopSettings();
function setReadMode(mode) {
if (!['continuous', 'single', 'listen', 'shadow'].includes(mode)) mode = 'continuous';
readMode = mode;
try { localStorage.setItem(MODE_KEY, readMode); } catch (_) { }
reflectReadMode();
clearShadowGapTimer();
shadowAutoPause = false;
if (readMode === 'shadow') shadowRepeatRemaining = shadowRepeatTotal;
// 模式切换:清调度→按新模式刷新当前段末→重建调度
clearAdvance(); isScheduling = false; scheduleTime = 0;
if (idx >= 0 && idx < items.length) segmentEnd = endFor(items[idx]);
scheduleAdvance();
}
function setFollowMode(follow) {
autoFollow = !!follow;
try { localStorage.setItem(FOLLOW_KEY, autoFollow.toString()); } catch (_) { }
reflectFollowMode();
}
function setAfterPlay(mode) {
if (!['none', 'single', 'all', 'next'].includes(mode)) mode = 'none';
afterPlay = mode;
try { localStorage.setItem(AFTER_PLAY_KEY, afterPlay); } catch (_) { }
reflectAfterPlay();
resetAutoNextPlayedLessons();
// 自动续集:默认开启自动跟随(用户可再手动关闭,但本次选择会帮你打开)
if (afterPlay === 'next' && !autoFollow) {
setFollowMode(true);
}
}
function setSkipIntro(skip) {
skipIntro = !!skip;
try { localStorage.setItem(SKIP_INTRO_KEY, skipIntro.toString()); } catch (_) { }
reflectSkipIntro();
// 重新计算第一句正文的位置
if (items && items.length > 0) {
firstContentIndex = skipIntro ? findFirstContentIndex(items) : 0;
shadowStartIndex = findFirstContentIndex(items, { skipQuestions: true });
}
}
function setShadowRepeatCount(value) {
shadowRepeatTotal = normalizeShadowRepeat(value);
shadowRepeatRemaining = shadowRepeatTotal;
try { localStorage.setItem(SHADOW_REPEAT_KEY, String(shadowRepeatTotal)); } catch (_) { }
reflectShadowSettings();
}
function setShadowGapMode(mode) {
if (!Object.prototype.hasOwnProperty.call(SHADOW_GAP_RATIOS, mode)) mode = 'medium';
shadowGapMode = mode;
try { localStorage.setItem(SHADOW_GAP_KEY, shadowGapMode); } catch (_) { }
reflectShadowSettings();
}
function updateListenModeUI() {
const isListenMode = readMode === 'listen';
const sentences = listEl.querySelectorAll('.sentence');
sentences.forEach((el, i) => {
if (isListenMode) {
el.classList.add('listen-mode');
if (revealedSentences.has(i)) {
el.classList.add('revealed');
} else {
el.classList.remove('revealed');
}
} else {
el.classList.remove('listen-mode', 'revealed');
}
});
}
function toggleSentenceReveal(i) {
if (readMode !== 'listen') return;
if (revealedSentences.has(i)) {
revealedSentences.delete(i);
} else {
revealedSentences.add(i);
}
// 保存到 localStorage(针对当前课程)
saveRevealedSentences();
updateListenModeUI();
}
function saveRevealedSentences() {
try {
const id = lessonId();
const allRevealed = JSON.parse(localStorage.getItem(REVEALED_SENTENCES_KEY) || '{}');
allRevealed[id] = Array.from(revealedSentences);
localStorage.setItem(REVEALED_SENTENCES_KEY, JSON.stringify(allRevealed));
} catch (_) { }
}
function loadRevealedSentences() {
try {
const id = lessonId();
const allRevealed = JSON.parse(localStorage.getItem(REVEALED_SENTENCES_KEY) || '{}');
const revealed = allRevealed[id] || [];
revealedSentences = new Set(revealed);
} catch (_) {
revealedSentences = new Set();
}
}
// 阅读模式单选按钮事件
const readModeContinuous = document.getElementById('readModeContinuous');
const readModeSingle = document.getElementById('readModeSingle');
const readModeListen = document.getElementById('readModeListen');
const readModeShadow = document.getElementById('readModeShadow');
if (readModeContinuous) readModeContinuous.addEventListener('change', () => { if (readModeContinuous.checked) setReadMode('continuous'); });
if (readModeSingle) readModeSingle.addEventListener('change', () => { if (readModeSingle.checked) setReadMode('single'); });
if (readModeListen) readModeListen.addEventListener('change', () => { if (readModeListen.checked) setReadMode('listen'); });
if (readModeShadow) readModeShadow.addEventListener('change', () => { if (readModeShadow.checked) setReadMode('shadow'); });
// 自动跟随单选按钮事件
const followOn = document.getElementById('followOn');
const followOff = document.getElementById('followOff');
if (followOn) followOn.addEventListener('change', () => { if (followOn.checked) setFollowMode(true); });
if (followOff) followOff.addEventListener('change', () => { if (followOff.checked) setFollowMode(false); });
// 播完后单选按钮事件
const afterPlayNoneRadio = document.getElementById('afterPlayNone');
const afterPlaySingleRadio = document.getElementById('afterPlaySingle');
const afterPlayAllRadio = document.getElementById('afterPlayAll');
const afterPlayNextRadio = document.getElementById('afterPlayNext');
if (afterPlayNoneRadio) afterPlayNoneRadio.addEventListener('change', () => { if (afterPlayNoneRadio.checked) setAfterPlay('none'); });
if (afterPlaySingleRadio) {
afterPlaySingleRadio.addEventListener('change', () => { if (afterPlaySingleRadio.checked) setAfterPlay('single'); });
// 当禁用时点击,显示提示
const afterPlaySingleLabel = document.querySelector('label[for="afterPlaySingle"]');
if (afterPlaySingleLabel) {
afterPlaySingleLabel.addEventListener('click', (e) => {
if (afterPlaySingleRadio.disabled) {
e.preventDefault();
showNotification('单句循环在连读/跟读模式下不可用');
}
});
}
}
if (afterPlayAllRadio) {
afterPlayAllRadio.addEventListener('change', () => { if (afterPlayAllRadio.checked) setAfterPlay('all'); });
// 当禁用时点击,显示提示
const afterPlayAllLabel = document.querySelector('label[for="afterPlayAll"]');
if (afterPlayAllLabel) {
afterPlayAllLabel.addEventListener('click', (e) => {
if (afterPlayAllRadio.disabled) {
e.preventDefault();
showNotification('整篇循环在点读模式下不可用');
}
});
}
}
if (afterPlayNextRadio) {
afterPlayNextRadio.addEventListener('change', () => {
if (afterPlayNextRadio.checked) {
setAfterPlay('next');
openAutoStop();
}
});
// 当禁用时点击,显示提示
const afterPlayNextLabel = document.querySelector('label[for="afterPlayNext"]');
if (afterPlayNextLabel) {
afterPlayNextLabel.addEventListener('click', (e) => {
if (afterPlayNextRadio.disabled) {
e.preventDefault();
showNotification('自动下一课在点读模式下不可用');
}
});
}
}
// 跟读设置
const shadowRepeatInput = document.getElementById('shadowRepeat');
if (shadowRepeatInput) {
shadowRepeatInput.addEventListener('change', () => {
setShadowRepeatCount(shadowRepeatInput.value);
});
shadowRepeatInput.addEventListener('blur', () => {
if (!shadowRepeatInput.value) {
setShadowRepeatCount(shadowRepeatTotal);
}
});
}
const shadowGapShort = document.getElementById('shadowGapShort');
const shadowGapMedium = document.getElementById('shadowGapMedium');
const shadowGapLong = document.getElementById('shadowGapLong');
if (shadowGapShort) shadowGapShort.addEventListener('change', () => { if (shadowGapShort.checked) setShadowGapMode('short'); });
if (shadowGapMedium) shadowGapMedium.addEventListener('change', () => { if (shadowGapMedium.checked) setShadowGapMode('medium'); });
if (shadowGapLong) shadowGapLong.addEventListener('change', () => { if (shadowGapLong.checked) setShadowGapMode('long'); });
const shadowSettingsGroup = document.getElementById('shadowSettingsGroup');
if (shadowSettingsGroup) {
shadowSettingsGroup.addEventListener('click', (e) => {
if (readMode !== 'shadow') {
e.preventDefault();
showNotification('请切换到跟读模式');
}
});
}
// 跳过开头单选按钮事件
const skipIntroOn = document.getElementById('skipIntroOn');
const skipIntroOff = document.getElementById('skipIntroOff');
if (skipIntroOn) skipIntroOn.addEventListener('change', () => { if (skipIntroOn.checked) setSkipIntro(true); });
if (skipIntroOff) skipIntroOff.addEventListener('change', () => { if (skipIntroOff.checked) setSkipIntro(false); });
// 倍速
audio.playbackRate = savedRate;
if (speedButton) speedButton.textContent = `${savedRate.toFixed(2)}x`;
if (speedButton) speedButton.addEventListener('click', () => {
currentRateIndex = (currentRateIndex + 1) % rates.length;
const newRate = rates[currentRateIndex];
audio.playbackRate = newRate;
});
audio.addEventListener('ratechange', () => {
const r = audio.playbackRate;
try { localStorage.setItem('audioPlaybackRate', r); } catch (_) { }
if (speedButton) speedButton.textContent = `${r.toFixed(2)}x`;
const i = rates.indexOf(r); if (i !== -1) currentRateIndex = i;
scheduleAdvance();
});
function pauseForNavigation() {
try { saveLastPos(); } catch (_) { }
clearShadowGapTimer();
shadowAutoPause = false;
if (!audio.paused) {
try { internalPause = true; audio.pause(); } catch (_) { }
}
}
// 返回
if (backLink) {
const fallback = `index.html#${book}`;
backLink.setAttribute('href', fallback);
backLink.addEventListener('click', (e) => {
e.preventDefault();
pauseForNavigation();
location.href = fallback;
});
}
// --------------------------
// 自定义播放器控制
// --------------------------
const playPauseBtn = qs('#playPauseBtn');
const playIcon = playPauseBtn ? playPauseBtn.querySelector('.play-icon') : null;
const pauseIcon = playPauseBtn ? playPauseBtn.querySelector('.pause-icon') : null;
const currentTimeEl = qs('#currentTime');
const durationEl = qs('#duration');
const progressBar = qs('#progressBar');
const progressFilled = qs('#progressFilled');
// 格式化时间显示
function formatTime(seconds) {
if (!isFinite(seconds) || seconds < 0) return '0:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${String(secs).padStart(2, '0')}`;
}
// 更新播放/暂停图标
function updatePlayPauseIcon() {
if (!playIcon || !pauseIcon) return;
if (audio.paused) {
playIcon.style.display = '';
pauseIcon.style.display = 'none';
} else {
playIcon.style.display = 'none';
pauseIcon.style.display = '';
}
}
// 播放/暂停按钮点击
if (playPauseBtn) {
playPauseBtn.addEventListener('click', (e) => {
e.preventDefault();
if (audio.paused) {
if (readMode === 'shadow') {
const tolerance = 0.1;
if (idx < 0 && items.length > 0) {
playSegment(shadowStartIndex, { manual: true });
return;
}
if (idx >= 0 && segmentEnd > 0) {
const currentTime = audio.currentTime;
if (Math.abs(currentTime - segmentEnd) < tolerance) {
playSegment(idx, { manual: true });
return;
}
}
const p = audio.play();
if (p && p.catch) p.catch(() => { });
return;
}
// 和空格键一样的逻辑:点读模式智能跳转
if (readMode === 'single' && idx >= 0 && segmentEnd > 0) {
const currentTime = audio.currentTime;
const tolerance = 0.1;
if (Math.abs(currentTime - segmentEnd) < tolerance) {
const nextIdx = Math.min(idx + 1, items.length - 1);
if (nextIdx < items.length && nextIdx !== idx) {
playSegment(nextIdx, { manual: true });
return;
}
playSegment(idx, { manual: true });
return;
}
}
if (idx < 0 && items.length > 0) {
playSegment(firstContentIndex, { manual: true });
} else {
const p = audio.play();
if (p && p.catch) p.catch(() => { });
}
} else {
audio.pause();
}
});
}
// 更新进度条和时间显示
function updateProgress() {
const current = audio.currentTime || 0;
const duration = audio.duration || 0;
if (currentTimeEl) currentTimeEl.textContent = formatTime(current);
if (durationEl) durationEl.textContent = formatTime(duration);
if (progressFilled && duration > 0) {
const percentage = (current / duration) * 100;
progressFilled.style.width = `${Math.min(100, Math.max(0, percentage))}%`;
}
}
// 进度条点击跳转
if (progressBar) {
progressBar.addEventListener('click', (e) => {
const rect = progressBar.getBoundingClientRect();
const clickX = e.clientX - rect.left;
const percentage = clickX / rect.width;
const duration = audio.duration || 0;
if (duration > 0) {
audio.currentTime = percentage * duration;
}
});
}
// 监听audio事件更新UI