-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1415 lines (1203 loc) · 54.5 KB
/
script.js
File metadata and controls
1415 lines (1203 loc) · 54.5 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
(function () {
'use strict';
// 配置常量
const CONFIG = {
DEFAULT_INTERVAL: 3,
DEFAULT_START: 1,
DEFAULT_RANDOM_RATIO: 30,
MAX_RANDOM_RATIO: 100,
MIN_RANDOM_RATIO: 1
};
// ==========================================================================
// 工具函数(模块顶层,避免重复创建)
// ==========================================================================
/** 判断是否为中文字符 */
function isChineseChar(char) {
return /[\u4e00-\u9fa5]/.test(char);
}
/** 判断是否为句子结束符 */
function isSentenceEnd(char) {
return /[。!?;,]/.test(char);
}
/**
* Fisher-Yates 标准洗牌算法
* 保证均匀随机分布,O(n) 时间复杂度
* @param {Array} array - 待洗牌数组(原地修改)
* @returns {Array} 洗牌后的数组
*/
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
// 获取DOM元素
const DOM = {
// 核心输入输出
inputText: document.getElementById('input-text'),
outputText: document.getElementById('output-text'),
// 工具栏控件
intervalInput: document.getElementById('interval'),
intervalSlider: document.getElementById('interval-slider'),
startInput: document.getElementById('start'),
startSlider: document.getElementById('start-slider'),
randomRatioInput: document.getElementById('random-ratio'),
randomRatioSlider: document.getElementById('random-ratio-slider'),
regularModeCheckbox: document.getElementById('regular-mode'),
randomModeCheckbox: document.getElementById('random-mode'),
firstCharModeCheckbox: document.getElementById('first-char-mode'),
// 视图切换按钮
btnEditView: document.getElementById('btn-edit-view'),
btnReciteView: document.getElementById('btn-recite-view'),
editLayer: document.getElementById('edit-layer'),
reciteLayer: document.getElementById('recite-layer'),
processBtn: document.getElementById('process-btn'), // 移动端浮动按钮
// 侧边栏相关
textsListUl: document.getElementById('texts-list-ul'),
paragraphsContainer: document.getElementById('paragraphs-container'),
textsListView: document.getElementById('texts-list-view'),
paragraphsListView: document.getElementById('paragraphs-list-view'),
backToTextsBtn: document.getElementById('back-to-texts'),
currentTextTitle: document.getElementById('current-text-title'),
// 模式切换
modeToggle: document.getElementById('mode-toggle'),
recitationMode: document.getElementById('recitation-mode'),
reviewMode: document.getElementById('review-mode'),
// 复习模式相关
generateReviewBtn: document.getElementById('generate-review'),
reviewContent: document.getElementById('review-content'),
reviewSentences: document.getElementById('review-sentences'),
// 新的组合控件
hideInfoControl: document.getElementById('hide-info-control'),
hideInfoToggleBtn: document.getElementById('hide-info-toggle-btn'),
hideDropdownTrigger: document.getElementById('hide-dropdown-trigger'),
hideDropdownMenu: document.getElementById('hide-dropdown-menu'),
hideTitleCheck: document.getElementById('hide-title-check'),
hideDynastyCheck: document.getElementById('hide-dynasty-check'),
hideAuthorCheck: document.getElementById('hide-author-check'),
// 生疏本模态窗口
viewUnknownCardsBtn: document.getElementById('view-unknown-cards-btn'),
unknownCardsModal: document.getElementById('unknown-cards-modal'),
closeModalBtn: document.getElementById('close-modal-btn'),
clearStorageBtn: document.getElementById('clear-storage-btn'),
unknownSourceList: document.getElementById('unknown-source-list'),
unknownCardsContainer: document.getElementById('unknown-cards-container'),
// 移动端相关
sidebarToggle: document.getElementById('sidebar-toggle'),
sidebarOverlay: document.getElementById('sidebar-overlay'),
sidebar: document.querySelector('.sidebar')
};
let reviewQuestionsGenerated = false;
const semesterSelector = document.createElement('select');
semesterSelector.id = 'semester-selector';
// 生疏本与熟悉度数据(使用 localStorage 持久化存储)
const STORAGE_KEYS = {
UNKNOWN_CARDS: 'recitation_unknown_cards',
FAMILIAR_CARDS: 'recitation_familiar_cards'
};
// 从 localStorage 加载数据
function loadUnknownCardsFromStorage() {
try {
const data = localStorage.getItem(STORAGE_KEYS.UNKNOWN_CARDS);
if (data) {
const parsed = JSON.parse(data);
return new Map(parsed);
}
} catch (e) {
console.warn('加载生疏本数据失败:', e);
}
return new Map();
}
function loadFamiliarCardsFromStorage() {
try {
const data = localStorage.getItem(STORAGE_KEYS.FAMILIAR_CARDS);
if (data) {
const parsed = JSON.parse(data);
return new Set(parsed);
}
} catch (e) {
console.warn('加载熟悉度数据失败:', e);
}
return new Set();
}
// 保存数据到 localStorage
function saveUnknownCardsToStorage() {
try {
const data = JSON.stringify(Array.from(unknownCards.entries()));
localStorage.setItem(STORAGE_KEYS.UNKNOWN_CARDS, data);
} catch (e) {
console.warn('保存生疏本数据失败:', e);
}
}
function saveFamiliarCardsToStorage() {
try {
const data = JSON.stringify(Array.from(familiarCards));
localStorage.setItem(STORAGE_KEYS.FAMILIAR_CARDS, data);
} catch (e) {
console.warn('保存熟悉度数据失败:', e);
}
}
// 清空所有存储(完全清理 localStorage 中的相关数据)
function clearAllStorage() {
if (confirm('确定要清空所有存储数据吗?此操作将清除所有生疏本记录和熟悉度数据,且无法恢复。')) {
// 清空 localStorage
localStorage.removeItem(STORAGE_KEYS.UNKNOWN_CARDS);
localStorage.removeItem(STORAGE_KEYS.FAMILIAR_CARDS);
// 清空内存数据
unknownCards.clear();
familiarCards.clear();
// 更新复习模式中的按钮状态
document.querySelectorAll('.mark-btn.active').forEach(btn => {
btn.classList.remove('active');
});
// 重新渲染模态窗口
renderUnknownCardsModal();
}
}
// 初始化数据(从 localStorage 加载)
const unknownCards = loadUnknownCardsFromStorage(); // key: unique id (source+text), value: card data
const familiarCards = loadFamiliarCardsFromStorage(); // set of unique ids
let currentReviewQuestions = []; // 当前显示的题目
const selectedTextsForReview = new Set(); // 复习模式下选中的篇目ID
// ==========================================================================
// 核心逻辑:文本处理
// ==========================================================================
function processText() {
// 获取用户输入的文本
const text = DOM.inputText.value.trim();
// 检查文本是否为空
if (!text) {
DOM.outputText.value = '请输入文言文内容后再进行处理';
return;
}
// 获取设置的参数
let interval = parseInt(DOM.intervalInput.value);
let start = parseInt(DOM.startInput.value);
let randomRatio = parseInt(DOM.randomRatioInput.value);
const isRegularModeEnabled = DOM.regularModeCheckbox.checked;
const isRandomModeEnabled = DOM.randomModeCheckbox.checked;
const isFirstCharModeEnabled = DOM.firstCharModeCheckbox.checked;
// 验证输入的数值是否有效
if (isNaN(interval) || interval < 1) {
interval = CONFIG.DEFAULT_INTERVAL;
DOM.intervalInput.value = interval;
}
if (isNaN(start) || start < 0) {
start = CONFIG.DEFAULT_START;
DOM.startInput.value = start;
}
if (isNaN(randomRatio) || randomRatio < CONFIG.MIN_RANDOM_RATIO || randomRatio > CONFIG.MAX_RANDOM_RATIO) {
randomRatio = CONFIG.DEFAULT_RANDOM_RATIO;
DOM.randomRatioInput.value = randomRatio;
}
// 仅显示句首字模式
if (isFirstCharModeEnabled) {
let result = '';
let isNewSentence = true;
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (isChineseChar(char)) {
if (isNewSentence) {
result += char;
isNewSentence = false;
} else {
result += '__ ';
}
} else {
result += char;
if (isSentenceEnd(char)) {
isNewSentence = true;
}
}
}
DOM.outputText.value = result;
return;
}
// 常规/随机挖空逻辑
let result = '';
let chineseCharCount = 0;
// 收集所有中文字符的位置
const chineseCharPositions = [];
for (let i = 0; i < text.length; i++) {
if (isChineseChar(text[i])) {
chineseCharPositions.push(i);
}
}
// 如果需要随机挖空,先生成随机挖空的位置集合
const randomReplacePositions = new Set();
if (isRandomModeEnabled && chineseCharPositions.length > 0) {
const randomCount = Math.floor(chineseCharPositions.length * (randomRatio / 100));
const shuffledPositions = shuffleArray([...chineseCharPositions]);
for (let i = 0; i < randomCount; i++) {
randomReplacePositions.add(shuffledPositions[i]);
}
}
// 处理文本
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (isChineseChar(char)) {
chineseCharCount++;
let shouldReplace = false;
if (isRegularModeEnabled && chineseCharCount >= start && (chineseCharCount - start) % interval === 0) {
shouldReplace = true;
}
if (!shouldReplace && isRandomModeEnabled && randomReplacePositions.has(i)) {
shouldReplace = true;
}
if (shouldReplace) {
result += '__ ';
} else {
result += char;
}
} else {
result += char;
}
}
DOM.outputText.value = result;
}
// ==========================================================================
// 视图切换逻辑 (Edit vs Recite)
// ==========================================================================
function switchToEditView() {
DOM.editLayer.classList.add('active');
DOM.reciteLayer.classList.remove('active');
DOM.btnEditView.classList.add('active');
DOM.btnReciteView.classList.remove('active');
}
function switchToReciteView() {
// 切换前先处理文本
processText();
DOM.reciteLayer.classList.add('active');
DOM.editLayer.classList.remove('active');
DOM.btnReciteView.classList.add('active');
DOM.btnEditView.classList.remove('active');
}
DOM.btnEditView.addEventListener('click', switchToEditView);
DOM.btnReciteView.addEventListener('click', switchToReciteView);
// 移动端浮动按钮逻辑
if (DOM.processBtn) {
DOM.processBtn.addEventListener('click', function () {
switchToReciteView();
});
}
// 键盘快捷键 (Ctrl+Enter)
DOM.inputText.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
switchToReciteView();
}
});
// ==========================================================================
// 控件状态管理
// ==========================================================================
function toggleControlElements() {
const isFirstCharModeEnabled = DOM.firstCharModeCheckbox.checked;
const isRegularModeEnabled = DOM.regularModeCheckbox.checked;
const isRandomModeEnabled = DOM.randomModeCheckbox.checked;
// 找到控件对应的父级.tool-item
const regularModeItem = DOM.regularModeCheckbox.closest('.tool-item');
const randomModeItem = DOM.randomModeCheckbox.closest('.tool-item');
const intervalItem = DOM.intervalInput.closest('.tool-item');
const startItem = DOM.startInput.closest('.tool-item');
const randomRatioItem = DOM.randomRatioInput.closest('.tool-item');
if (isFirstCharModeEnabled) {
// 禁用其他模式
DOM.regularModeCheckbox.disabled = true;
DOM.randomModeCheckbox.disabled = true;
DOM.intervalInput.disabled = true;
DOM.startInput.disabled = true;
DOM.randomRatioInput.disabled = true;
// 视觉反馈
if (regularModeItem) regularModeItem.classList.add('disabled');
if (randomModeItem) randomModeItem.classList.add('disabled');
if (intervalItem) intervalItem.classList.add('disabled');
if (startItem) startItem.classList.add('disabled');
if (randomRatioItem) randomRatioItem.classList.add('disabled');
} else {
// 启用其他模式
DOM.regularModeCheckbox.disabled = false;
DOM.randomModeCheckbox.disabled = false;
if (regularModeItem) regularModeItem.classList.remove('disabled');
if (randomModeItem) randomModeItem.classList.remove('disabled');
// 根据各自开关状态控制输入框
DOM.intervalInput.disabled = !isRegularModeEnabled;
DOM.startInput.disabled = !isRegularModeEnabled;
DOM.randomRatioInput.disabled = !isRandomModeEnabled;
if (intervalItem) intervalItem.classList.toggle('disabled', !isRegularModeEnabled);
if (startItem) startItem.classList.toggle('disabled', !isRegularModeEnabled);
if (randomRatioItem) randomRatioItem.classList.toggle('disabled', !isRandomModeEnabled);
}
}
// 监听设置变化
DOM.regularModeCheckbox.addEventListener('change', function () {
if (this.checked && DOM.firstCharModeCheckbox.checked) DOM.firstCharModeCheckbox.checked = false;
toggleControlElements();
// 如果在背诵视图,实时更新
if (DOM.reciteLayer.classList.contains('active')) processText();
});
DOM.randomModeCheckbox.addEventListener('change', function () {
if (this.checked && DOM.firstCharModeCheckbox.checked) DOM.firstCharModeCheckbox.checked = false;
toggleControlElements();
if (DOM.reciteLayer.classList.contains('active')) processText();
});
DOM.firstCharModeCheckbox.addEventListener('change', function () {
if (this.checked) {
DOM.regularModeCheckbox.checked = false;
DOM.randomModeCheckbox.checked = false;
}
toggleControlElements();
if (DOM.reciteLayer.classList.contains('active')) processText();
});
// ==========================================================================
// 滑动条与输入框双向联动逻辑
// ==========================================================================
// 初始化:将输入框值同步到滑动条
function initSliders() {
DOM.intervalSlider.value = DOM.intervalInput.value;
DOM.startSlider.value = DOM.startInput.value;
DOM.randomRatioSlider.value = DOM.randomRatioInput.value;
}
// 滑动条 → 输入框联动
function setupSliderListeners() {
// 间隔滑动条
DOM.intervalSlider.addEventListener('input', function () {
DOM.intervalInput.value = this.value;
if (DOM.reciteLayer.classList.contains('active')) processText();
});
// 起始滑动条
DOM.startSlider.addEventListener('input', function () {
DOM.startInput.value = this.value;
if (DOM.reciteLayer.classList.contains('active')) processText();
});
// 随机频率滑动条
DOM.randomRatioSlider.addEventListener('input', function () {
DOM.randomRatioInput.value = this.value;
if (DOM.reciteLayer.classList.contains('active')) processText();
});
}
// 输入框 → 滑动条联动
function setupInputListeners() {
// 间隔输入框
DOM.intervalInput.addEventListener('change', function () {
// 验证范围
let value = parseInt(this.value);
if (isNaN(value) || value < 1) {
value = CONFIG.DEFAULT_INTERVAL;
this.value = value;
}
DOM.intervalSlider.value = value;
});
// 起始输入框
DOM.startInput.addEventListener('change', function () {
// 验证范围
let value = parseInt(this.value);
if (isNaN(value) || value < 0) {
value = CONFIG.DEFAULT_START;
this.value = value;
}
DOM.startSlider.value = value;
});
// 随机频率输入框
DOM.randomRatioInput.addEventListener('change', function () {
// 验证范围
let value = parseInt(this.value);
if (isNaN(value) || value < CONFIG.MIN_RANDOM_RATIO || value > CONFIG.MAX_RANDOM_RATIO) {
value = CONFIG.DEFAULT_RANDOM_RATIO;
this.value = value;
}
DOM.randomRatioSlider.value = value;
});
// 实时更新处理
[DOM.intervalInput, DOM.startInput, DOM.randomRatioInput].forEach(input => {
input.addEventListener('change', () => {
if (DOM.reciteLayer.classList.contains('active')) processText();
});
});
}
// 设置所有联动监听器
function setupSliderInputSync() {
initSliders();
setupSliderListeners();
setupInputListeners();
}
// ==========================================================================
// 侧边栏与篇目列表逻辑
// ==========================================================================
function loadSampleText() {
const sample = `臣密言:臣以险衅,夙遭闵凶。生孩六月,慈父见背;行年四岁,舅夺母志。祖母刘愍臣孤弱,躬亲抚养。臣少多疾病,九岁不行,零丁孤苦,至于成立。既无伯叔,终鲜兄弟,门衰祚薄,晚有儿息。外无期功强近之亲,内无应门五尺之僮,茕茕孑立,形影相吊。而刘夙婴疾病,常在床蓐,臣侍汤药,未曾废离。`;
DOM.inputText.value = sample;
}
function initSemesterSelector() {
// 如果已经添加了选择器,就跳过
if (document.getElementById('semester-selector')) return;
// 直接使用DOM.textsListView作为容器
const container = DOM.textsListView;
semesterSelector.innerHTML = '<option value="all">全部册次</option>';
const semesters = new Set();
const classicTexts = window.RecitationData && window.RecitationData.texts ? window.RecitationData.texts : [];
if (classicTexts.length > 0) {
classicTexts.forEach(text => {
if (text.category === '学期') {
semesters.add(text.title);
}
});
}
semesters.forEach(semester => {
const option = document.createElement('option');
option.value = semester;
option.textContent = semester;
semesterSelector.appendChild(option);
});
semesterSelector.addEventListener('change', function () {
initTextsList(this.value);
});
// 插入到列表之前
container.insertBefore(semesterSelector, DOM.textsListUl);
}
function initTextsList(selectedSemester = 'all') {
DOM.textsListUl.innerHTML = '';
const classicTexts = window.RecitationData && window.RecitationData.texts ? window.RecitationData.texts : [];
if (classicTexts.length > 0) {
const filteredTexts = classicTexts.filter(text => {
if (text.category === '学期') return false;
return selectedSemester === 'all' || text.category.startsWith(selectedSemester);
});
if (filteredTexts.length > 0) {
filteredTexts.forEach(text => {
const li = document.createElement('li');
const titleDiv = document.createElement('div');
titleDiv.className = 'text-title';
titleDiv.textContent = text.title;
const authorDiv = document.createElement('div');
authorDiv.className = 'text-author';
const hasDynasty = !!text.dynasty;
const hasAuthor = !!text.author;
if (hasDynasty && hasAuthor) {
authorDiv.textContent = `${text.dynasty} · ${text.author}`;
} else if (hasDynasty) {
authorDiv.textContent = text.dynasty;
} else {
authorDiv.textContent = text.author || '未知';
}
li.appendChild(titleDiv);
li.appendChild(authorDiv);
li.dataset.textId = text.id;
li.addEventListener('click', function () {
const isReviewMode = !DOM.modeToggle.checked;
if (isReviewMode) {
// 复习模式:切换选中状态(多选)
this.classList.toggle('selected');
if (this.classList.contains('selected')) {
selectedTextsForReview.add(text.id);
} else {
selectedTextsForReview.delete(text.id);
}
} else {
// 背诵模式:单选并跳转段落页
document.querySelectorAll('#texts-list-ul li').forEach(item => item.classList.remove('selected'));
this.classList.add('selected');
showParagraphs(text);
// 移动端:不在此处关闭侧边栏,等用户选择段落后再关闭
}
});
DOM.textsListUl.appendChild(li);
});
} else {
DOM.textsListUl.innerHTML = '<li style="color:var(--color-text-muted);text-align:center;">暂无篇目</li>';
}
}
}
function switchSidebarView(viewName) {
if (viewName === 'texts') {
DOM.textsListView.classList.add('active');
DOM.paragraphsListView.classList.remove('active');
} else {
DOM.textsListView.classList.remove('active');
DOM.paragraphsListView.classList.add('active');
}
}
function showParagraphs(text) {
DOM.currentTextTitle.textContent = text.title;
switchSidebarView('paragraphs');
DOM.paragraphsContainer.innerHTML = '';
// 全文按钮
const selectAllBtn = document.createElement('button');
selectAllBtn.className = 'select-all-btn';
selectAllBtn.textContent = '选择全文';
selectAllBtn.addEventListener('click', function () {
const fullText = text.paragraphs.map(p => p.content).join('\n\n');
DOM.inputText.value = fullText;
switchToEditView(); // 自动切回编辑模式让用户看到内容
// 移动端:选择后关闭侧边栏
if (isMobileDevice()) {
closeSidebar();
}
});
DOM.paragraphsContainer.appendChild(selectAllBtn);
// 段落按钮
text.paragraphs.forEach((paragraph, index) => {
const card = document.createElement('div');
card.className = 'paragraph-card';
const title = document.createElement('h5');
// 简单处理标题
title.textContent = paragraph.id.includes('-') ? '合并段落' : `段落 ${index + 1}`;
const preview = document.createElement('p');
preview.className = 'paragraph-preview';
preview.textContent = paragraph.content;
const btn = document.createElement('button');
btn.className = 'select-paragraph-btn';
btn.textContent = '选择此段落';
btn.addEventListener('click', function () {
DOM.inputText.value = paragraph.content;
switchToEditView();
// 移动端:选择后关闭侧边栏
if (isMobileDevice()) {
closeSidebar();
}
});
card.appendChild(title);
card.appendChild(preview);
card.appendChild(btn);
DOM.paragraphsContainer.appendChild(card);
});
}
DOM.backToTextsBtn.addEventListener('click', () => {
switchSidebarView('texts');
});
// ==========================================================================
// 模式切换 (背诵 vs 复习)
// ==========================================================================
function switchAppMode(isChecked) {
// Toggle Checked: Right side = Recitation Mode
// Toggle Unchecked: Left side = Review Mode (Default)
const isRecitationMode = isChecked;
if (isRecitationMode) {
// Switch to Recitation Mode
DOM.reviewMode.classList.remove('active');
DOM.recitationMode.classList.add('active');
document.body.classList.remove('review-mode-active');
} else {
// Switch to Review Mode
DOM.recitationMode.classList.remove('active');
DOM.reviewMode.classList.add('active');
document.body.classList.add('review-mode-active');
if (!reviewQuestionsGenerated) {
generateReviewQuestions();
reviewQuestionsGenerated = true;
}
}
}
DOM.modeToggle.addEventListener('change', function () {
switchAppMode(this.checked);
});
// ==========================================================================
// 复习模式逻辑 (保持原有逻辑,仅适配新DOM)
// ==========================================================================
function getRandomTexts(count = 5) {
const classicTexts = window.RecitationData && window.RecitationData.texts ? window.RecitationData.texts : [];
let validTexts = classicTexts.filter(text =>
text.category !== '学期' &&
text.paragraphs &&
text.paragraphs.length > 0 &&
text.paragraphs.some(p => p.content && p.content.trim().length > 0)
);
// 如果有选中的篇目,只使用选中的篇目
if (selectedTextsForReview.size > 0) {
validTexts = validTexts.filter(text => selectedTextsForReview.has(text.id));
}
const shuffled = shuffleArray([...validTexts]);
return shuffled.slice(0, Math.min(count, shuffled.length));
}
function extractSentencesFromText(text) {
const sentences = [];
text.paragraphs.forEach(paragraph => {
if (paragraph.content) {
// 使用正则分割,保留分隔符
const parts = paragraph.content.split(/([。!?])/).filter(s => s.length > 0);
const paragraphSentences = [];
// 重组句子(内容 + 标点)
for (let i = 0; i < parts.length; i += 2) {
const content = parts[i].trim();
const punctuation = parts[i + 1] || '。';
if (content.length > 0) {
paragraphSentences.push(content + punctuation);
}
}
// 为每个句子添加索引和段落句子引用
paragraphSentences.forEach((sentence, index) => {
sentences.push({
text: sentence,
source: text.title,
author: text.author,
dynasty: text.dynasty,
paragraphSentences: paragraphSentences, // 段落内所有句子
sentenceIndex: index // 当前句子在段落中的索引
});
});
}
});
return sentences;
}
function createBlankSentence(sentence) {
// 使用正则表达式分割,同时保留分隔符
const splitRegex = /([,;])/;
const parts = sentence.text.split(splitRegex).filter(p => p.length > 0);
// 提取分句和分隔符
const clauses = [];
const separators = [];
for (let i = 0; i < parts.length; i++) {
if (/^[,;]$/.test(parts[i])) {
separators.push(parts[i]);
} else if (parts[i].trim().length > 0) {
clauses.push(parts[i].trim());
}
}
// 如果只有一个分句,尝试与相邻句子合并
if (clauses.length <= 1) {
const paragraphSentences = sentence.paragraphSentences;
const currentIndex = sentence.sentenceIndex;
// 如果没有段落信息或只有一句话,无法合并
if (!paragraphSentences || paragraphSentences.length <= 1) {
return { original: sentence.text, blanked: sentence.text, blankIndex: -1 };
}
let combinedText = '';
let blankSentenceText = sentence.text;
// 检查可以合并的方向
const canMergeWithNext = currentIndex < paragraphSentences.length - 1;
const canMergeWithPrev = currentIndex > 0;
// 随机选择合并方向,除非只有一个方向可选
let mergeWithNext;
if (canMergeWithNext && canMergeWithPrev) {
mergeWithNext = Math.random() < 0.5; // 随机选择
} else if (canMergeWithNext) {
mergeWithNext = true;
} else if (canMergeWithPrev) {
mergeWithNext = false;
} else {
return { original: sentence.text, blanked: sentence.text, blankIndex: -1 };
}
if (mergeWithNext) {
// 与后一句合并:当前句挖空
combinedText = sentence.text + paragraphSentences[currentIndex + 1];
} else {
// 与前一句合并:当前句挖空
combinedText = paragraphSentences[currentIndex - 1] + sentence.text;
}
// 挖空当前句子(去掉句末标点后挖空)
const blankTextWithoutPunctuation = blankSentenceText.replace(/[。!?]$/, '');
const blankedCombined = combinedText.replace(blankTextWithoutPunctuation, '__________');
return {
original: combinedText,
blanked: blankedCombined,
blankIndex: 0, // 标记为有效挖空
blankText: blankTextWithoutPunctuation,
source: sentence.source,
author: sentence.author,
dynasty: sentence.dynasty
};
}
// 随机选择一个分句进行挖空(排除最后一个,因为它通常包含句末标点)
const randomIndex = Math.floor(Math.random() * (clauses.length - 1));
const selectedClause = clauses[randomIndex].trim();
const blankedClause = '__________';
let blankedSentence = '';
for (let i = 0; i < clauses.length; i++) {
if (i === randomIndex) {
blankedSentence += blankedClause;
} else {
blankedSentence += clauses[i];
}
// 使用原始的分隔符,如果没有则跳过
if (i < separators.length) {
blankedSentence += separators[i];
}
}
return {
original: sentence.text,
blanked: blankedSentence,
blankIndex: randomIndex,
blankText: selectedClause,
source: sentence.source,
author: sentence.author,
dynasty: sentence.dynasty
};
}
function generateReviewQuestions() {
DOM.reviewSentences.innerHTML = '';
const randomTexts = getRandomTexts(5);
if (randomTexts.length === 0) {
DOM.reviewSentences.innerHTML = '<p class="error-message">无法获取数据</p>';
return;
}
const reviewQuestions = [];
const targetCount = 5; // 目标题目数量
// 从每个篇目收集所有可用句子
const allAvailableSentences = [];
randomTexts.forEach(text => {
const sentences = extractSentencesFromText(text);
sentences.forEach(sentence => {
allAvailableSentences.push(sentence);
});
});
// 随机打乱所有句子
const shuffledSentences = [...allAvailableSentences].sort(() => Math.random() - 0.5);
// 尝试生成目标数量的题目
for (const sentence of shuffledSentences) {
if (reviewQuestions.length >= targetCount) break;
const blankedSentence = createBlankSentence(sentence);
if (blankedSentence.blankIndex >= 0) {
// 生成唯一ID
blankedSentence.uid = `${blankedSentence.source || 'unknown'}_${blankedSentence.original.substring(0, 20)}`;
// 避免重复的句子
if (!reviewQuestions.some(q => q.uid === blankedSentence.uid)) {
reviewQuestions.push(blankedSentence);
}
}
}
// 保存当前题目供熟悉度判定使用
currentReviewQuestions = reviewQuestions;
// 渲染题目
reviewQuestions.forEach((question, index) => {
const el = document.createElement('div');
el.className = 'review-sentence';
el.dataset.uid = question.uid;
const num = document.createElement('span');
num.className = 'sentence-number';
num.textContent = index + 1;
const content = document.createElement('span');
content.className = 'sentence-content';
content.innerHTML = processSentenceForDisplay(question.blanked, question.blankText);
const source = document.createElement('div');
source.className = 'sentence-source';
source.style.marginTop = '10px';
source.style.color = '#666';
source.style.fontSize = '0.9rem';
// 构建来源文本,支持联动隐藏作者和朝代
let sourceText = '';
// 获取隐藏设置
const isHideEnabled = DOM.hideInfoControl.classList.contains('active');
const hideTitle = DOM.hideTitleCheck.checked;
const hideDynasty = DOM.hideDynastyCheck.checked;
const hideAuthor = DOM.hideAuthorCheck.checked;
// 显示标题
if (question.source) {
if (isHideEnabled && hideTitle) {
sourceText += `<span class="blank" data-blank="true" data-text="${question.source}">__________</span>`;
} else {
sourceText += question.source;
}
}
// 显示朝代和作者
const hasDynasty = !!question.dynasty;
const hasAuthor = !!question.author;
if (hasDynasty || hasAuthor) {
if (sourceText) sourceText += ' · '; // 如果前面有标题,加分隔符
// 显示朝代(在作者左侧)
if (hasDynasty) {
if (isHideEnabled && hideDynasty) {
sourceText += `<span class="blank" data-blank="true" data-text="${question.dynasty}">__________</span>`;
} else {
sourceText += question.dynasty;
}
if (hasAuthor) {
sourceText += ' · ';
}
}
// 显示作者
if (hasAuthor) {
if (isHideEnabled && hideAuthor) {
sourceText += `<span class="blank" data-blank="true" data-text="${question.author}">__________</span>`;
} else {
sourceText += question.author;
}
}
}
source.innerHTML = `—— ${sourceText}`;
// 标记按钮(生疏本)
const actions = document.createElement('div');
actions.className = 'sentence-actions';
const markBtn = document.createElement('button');
markBtn.className = 'mark-btn';
if (unknownCards.has(question.uid)) {
markBtn.classList.add('active');
}
markBtn.innerHTML = `<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>`;
markBtn.title = '标记为生疏';
markBtn.dataset.uid = question.uid;
markBtn.addEventListener('click', function (e) {
e.stopPropagation();
toggleUnknownCard(question, this);
});
actions.appendChild(markBtn);
el.appendChild(num);
el.appendChild(content);
el.appendChild(source);
el.appendChild(actions);
// 存储数据用于交互
el.dataset.blankText = question.blankText;
DOM.reviewSentences.appendChild(el);
});
DOM.reviewContent.classList.remove('hidden');
addBlankClickListenersWithFamiliarity();
}
function processSentenceForDisplay(sentence, hiddenText) {
return sentence.replace(/__________/g, `<span class="blank" data-blank="true" data-text="${hiddenText}">__________</span>`);
}
function addBlankClickListeners() {