-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathread.html
More file actions
1775 lines (1611 loc) · 68.4 KB
/
read.html
File metadata and controls
1775 lines (1611 loc) · 68.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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>阅读 - 我的书架</title>
<meta name="description" content="">
<!-- P3修复:DNS预解析和预连接 -->
<link rel="preconnect" href="https://github.com" crossorigin>
<link rel="dns-prefetch" href="https://github.com">
<link rel="stylesheet" href="/style.css">
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#d4a574">
</head>
<body>
<div class="progress-bar" id="progress-bar"></div>
<div class="navbar">
<h1><a href="/">📚 我的书架</a></h1>
<nav>
<a href="#" id="back-link">返回目录</a>
<span id="nav-user"></span>
</nav>
</div>
<div class="reader" id="reader-area">
<div class="breadcrumb" id="breadcrumb"></div>
<div id="content" class="loading">加载中...</div>
</div>
<!-- 底部工具栏 -->
<div class="reader-bottom-bar" id="bottom-bar">
<button class="bar-btn" id="bar-prev" title="上一章"><span class="bar-icon">◀</span>上一章</button>
<button class="bar-btn" id="bar-toc" title="目录"><span class="bar-icon">☰</span>目录</button>
<button class="bar-btn" id="bar-bookmark" title="书签"><span class="bar-icon" id="bookmark-icon">☆</span>书签</button>
<button class="bar-btn" id="bar-settings" title="设置"><span class="bar-icon">⚙</span>设置</button>
<button class="bar-btn" id="bar-immersive" title="沉浸模式"><span class="bar-icon">🔲</span>沉浸</button>
<button class="bar-btn" id="bar-next" title="下一章"><span class="bar-icon">▶</span>下一章</button>
</div>
<!-- 章节目录浮层 -->
<div class="toc-overlay" id="toc-overlay">
<div class="toc-panel">
<h3 id="toc-title">目录</h3>
<ul class="toc-list" id="toc-list"></ul>
</div>
</div>
<!-- 设置面板 -->
<div class="settings-overlay" id="settings-overlay">
<div class="settings-panel">
<h3>阅读设置<button class="close-btn" id="close-settings">✕</button></h3>
<div class="setting-row">
<span class="setting-label">主题</span>
<div class="theme-options" id="theme-options">
<div class="theme-dot" data-theme="light" title="默认"></div>
<div class="theme-dot" data-theme="dark" title="夜间"></div>
<div class="theme-dot" data-theme="green" title="护眼"></div>
<div class="theme-dot" data-theme="sepia" title="羊皮纸"></div>
<div class="theme-dot" data-theme="blue" title="淡蓝"></div>
</div>
</div>
<div class="setting-row">
<span class="setting-label">字体</span>
<div class="font-options" id="font-options">
<div class="font-option" data-font="'Georgia','Noto Serif SC','Source Han Serif CN',serif" style="font-family:Georgia,serif">宋体/衬线</div>
<div class="font-option" data-font="'PingFang SC','Microsoft YaHei','Noto Sans SC',sans-serif" style="font-family:sans-serif">黑体/无衬线</div>
<div class="font-option" data-font="'KaiTi','STKaiti','AR PL UKai CN',serif" style="font-family:KaiTi,STKaiti,serif">楷体</div>
<div class="font-option" data-font="'FangSong','STFangsong',serif" style="font-family:FangSong,STFangsong,serif">仿宋</div>
</div>
</div>
<div class="setting-row">
<span class="setting-label">字号</span>
<div class="slider-row">
<span style="font-size:12px">A</span>
<input type="range" id="font-size-slider" min="14" max="28" step="1">
<span style="font-size:20px">A</span>
<span class="slider-val" id="font-size-val">17px</span>
</div>
</div>
<div class="setting-row">
<span class="setting-label">行距</span>
<div class="slider-row">
<span style="font-size:12px">紧</span>
<input type="range" id="line-height-slider" min="1.5" max="3" step="0.1">
<span style="font-size:12px">松</span>
<span class="slider-val" id="line-height-val">2.0</span>
</div>
</div>
<div class="setting-row">
<span class="setting-label">页面宽度</span>
<div class="slider-row">
<span style="font-size:12px">窄</span>
<input type="range" id="width-slider" min="500" max="960" step="20">
<span style="font-size:12px">宽</span>
<span class="slider-val" id="width-val">720px</span>
</div>
</div>
<div class="setting-row">
<span class="setting-label">阅读模式</span>
<div class="mode-options" id="mode-options">
<div class="mode-option" data-mode="scroll">📜 滚动</div>
<div class="mode-option" data-mode="pager">📖 翻页</div>
</div>
</div>
</div>
</div>
<button class="back-to-top has-bar" id="back-top" onclick="window.scrollTo({top:0,behavior:'smooth'})">↑</button>
<!-- 翻页模式:点击区域 + 页码 -->
<div class="pager-tap-left" id="pager-tap-left" style="display:none"></div>
<div class="pager-tap-right" id="pager-tap-right" style="display:none"></div>
<div class="pager-indicator" id="pager-indicator"></div>
<div class="immersive-hint" id="immersive-hint">点击中央或按 Esc 退出沉浸模式</div>
<!-- 批注:浮动按钮(PC+移动端统一) -->
<div id="anno-float-btn" class="anno-float-btn">📝</div>
<!-- 批注:输入框 -->
<div id="anno-editor" class="anno-editor" style="display:none">
<div class="anno-editor-quote" id="anno-quote"></div>
<div class="anno-input-wrap">
<textarea id="anno-input" maxlength="500" placeholder="写下你的批注..."></textarea>
<span class="anno-char-count"><span id="anno-char-num">0</span>/500</span>
</div>
<div class="anno-editor-footer">
<button id="anno-vis-btn" class="anno-vis-btn" type="button">🔒 仅自己可见</button>
<div class="anno-editor-actions">
<button class="btn btn-sm" id="anno-cancel" type="button">取消</button>
<button class="btn btn-sm anno-submit-btn" id="anno-submit" type="button">发表</button>
</div>
</div>
<div class="anno-editor-hint">Ctrl+Enter 发表 · Esc 取消</div>
</div>
<!-- 批注:查看弹窗 -->
<div id="anno-popover" class="anno-popover" style="display:none"></div>
<script>
// ===== 认证状态 =====
const authToken = ''; // token由HttpOnly Cookie自动携带
let currentUser = null; // { userId, username, role }
let canAnnotate = false; // 当前书籍是否可批注
let currentBookId = null;
let currentChapterId = null;
async function fetchCurrentUser() {
const navUser = document.getElementById('nav-user');
try {
const res = await fetch('/api/me', { credentials: 'same-origin' });
if (res.ok) {
currentUser = await res.json();
const roleMap = {
'super_admin': { label: '超管', cls: 'super' },
'admin': { label: '管理', cls: 'admin' },
'demo': { label: '用户', cls: 'demo' }
};
const r = roleMap[currentUser.role] || { label: '用户', cls: 'demo' };
navUser.innerHTML = `<a href="/admin.html"><span class="role-badge ${r.cls}">${r.label}</span> ${esc(currentUser.username || '')}</a> <a href="#" onclick="doLogout();return false" style="font-size:12px;color:#e74c3c;margin-left:6px">退出</a>`;
} else {
navUser.innerHTML = '<a href="/admin.html">管理</a>';
}
} catch {
navUser.innerHTML = '<a href="/admin.html">管理</a>';
}
}
async function doLogout() {
try { await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' }); } catch {}
currentUser = null;
location.reload();
}
function annoApi(method, path, body) {
const opts = { method, headers: {}, credentials: 'same-origin' };
if (body) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(body);
}
return fetch(path, opts);
}
// ===== 句子分割工具 =====
function splitSentences(text) {
if (!text || !text.trim()) return [];
// 匹配句子:非句末标点的字符 + 可选的句末标点(含省略号…和连续英文句号..)
// 🟡-4: 连续英文句号 .. / ... 视为省略号,不逐个断句
const raw = text.match(/[^。!?…!?\n]+(?:\.{2,}|[。!?…!?\n])?/g) || [text];
const merged = [];
let buf = '';
let depth = 0;
for (const seg of raw) {
buf += seg;
for (const ch of seg) {
if (ch === '\u201c' || ch === '\u300c' || ch === '\u300e') depth++;
if (ch === '\u201d' || ch === '\u300d' || ch === '\u300f') depth = Math.max(0, depth - 1);
}
if (depth === 0) {
const trimmed = buf.trim();
if (trimmed) merged.push(trimmed);
buf = '';
}
}
if (buf.trim()) merged.push(buf.trim());
return merged;
}
function snapToSentence(paragraphText, selStart, selEnd) {
const sentences = splitSentences(paragraphText);
let pos = 0;
for (let i = 0; i < sentences.length; i++) {
const s = sentences[i];
const sStart = paragraphText.indexOf(s, pos);
const sEnd = sStart + s.length;
if (selStart < sEnd && selEnd > sStart) {
return { text: s, sentIdx: i, start: sStart, end: sEnd };
}
pos = sEnd;
}
return null;
}
async function sentenceHash(text) {
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
return [...new Uint8Array(buf)].slice(0, 16).map(b => b.toString(16).padStart(2, '0')).join('');
}
function annotationOpacity(count) {
if (count <= 0) return 0;
// 1人=0.3, 3人≈0.5, 10人≈0.75, 20人≈0.9(🟢-2: 改为20条达到最大浓度)
const min = 0.3, max = 0.9;
return Math.min(max, min + (max - min) * (Math.log10(count) / Math.log10(20)));
}
// ===== 阅读设置初始化 =====
let immersiveActive = false; // 沉浸模式状态(提前声明供其他handler使用)
const THEMES = ['light','dark','green','sepia','blue'];
const FONTS = [
"'Georgia','Noto Serif SC','Source Han Serif CN',serif",
"'PingFang SC','Microsoft YaHei','Noto Sans SC',sans-serif",
"'KaiTi','STKaiti','AR PL UKai CN',serif",
"'FangSong','STFangsong',serif"
];
function loadSettings() {
let readingMode = 'scroll';
try { readingMode = localStorage.getItem('reading-mode') || 'scroll'; } catch {}
return {
theme: localStorage.getItem('theme') || 'light',
fontSize: parseInt(localStorage.getItem('font-size')) || 17,
lineHeight: parseFloat(localStorage.getItem('line-height')) || 2,
fontFamily: localStorage.getItem('font-family') || FONTS[0],
readingWidth: parseInt(localStorage.getItem('reading-width')) || 720,
readingMode: readingMode
};
}
let settings = loadSettings();
// ===== 翻页模式变量(需在 applyAllSettings 之前声明)=====
let pagerState = { currentPage: 0, totalPages: 1, columnWidth: 0 };
const pagerTapLeft = document.getElementById('pager-tap-left');
const pagerTapRight = document.getElementById('pager-tap-right');
const pagerIndicator = document.getElementById('pager-indicator');
applyAllSettings();
function applyAllSettings() {
const root = document.documentElement;
root.setAttribute('data-theme', settings.theme);
root.style.setProperty('--font-size', settings.fontSize + 'px');
root.style.setProperty('--line-height', settings.lineHeight);
root.style.setProperty('--letter-spacing', '0.02em');
root.style.setProperty('--font-family', settings.fontFamily);
root.style.setProperty('--reading-width', settings.readingWidth + 'px');
applyReadingMode();
}
function saveSetting(key, val) {
localStorage.setItem(key, val);
}
// ===== 设置面板交互 =====
const settingsOverlay = document.getElementById('settings-overlay');
const tocOverlay = document.getElementById('toc-overlay');
// 主题选择
document.getElementById('theme-options').addEventListener('click', (e) => {
const dot = e.target.closest('.theme-dot');
if (!dot) return;
settings.theme = dot.dataset.theme;
saveSetting('theme', settings.theme);
applyAllSettings();
updateSettingsUI();
});
// 字体选择
document.getElementById('font-options').addEventListener('click', (e) => {
const opt = e.target.closest('.font-option');
if (!opt) return;
settings.fontFamily = opt.dataset.font;
saveSetting('font-family', settings.fontFamily);
applyAllSettings();
updateSettingsUI();
// 字体变化后需要等渲染再重新分页
if (settings.readingMode === 'pager') {
requestAnimationFrame(() => { requestAnimationFrame(() => { pagerRecalc(); }); });
}
});
// 防抖工具函数(翻页模式滑块用)
let _pagerDebounceTimer = null;
function debouncedPagerRecalc() {
if (_pagerDebounceTimer) clearTimeout(_pagerDebounceTimer);
_pagerDebounceTimer = setTimeout(pagerRecalc, 100);
}
// 字号滑块
document.getElementById('font-size-slider').addEventListener('input', (e) => {
settings.fontSize = parseInt(e.target.value);
saveSetting('font-size', settings.fontSize);
document.getElementById('font-size-val').textContent = settings.fontSize + 'px';
applyAllSettings();
if (settings.readingMode === 'pager') debouncedPagerRecalc();
});
// 行距滑块
document.getElementById('line-height-slider').addEventListener('input', (e) => {
settings.lineHeight = parseFloat(e.target.value);
saveSetting('line-height', settings.lineHeight);
document.getElementById('line-height-val').textContent = settings.lineHeight.toFixed(1);
applyAllSettings();
if (settings.readingMode === 'pager') debouncedPagerRecalc();
});
// 页面宽度滑块
document.getElementById('width-slider').addEventListener('input', (e) => {
settings.readingWidth = parseInt(e.target.value);
saveSetting('reading-width', settings.readingWidth);
document.getElementById('width-val').textContent = settings.readingWidth + 'px';
applyAllSettings();
if (settings.readingMode === 'pager') debouncedPagerRecalc();
});
// 阅读模式切换
document.getElementById('mode-options').addEventListener('click', (e) => {
const opt = e.target.closest('.mode-option');
if (!opt) return;
const newMode = opt.dataset.mode;
if (newMode === settings.readingMode) return;
settings.readingMode = newMode;
saveSetting('reading-mode', newMode);
applyAllSettings();
updateSettingsUI();
});
function updateSettingsUI() {
document.querySelectorAll('.theme-dot').forEach(d => {
d.classList.toggle('active', d.dataset.theme === settings.theme);
});
document.querySelectorAll('.font-option').forEach(o => {
o.classList.toggle('active', o.dataset.font === settings.fontFamily);
});
document.getElementById('font-size-slider').value = settings.fontSize;
document.getElementById('font-size-val').textContent = settings.fontSize + 'px';
document.getElementById('line-height-slider').value = settings.lineHeight;
document.getElementById('line-height-val').textContent = settings.lineHeight.toFixed(1);
document.getElementById('width-slider').value = settings.readingWidth;
document.getElementById('width-val').textContent = settings.readingWidth + 'px';
document.querySelectorAll('.mode-option').forEach(o => {
o.classList.toggle('active', o.dataset.mode === settings.readingMode);
});
}
// 打开/关闭设置
document.getElementById('bar-settings').addEventListener('click', () => {
updateSettingsUI();
settingsOverlay.classList.add('active');
});
document.getElementById('close-settings').addEventListener('click', () => {
settingsOverlay.classList.remove('active');
});
settingsOverlay.addEventListener('click', (e) => {
if (e.target === settingsOverlay) settingsOverlay.classList.remove('active');
});
// 打开/关闭目录
document.getElementById('bar-toc').addEventListener('click', () => {
tocOverlay.classList.add('active');
// 滚动到当前章节
const cur = document.querySelector('.toc-list a.current');
if (cur) cur.scrollIntoView({ block: 'center' });
});
tocOverlay.addEventListener('click', (e) => {
if (e.target === tocOverlay) tocOverlay.classList.remove('active');
});
// ===== 翻页模式引擎 =====
function applyReadingMode() {
const isPager = settings.readingMode === 'pager';
document.body.classList.toggle('pager-mode', isPager);
pagerTapLeft.style.display = isPager ? 'block' : 'none';
pagerTapRight.style.display = isPager ? 'block' : 'none';
if (isPager) {
pagerRecalc();
} else {
// 切回滚动模式:清除column样式和transform
const content = document.querySelector('.reader-content');
if (content) {
// 记住当前阅读比例
const ratio = pagerState.totalPages > 1 ? pagerState.currentPage / (pagerState.totalPages - 1) : 0;
content.style.transition = 'none';
content.style.transform = '';
content.style.height = '';
content.style.columnWidth = '';
content.style.columnGap = '';
content.offsetHeight; // force reflow
content.style.transition = '';
// 恢复滚动位置
if (ratio > 0) {
requestAnimationFrame(() => {
const h = document.documentElement.scrollHeight - window.innerHeight;
if (h > 0) window.scrollTo(0, h * ratio);
});
}
}
pagerIndicator.style.display = 'none';
}
}
function pagerRecalc() {
if (settings.readingMode !== 'pager') return;
const content = document.querySelector('.reader-content');
if (!content) return;
// 保存当前阅读比例
const oldRatio = pagerState.totalPages > 1 ? pagerState.currentPage / (pagerState.totalPages - 1) : 0;
// 获取容器可用高度
const reader = document.getElementById('reader-area');
const readerRect = reader.getBoundingClientRect();
const titleEl = reader.querySelector('h2');
const titleH = titleEl ? titleEl.offsetHeight + 16 : 0;
const availH = readerRect.height - titleH;
if (availH <= 0) return;
const colW = readerRect.width;
pagerState.columnWidth = colW;
// 批量设置样式,只触发一次 reflow
content.style.transition = 'none';
content.style.transform = 'translateX(0)';
content.style.height = availH + 'px';
content.style.columnWidth = colW + 'px';
content.style.columnGap = colW + 'px';
// 单次强制 reflow 获取 scrollWidth
const scrollW = content.scrollWidth;
// 优化页码计算:使用更精确的公式
// 每页宽度 = columnWidth + columnGap = colW * 2
const pageWidth = colW * 2;
if (scrollW <= colW) {
pagerState.totalPages = 1;
} else {
// 使用 ceil 向上取整,确保最后一页也能显示
pagerState.totalPages = Math.ceil(scrollW / pageWidth);
}
pagerState.totalPages = Math.max(1, pagerState.totalPages);
// 恢复到相近的页码
if (pagerState.totalPages > 1) {
pagerState.currentPage = Math.min(Math.round(oldRatio * (pagerState.totalPages - 1)), pagerState.totalPages - 1);
} else {
pagerState.currentPage = 0;
}
pagerState.currentPage = Math.max(0, pagerState.currentPage);
pagerGoTo(pagerState.currentPage, false);
}
function pagerGoTo(page, animate) {
const content = document.querySelector('.reader-content');
if (!content) return;
page = Math.max(0, Math.min(page, pagerState.totalPages - 1));
pagerState.currentPage = page;
const offset = page * pagerState.columnWidth * 2;
if (animate === false) {
content.style.transition = 'none';
} else {
content.style.transition = 'transform 0.35s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
}
content.style.transform = 'translateX(-' + offset + 'px)';
if (animate === false) {
// force reflow then restore transition
content.offsetHeight;
content.style.transition = '';
}
pagerUpdateIndicator();
// 保存进度(用页码比例模拟scrollPct)
if (window._chapterMeta) {
const m = window._chapterMeta;
const pct = pagerState.totalPages > 1 ? page / (pagerState.totalPages - 1) : 0;
try {
const progress = {
chapterId: m.chapterId, chapterTitle: m.chapterTitle,
bookTitle: m.bookTitle, bookId: m.bookId,
scrollPct: pct, time: Date.now()
};
localStorage.setItem('reading_' + m.bookId, JSON.stringify(progress));
} catch {}
}
}
function pagerUpdateIndicator() {
pagerIndicator.textContent = (pagerState.currentPage + 1) + ' / ' + pagerState.totalPages;
}
function pagerNext() {
if (pagerState.currentPage < pagerState.totalPages - 1) {
pagerGoTo(pagerState.currentPage + 1, true);
} else if (nextUrl) {
location.href = nextUrl;
}
}
function pagerPrev() {
if (pagerState.currentPage > 0) {
pagerGoTo(pagerState.currentPage - 1, true);
} else if (prevUrl) {
location.href = prevUrl;
}
}
// 翻页点击区域(有选区时不翻页,让批注交互优先)
pagerTapLeft.addEventListener('click', (e) => {
const sel = window.getSelection();
if (sel && !sel.isCollapsed) return; // 有选区时不翻页
e.stopPropagation(); pagerPrev();
});
pagerTapRight.addEventListener('click', (e) => {
const sel = window.getSelection();
if (sel && !sel.isCollapsed) return;
e.stopPropagation(); pagerNext();
});
// 触摸滑动翻页
let touchStartX = 0, touchStartY = 0, touchStartTime = 0;
document.addEventListener('touchstart', (e) => {
if (settings.readingMode !== 'pager') return;
if (e.target.closest('.settings-panel') || e.target.closest('.toc-panel') || e.target.closest('.reader-bottom-bar')) return;
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
touchStartTime = Date.now();
}, { passive: true });
document.addEventListener('touchend', (e) => {
if (settings.readingMode !== 'pager') return;
if (e.target.closest('.settings-panel') || e.target.closest('.toc-panel') || e.target.closest('.reader-bottom-bar')) return;
const dx = e.changedTouches[0].clientX - touchStartX;
const dy = e.changedTouches[0].clientY - touchStartY;
const dt = Date.now() - touchStartTime;
// 水平滑动距离>50px,且水平>垂直,且时间<500ms
if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy) && dt < 500) {
if (dx < 0) pagerNext();
else pagerPrev();
}
}, { passive: true });
// resize时重新计算
let resizeTimer = null;
window.addEventListener('resize', () => {
if (settings.readingMode !== 'pager') return;
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(pagerRecalc, 200);
});
// ===== 底部工具栏显示/隐藏 =====
const bottomBar = document.getElementById('bottom-bar');
let barVisible = true;
bottomBar.classList.add('visible');
document.getElementById('reader-area').addEventListener('click', (e) => {
if (immersiveActive) return; // 沉浸模式下由专门的handler处理
if (e.target.closest('a') || e.target.closest('button') || e.target.closest('.reader-nav')) return;
// 翻页模式下,中间区域点击切换工具栏(左右区域由tap zone处理)
if (settings.readingMode === 'pager') {
const x = e.clientX;
const w = window.innerWidth;
if (x < w * 0.35 || x > w * 0.65) return; // 左右区域不处理
}
barVisible = !barVisible;
bottomBar.classList.toggle('visible', barVisible);
});
// ===== 进度条 + 滚动位置记忆 =====
// P2修复:优化进度保存频率,使用节流而非防抖
// 节流确保定期保存,防抖可能导致长时间不保存
let scrollSaveTimer = null;
let lastSaveTime = 0;
const SCROLL_SAVE_INTERVAL = 2000; // 节流间隔:2秒保存一次,平衡性能和体验
window.addEventListener('scroll', () => {
if (settings.readingMode === 'pager') return;
const h = document.documentElement.scrollHeight - window.innerHeight;
const pct = h > 0 ? (window.scrollY / h * 100) : 0;
document.getElementById('progress-bar').style.width = pct + '%';
document.getElementById('back-top').classList.toggle('visible', window.scrollY > 400);
// 节流保存滚动位置:确保每2秒最多保存一次
const now = Date.now();
if (now - lastSaveTime >= SCROLL_SAVE_INTERVAL) {
// 立即保存并更新时间戳
saveScrollPosition();
lastSaveTime = now;
} else {
// 在节流间隔内,设置定时器确保最终会保存
if (scrollSaveTimer) clearTimeout(scrollSaveTimer);
scrollSaveTimer = setTimeout(() => {
saveScrollPosition();
lastSaveTime = Date.now();
}, SCROLL_SAVE_INTERVAL - (now - lastSaveTime));
}
});
function saveScrollPosition() {
if (!window._chapterMeta) return;
if (settings.readingMode === 'pager') return; // pager模式在pagerGoTo中保存
const m = window._chapterMeta;
const h = document.documentElement.scrollHeight - window.innerHeight;
const pct = h > 0 ? (window.scrollY / h) : 0;
const progress = {
chapterId: m.chapterId, chapterTitle: m.chapterTitle,
bookTitle: m.bookTitle, bookId: m.bookId,
scrollPct: pct, time: Date.now()
};
localStorage.setItem(`reading_${m.bookId}`, JSON.stringify(progress));
}
// ===== 键盘快捷键 =====
let prevUrl = null, nextUrl = null, backUrl = null;
document.addEventListener('keydown', (e) => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
if (e.key === 'ArrowLeft') {
if (settings.readingMode === 'pager') pagerPrev();
else if (prevUrl) location.href = prevUrl;
return;
}
if (e.key === 'ArrowRight') {
if (settings.readingMode === 'pager') pagerNext();
else if (nextUrl) location.href = nextUrl;
return;
}
if (e.key === 'Escape') {
if (immersiveActive) { exitImmersive(); return; }
if (document.fullscreenElement) { document.exitFullscreen(); return; }
if (settingsOverlay.classList.contains('active')) settingsOverlay.classList.remove('active');
else if (tocOverlay.classList.contains('active')) tocOverlay.classList.remove('active');
else if (backUrl) location.href = backUrl;
}
if (e.key === 'i' || e.key === 'I') {
toggleImmersive();
return;
}
if (e.key === 't' || e.key === 'T') {
const idx = THEMES.indexOf(settings.theme);
settings.theme = THEMES[(idx + 1) % THEMES.length];
saveSetting('theme', settings.theme);
applyAllSettings(); updateSettingsUI();
}
if (e.key === 'f' || e.key === 'F') {
if (document.fullscreenElement) document.exitFullscreen();
else document.documentElement.requestFullscreen().catch(() => {});
}
if (e.key === 's' || e.key === 'S') {
settingsOverlay.classList.toggle('active');
}
});
// ===== 加载站点设置 =====
fetch('/api/settings').then(r => r.json()).then(d => {
const s = d.settings || {};
if (s.site_name) document.querySelector('.navbar h1 a').textContent = '📚 ' + s.site_name;
}).catch(() => {});
// ===== 加载自定义字体 =====
fetch('/api/fonts').then(r => r.json()).then(d => {
const fonts = d.fonts || [];
const container = document.getElementById('font-options');
fonts.forEach(name => {
const familyName = 'Custom-' + name.replace(/\.woff2$/i, '');
const face = new FontFace(familyName, `url(/api/fonts/${encodeURIComponent(name)})`);
face.load().then(loaded => {
document.fonts.add(loaded);
const div = document.createElement('div');
div.className = 'font-option';
div.dataset.font = `'${familyName}'`;
div.style.fontFamily = familyName;
div.textContent = name.replace(/\.woff2$/i, '');
container.appendChild(div);
// 如果当前选中的就是这个字体,标记active
if (settings.fontFamily === `'${familyName}'`) div.classList.add('active');
}).catch(() => {}); // 加载失败静默忽略
});
}).catch(() => {});
// ===== 预加载缓存 =====
let prefetchedNext = null;
// ===== 加载章节 =====
const chapterId = new URLSearchParams(location.search).get('id');
if (!chapterId || !/^\d+$/.test(chapterId)) {
document.getElementById('content').innerHTML = '<div class="msg msg-error">无效的章节ID</div>';
} else {
loadChapter();
}
async function loadChapter() {
const el = document.getElementById('content');
try {
// 检查是否有预加载缓存
let data;
if (prefetchedNext && prefetchedNext.chapter && String(prefetchedNext.chapter.id) === chapterId) {
data = prefetchedNext;
prefetchedNext = null;
} else {
const res = await fetch(`/api/chapters/${chapterId}`);
if (!res.ok) throw new Error(res.status === 404 ? '章节不存在' : '加载失败');
data = await res.json();
}
const c = data.chapter;
// 存储元数据
window._chapterMeta = {
chapterId: c.id, chapterTitle: c.title,
bookTitle: c.book_title, bookId: c.book_id
};
window._chapterData = { content: data.content, title: c.title };
// SEO
document.title = esc(c.title) + ' - ' + esc(c.book_title);
const metaDesc = document.querySelector('meta[name="description"]');
if (metaDesc) metaDesc.content = `${c.book_title} - ${c.title}`;
// 面包屑
backUrl = `/book.html?id=${c.book_id}`;
document.getElementById('back-link').href = backUrl;
document.getElementById('breadcrumb').innerHTML =
`<a href="/">书架</a><span>›</span><a href="/book.html?id=${c.book_id}">${esc(c.book_title)}</a><span>›</span>${esc(c.title)}`;
// 正文 — 按段落渲染为 <p>(批注系统依赖段落索引)
const contentDiv = document.createElement('div');
contentDiv.className = 'reader-content';
const rawParagraphs = data.content.split('\n');
rawParagraphs.forEach((text, idx) => {
if (!text.trim()) return; // 跳过空行,但保留原始索引
const p = document.createElement('p');
p.textContent = text;
p.dataset.paraIdx = idx;
contentDiv.appendChild(p);
});
currentBookId = c.book_id;
currentChapterId = c.id;
// 导航
prevUrl = data.prevChapter ? `/read.html?id=${data.prevChapter.id}` : null;
nextUrl = data.nextChapter ? `/read.html?id=${data.nextChapter.id}` : null;
const nav = document.createElement('div');
nav.className = 'reader-nav';
nav.innerHTML = `
${prevUrl ? `<a href="${prevUrl}">← ${esc(data.prevChapter.title)}</a>` : '<span class="disabled">已是第一章</span>'}
<a href="/book.html?id=${c.book_id}">目录</a>
<a href="#" id="export-btn" style="font-size:13px">导出TXT</a>
<a href="#" id="download-book-btn" style="font-size:13px">📥 缓存全书</a>
${nextUrl ? `<a href="${nextUrl}">${esc(data.nextChapter.title)} →</a>` : '<span class="disabled">已是最新章</span>'}
`;
el.innerHTML = `<h2>${esc(c.title)}</h2>`;
el.appendChild(contentDiv);
el.appendChild(nav);
// 导出按钮事件
document.getElementById('export-btn').addEventListener('click', (e) => { e.preventDefault(); exportThis(); });
// 缓存全书按钮
document.getElementById('download-book-btn').addEventListener('click', async (e) => {
e.preventDefault();
const btn = e.target;
try {
btn.textContent = '📥 获取目录...';
const bRes = await fetch(`/api/books/${c.book_id}`);
const bData = await bRes.json();
const chs = bData.chapters || [];
if (chs.length === 0) { btn.textContent = '📥 无章节'; return; }
let done = 0;
for (const ch of chs) {
await fetch(`/api/chapters/${ch.id}`);
done++;
btn.textContent = `📥 ${done}/${chs.length}`;
}
btn.textContent = '✅ 缓存完成';
} catch (err) {
btn.textContent = '❌ 缓存失败';
}
});
// 底部工具栏按钮
document.getElementById('bar-prev').onclick = () => { if (prevUrl) location.href = prevUrl; };
document.getElementById('bar-next').onclick = () => { if (nextUrl) location.href = nextUrl; };
document.getElementById('bar-prev').style.opacity = prevUrl ? '1' : '0.3';
document.getElementById('bar-next').style.opacity = nextUrl ? '1' : '0.3';
// 保存阅读进度
saveScrollPosition();
// 阅读统计:记录章节字数和阅读天数
trackReadingStats(c.id, data.content.length);
// 更新书签图标
updateBookmarkIcon();
// 恢复滚动位置
restoreScrollPosition(c.book_id, c.id);
// 加载目录
loadTOC(c.book_id, c.id);
// 预加载下一章
if (data.nextChapter) {
setTimeout(() => {
fetch(`/api/chapters/${data.nextChapter.id}`)
.then(r => r.json())
.then(d => { prefetchedNext = d; })
.catch(() => {});
}, 2000);
}
// 初始化批注系统
initAnnotations();
} catch (e) {
el.innerHTML = `<div class="msg msg-error">${esc(e.message)}</div>`;
}
}
function restoreScrollPosition(bookId, currentChapterId) {
try {
const saved = JSON.parse(localStorage.getItem(`reading_${bookId}`));
if (saved && saved.chapterId === currentChapterId && saved.scrollPct > 0) {
if (settings.readingMode === 'pager') {
// 翻页模式:延迟到分页计算后恢复
requestAnimationFrame(() => {
requestAnimationFrame(() => {
pagerRecalc();
const page = Math.round(saved.scrollPct * (pagerState.totalPages - 1));
pagerGoTo(page, false);
});
});
} else {
// 滚动模式:恢复滚动位置
requestAnimationFrame(() => {
const h = document.documentElement.scrollHeight - window.innerHeight;
if (h > 0) window.scrollTo(0, h * saved.scrollPct);
});
}
} else if (settings.readingMode === 'pager') {
// 没有保存的位置,但需要初始化分页
requestAnimationFrame(() => {
requestAnimationFrame(() => { pagerRecalc(); });
});
}
} catch {
if (settings.readingMode === 'pager') {
requestAnimationFrame(() => {
requestAnimationFrame(() => { pagerRecalc(); });
});
}
}
}
async function loadTOC(bookId, currentChapterId) {
try {
const res = await fetch(`/api/books/${bookId}`);
const data = await res.json();
const list = document.getElementById('toc-list');
document.getElementById('toc-title').textContent = data.book.title;
list.innerHTML = (data.chapters || []).map(ch =>
`<li><a href="/read.html?id=${ch.id}" class="${ch.id === currentChapterId ? 'current' : ''}">${esc(ch.title)}</a></li>`
).join('');
} catch {}
}
function esc(s) {
const d = document.createElement('div');
d.textContent = s || '';
return d.innerHTML;
}
function exportThis() {
if (!window._chapterData) return;
const BOM = '\uFEFF';
const blob = new Blob([BOM + window._chapterData.content], {type:'text/plain;charset=utf-8'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = (window._chapterData.title + '.txt').replace(/[<>:"/\\|?*]/g, '_');
a.click();
URL.revokeObjectURL(url);
}
// ===== 书签功能 =====
function getBookmarks(bookId) {
try { return JSON.parse(localStorage.getItem(`bookmarks_${bookId}`)) || []; }
catch { return []; }
}
function saveBookmarks(bookId, bookmarks) {
localStorage.setItem(`bookmarks_${bookId}`, JSON.stringify(bookmarks));
}
function isBookmarked() {
if (!window._chapterMeta) return false;
const m = window._chapterMeta;
const bms = getBookmarks(m.bookId);
return bms.some(b => b.chapterId === m.chapterId);
}
function updateBookmarkIcon() {
document.getElementById('bookmark-icon').textContent = isBookmarked() ? '★' : '☆';
}
function toggleBookmark() {
if (!window._chapterMeta) return;
const m = window._chapterMeta;
let bms = getBookmarks(m.bookId);
const idx = bms.findIndex(b => b.chapterId === m.chapterId);
if (idx >= 0) {
bms.splice(idx, 1);
} else {
const h = document.documentElement.scrollHeight - window.innerHeight;
const pct = h > 0 ? (window.scrollY / h) : 0;
bms.push({
chapterId: m.chapterId, chapterTitle: m.chapterTitle,
scrollPct: pct, time: Date.now()
});
}
saveBookmarks(m.bookId, bms);
updateBookmarkIcon();
}
document.getElementById('bar-bookmark').addEventListener('click', toggleBookmark);
// ===== 阅读统计 =====
function getReadingStats() {
try { return JSON.parse(localStorage.getItem('readingStats')) || {}; } catch { return {}; }
}
function saveReadingStats(s) {
localStorage.setItem('readingStats', JSON.stringify(s));
}
function trackReadingStats(chId, charCount) {
const s = getReadingStats();
if (!s.totalSeconds) s.totalSeconds = 0;
if (!s.totalChars) s.totalChars = 0;
if (!Array.isArray(s.readChapterIds)) s.readChapterIds = [];
if (!Array.isArray(s.days)) s.days = [];
// 记录今天
const today = new Date().toISOString().slice(0, 10);
if (!s.days.includes(today)) s.days.push(today);
// 首次阅读该章节才累加字数
if (!s.readChapterIds.includes(chId)) {
s.readChapterIds.push(chId);
s.totalChars += charCount;
}
s.lastActiveDate = today;
saveReadingStats(s);
}
// 每30秒累加阅读时长
// 保存定时器引用,以便页面离开时清理
let readingStatsTimer = null;
readingStatsTimer = setInterval(() => {
if (document.hidden) return;
const s = getReadingStats();
s.totalSeconds = (s.totalSeconds || 0) + 30;
saveReadingStats(s);
}, 30000);
// 页面离开时清理定时器,防止内存泄漏
function cleanupReadingStats() {
if (readingStatsTimer) {
clearInterval(readingStatsTimer);
readingStatsTimer = null;
}
}
// 使用 pagehide 事件(比 beforeunload 更可靠)
window.addEventListener('pagehide', cleanupReadingStats);
// 同时监听 beforeunload 作为后备
window.addEventListener('beforeunload', cleanupReadingStats);
// ===== 沉浸模式 =====
const immersiveHint = document.getElementById('immersive-hint');
function toggleImmersive() {
immersiveActive = !immersiveActive;
document.body.classList.toggle('immersive', immersiveActive);
if (immersiveActive) {
document.documentElement.requestFullscreen().catch(() => {});
// 显示退出提示
immersiveHint.classList.add('show');
setTimeout(() => immersiveHint.classList.remove('show'), 2000);
} else {