-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
944 lines (898 loc) · 54.7 KB
/
Copy pathindex.html
File metadata and controls
944 lines (898 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>经济学人智能阅读助手</title>
<style>
:root{
--bg:#efe9dd; /* 整体暖底 */
--panel:#f7f3ea; /* 侧栏 */
--read:#fbf8f1; /* 阅读区,米色护眼 */
--surface:#f8f4ec; /* 卡片面板 */
--ink:#33302a; /* 正文深棕灰,非纯黑 */
--ink-soft:#56524a;
--muted:#938c7e;
--line:#e3dccd;
--accent:#9c1b14; /* 略沉的经济学人红 */
--accent-soft:#f0e3df;
--mark-w:#f7e6a6; --mark-w-b:#d6a800;
--mark-s:#cfe2f4; --mark-s-b:#3f86c9;
}
*{box-sizing:border-box;}
html,body{height:100%;}
body{margin:0; background:var(--bg); color:var(--ink);
font-family:"Iowan Old Style",Georgia,"Songti SC",serif; font-size:16px;}
button{font-family:inherit; cursor:pointer; border:none; border-radius:7px; font-size:13px; padding:7px 13px; transition:.15s;}
button:disabled{opacity:.45; cursor:default;}
.primary{background:var(--accent); color:#fff;}
.primary:hover:not(:disabled){background:#811611;}
.ghost{background:#e8e1d3; color:#4a463e;}
.ghost:hover:not(:disabled){background:#ded6c6;}
.muted{color:var(--muted); font-size:12.5px;}
input[type=text],input[type=password]{font-family:inherit; padding:7px 10px; border:1px solid var(--line); border-radius:7px; font-size:13px; background:#fff;}
/* 顶栏 */
header{display:flex; align-items:center; gap:16px; padding:11px 20px;
background:var(--read); border-bottom:1px solid var(--line);}
.brand{font-weight:700; font-size:16px; color:var(--accent); letter-spacing:.3px;}
.brand small{font-weight:400; color:var(--muted); font-size:12px; margin-left:6px;}
header .sp{flex:1;}
.prog{display:none; align-items:center; gap:10px; min-width:240px;}
.bar-track{flex:1; height:8px; background:#e0d8c7; border-radius:5px; overflow:hidden;}
.bar-fill{height:100%; width:0; background:var(--accent); transition:width .15s;}
#barLabel{font-size:12px; color:var(--muted); white-space:nowrap;}
.keybox{position:relative;}
.keypanel{display:none; position:absolute; right:0; top:34px; background:#fff; border:1px solid var(--line);
border-radius:9px; padding:14px; width:392px; max-height:80vh; overflow-y:auto; box-shadow:0 8px 26px rgba(0,0,0,.12); z-index:30;}
.keypanel.open{display:block;}
.fld{display:block; font-size:11px; color:var(--muted); margin:9px 0 3px;}
.keypanel input, .keypanel select{width:100%; font-family:inherit; padding:7px 9px; border:1px solid var(--line);
border-radius:7px; font-size:13px; background:#fff;}
/* ===== NotebookLM 风格:卡片式三栏 + 可拖拽调宽 + 可折叠 ===== */
.app{display:flex; gap:10px; padding:10px; height:calc(100vh - 56px); align-items:stretch;}
.panel{background:var(--surface); border:1px solid var(--line); border-radius:16px;
display:flex; flex-direction:column; overflow:hidden; min-width:0;}
.panel.left{width:var(--wL,290px); flex:0 0 auto;}
.panel.right{width:var(--wR,340px); flex:0 0 auto;}
.panel.mid{flex:1 1 auto; min-width:340px; background:var(--read);}
.phead{display:flex; align-items:center; gap:10px; padding:13px 16px; border-bottom:1px solid var(--line); flex:0 0 auto;}
.ptitle{font-size:13px; font-weight:600; color:var(--ink); flex:1; min-width:0;
font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;}
.ptitle.t{font-size:17px; line-height:1.3; font-family:"Iowan Old Style",Georgia,serif;}
.ptitle.t .tzh{display:block; font-size:12.5px; color:var(--ink-soft); font-weight:400; margin-top:3px; font-family:"Songti SC",serif;}
.pbody{flex:1 1 auto; overflow-y:auto; padding:14px 16px;}
.panel.mid .pbody{padding:24px 28px 70px;}
.pbody::-webkit-scrollbar{width:9px;} .pbody::-webkit-scrollbar-thumb{background:#d7cdba; border-radius:5px;}
.icon{background:transparent; color:var(--muted); font-size:17px; line-height:1; padding:3px 8px; border-radius:8px;}
.icon:hover{background:rgba(0,0,0,.06); color:var(--ink);}
.chip{background:#e8e1d3; color:#4a463e; font-size:12px; padding:5px 11px; border-radius:16px;}
.chip:hover:not(:disabled){background:#ded6c6;}
.chip.primary{background:var(--accent); color:#fff;} .chip.primary:hover:not(:disabled){background:#811611;}
/* 拖拽分隔条 */
.resizer{flex:0 0 7px; align-self:stretch; cursor:col-resize; border-radius:4px; background:transparent; transition:background .15s;}
.resizer:hover,.resizer.drag{background:#c7d0dc;}
/* 折叠态:收成窄条 */
.panel.collapsed{width:48px!important; flex:0 0 48px;}
.panel.collapsed .pbody{display:none;}
.panel.collapsed .phead{flex-direction:column; padding:12px 4px; gap:10px; border-bottom:none;}
.panel.collapsed .ptitle{writing-mode:vertical-rl; text-orientation:mixed; flex:0 0 auto; font-size:12px;}
.panel.collapsed .chip{display:none;}
/* 左栏:标题列表 */
.issue{font-size:12px; color:var(--muted); margin-bottom:12px;}
.sec{font-size:11px; letter-spacing:.6px; text-transform:uppercase; color:var(--accent);
margin:16px 0 6px; padding-bottom:4px; border-bottom:1px solid var(--line);}
.art{padding:8px 9px; border-radius:7px; cursor:pointer; margin-bottom:2px;}
.art:hover{background:#efe7d7;}
.art.active{background:var(--accent-soft);}
.art .en{font-size:13.5px; line-height:1.35; color:var(--ink);}
.art .zh{font-size:12px; line-height:1.35; color:var(--ink-soft); margin-top:2px;
font-family:"Songti SC","Noto Serif SC",serif;}
.art .pg{float:right; font-size:11px; color:var(--muted); margin-left:6px;}
.empty{color:var(--muted); font-size:13px; padding:30px 6px; text-align:center; line-height:1.7;}
/* 中栏:阅读 */
#reader{max-width:760px; margin:0 auto; font-size:18px; line-height:1.9; color:var(--ink); text-align:justify; hyphens:none;}
#reader p{margin:0 0 1.1em;}
#reader p:last-child{margin-bottom:0;}
.hint{max-width:760px; margin:0 auto 14px; font-size:12.5px; color:var(--muted);}
.mark-word{background:var(--mark-w); border-bottom:2px solid var(--mark-w-b); border-radius:2px; cursor:pointer;}
.mark-sent{background:var(--mark-s); border-bottom:2px solid var(--mark-s-b); border-radius:2px; cursor:pointer;}
/* 右栏:解析 */
.ana{background:var(--read); border:1px solid var(--line); border-radius:10px; padding:12px 13px; margin-bottom:11px;}
.ana .snip{font-size:13.5px; font-weight:600; line-height:1.4; margin-bottom:7px;}
.tag{display:inline-block; font-size:10.5px; padding:1px 7px; border-radius:9px; margin-left:6px; vertical-align:middle; font-weight:400;}
.tag.w{background:var(--mark-w);} .tag.s{background:var(--mark-s);}
.ana .field{font-size:13px; line-height:1.6; margin:5px 0; color:var(--ink-soft);
font-family:"Songti SC","Noto Serif SC",serif;}
.ana .lbl{color:var(--accent); font-size:11px; font-weight:700; margin-right:5px;
font-family:Georgia,serif; letter-spacing:.3px;}
.ana .struct{font-size:12.5px; color:var(--muted); margin-top:4px; padding-left:8px; border-left:2px solid var(--line);}
.pending{color:var(--muted); font-size:12px;}
#popup{position:fixed; display:none; gap:6px; background:#2c2a26; padding:6px; border-radius:9px; z-index:90; box-shadow:0 6px 18px rgba(0,0,0,.25);}
#popup button{background:#3d3a34; color:#f3eee2;} #popup button:hover{background:#504c44;}
/* 即点即查释义卡 */
#wordCard{position:fixed; display:none; z-index:95; width:min(340px,88vw);
background:var(--read); border:1px solid var(--line); border-radius:12px;
box-shadow:0 10px 30px rgba(0,0,0,.18); padding:13px 15px;}
#wordCard .wc-w{font-size:16px; font-weight:700;}
#wordCard .wc-ph{color:var(--muted); font-size:12.5px; margin-left:7px;}
#wordCard .wc-close{position:absolute; right:8px; top:6px; background:transparent; color:var(--muted); font-size:15px; padding:2px 7px;}
#wordCard .wc-close:hover{color:var(--ink);}
#wordCard .field{font-size:13px; line-height:1.6; margin:6px 0 0; color:var(--ink-soft); font-family:"Songti SC","Noto Serif SC",serif;}
#wordCard .lbl{color:var(--accent); font-size:11px; font-weight:700; margin-right:5px; font-family:Georgia,serif;}
/* 全文解析区块 */
.fullana-h{display:flex; align-items:center; gap:8px; font-size:12px; font-weight:700; color:var(--accent);
margin:6px 0 8px; padding-bottom:4px; border-bottom:1px solid var(--line); letter-spacing:.5px;}
.addv{background:#e8e1d3; color:#4a463e; font-size:11px; padding:2px 8px; border-radius:10px; margin-left:6px; vertical-align:middle;}
.addv:hover:not(:disabled){background:#ded6c6;}
/* 不背单词官网入口 */
.bbdc{display:inline-flex; align-items:center; gap:6px; text-decoration:none;
background:#e8e1d3; color:#3a4a47; padding:5px 11px 5px 6px; border-radius:18px; font-size:13px;
font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif; transition:.15s;}
.bbdc:hover{background:#ded6c6;}
.bbdc .lg{width:22px; height:22px; border-radius:6px; display:block; flex:0 0 auto; object-fit:cover;}
.bbdc .fallback{width:22px; height:22px; border-radius:6px; background:#16b6a6; color:#fff;
display:none; align-items:center; justify-content:center; font-size:12px; font-weight:700;
font-family:-apple-system,"PingFang SC",sans-serif;}
.bbdc .ext{font-size:10px; color:var(--muted); margin-left:1px;}
/* 移动端底部分页栏(默认隐藏,窄屏显示)*/
.mtabs{display:none; position:fixed; left:0; right:0; bottom:0; z-index:85;
background:var(--read); border-top:1px solid var(--line);
padding-bottom:env(safe-area-inset-bottom);}
.mtabs button{flex:1; background:transparent; border:none; border-radius:0; color:var(--muted);
display:flex; flex-direction:column; align-items:center; justify-content:center; gap:2px;
padding:8px 0; font-size:19px; line-height:1;
font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;}
.mtabs button span{font-size:11px;}
.mtabs button.active{color:var(--accent);}
.mtabs button.active span{font-weight:700;}
/* ===== 平板 / 手机:单栏分页切换 ===== */
@media(max-width:900px){
html,body{height:100%;}
body{display:flex; flex-direction:column; padding-bottom:calc(58px + env(safe-area-inset-bottom));}
header{flex:0 0 auto; flex-wrap:wrap; gap:10px 12px; padding:10px 14px;}
.app{flex:1 1 auto; min-height:0; height:auto; flex-direction:column; padding:8px; gap:8px;}
.resizer{display:none;}
.phead .icon{display:none;} /* 折叠按钮在移动端无意义 */
.panel{width:auto!important; flex:1 1 auto!important; min-height:0; border-radius:14px;
display:none!important;} /* 默认全部隐藏,仅显示当前分页 */
#app[data-pane="left"] .panel.left,
#app[data-pane="mid"] .panel.mid,
#app[data-pane="right"] .panel.right{display:flex!important;}
.panel.collapsed{width:auto!important; flex:1 1 auto!important;}
.panel.collapsed .pbody{display:block;}
.panel.collapsed .phead{flex-direction:row; padding:13px 16px; border-bottom:1px solid var(--line);}
.panel.collapsed .ptitle{writing-mode:horizontal-tb;}
.panel.mid .pbody{padding:18px 16px 30px;}
#reader{font-size:17px; line-height:1.85;}
#popup button{padding:11px 16px; font-size:15px;} /* 触摸目标更大 */
.keypanel{width:min(392px,92vw); right:0;} /* AI 设置面板不溢出窄屏 */
.mtabs{display:flex;}
}
</style>
</head>
<body>
<header>
<span class="brand">📕 经济学人智能阅读助手<small>中英对照 · 护眼三栏</small></span>
<input type="file" id="file" accept="application/pdf" style="display:none" onchange="upload()" />
<button class="ghost" onclick="document.getElementById('file').click()">导入 PDF</button>
<div class="prog" id="prog"><div class="bar-track"><div class="bar-fill" id="barFill"></div></div><span id="barLabel"></span></div>
<span class="sp"></span>
<a class="bbdc" href="https://learnywhere.cn" target="_blank" rel="noopener"
title="打开「不背单词」官网(登录后到「自制词书」上传导出的 .txt)">
<img class="lg" src="https://learnywhere.cn/favicon.ico" alt="不背单词"
onerror="this.style.display='none';this.nextElementSibling.style.display='inline-flex';" />
<span class="fallback">背</span>不背单词<span class="ext">↗</span>
</a>
<div class="keybox">
<button class="ghost" onclick="document.getElementById('keypanel').classList.toggle('open')">⚙ AI 设置</button>
<div class="keypanel" id="keypanel">
<div style="font-size:13px;margin-bottom:6px;font-weight:600;">AI 模型设置(可选)</div>
<div class="muted">支持 Claude 及任意 OpenAI 兼容接口(DeepSeek、Kimi、智谱、OpenRouter、本地 Ollama、OpenAI 等)。配置仅存于本机浏览器,直连所选服务,不经任何中转。</div>
<label class="fld">服务商预设</label>
<select id="cfgPreset" onchange="applyPreset()">
<option value="">— 自定义 —</option>
<option value="anthropic">Anthropic(Claude 官方)</option>
<option value="openai">OpenAI</option>
<option value="deepseek">DeepSeek</option>
<option value="moonshot">Kimi / Moonshot</option>
<option value="zhipu">智谱 GLM</option>
<option value="openrouter">OpenRouter(聚合,支持浏览器)</option>
<option value="ollama">本地 Ollama</option>
</select>
<label class="fld">接口类型</label>
<select id="cfgFormat">
<option value="openai">OpenAI 兼容 (/chat/completions)</option>
<option value="anthropic">Anthropic (/v1/messages)</option>
</select>
<label class="fld">模型网址 Base URL</label>
<input type="text" id="cfgBase" placeholder="https://api.deepseek.com/v1" />
<label class="fld">API Key</label>
<input type="password" id="cfgKey" placeholder="sk-..." />
<label class="fld">模型</label>
<div class="row" style="gap:6px;">
<input type="text" id="cfgModel" list="modelList" placeholder="deepseek-chat" style="flex:1;" />
<button class="ghost" onclick="fetchModels()" style="white-space:nowrap;">拉取</button>
</div>
<datalist id="modelList"></datalist>
<div class="row" style="margin-top:11px;">
<button class="primary" onclick="saveCfg()">保存</button>
<button class="ghost" onclick="testConn()" style="margin-left:6px;">测试连接</button>
<span class="muted" id="cfgStatus" style="margin-left:8px;"></span>
</div>
<div class="muted" style="margin-top:9px;line-height:1.6;">⚠ 部分服务商不允许浏览器直连(CORS 限制),如 OpenAI、DeepSeek 可能被拦。<b>OpenRouter</b> 和 <b>本地 Ollama</b> 对浏览器最友好;若被拦可改用 mvp 后端版或自建代理。</div>
</div>
</div>
</header>
<div class="app" id="app" data-pane="left">
<section class="panel left" id="pLeft">
<div class="phead">
<span class="ptitle">文章</span>
<button class="chip" id="trBtn" style="display:none" onclick="translateTitles()">中英对照</button>
<button class="icon" id="colL" title="收起" onclick="collapsePanel('left')">‹</button>
</div>
<div class="pbody">
<div class="issue" id="issueHint"></div>
<div id="list"><div class="empty">点击右上角「导入 PDF」<br>开始阅读本期《经济学人》</div></div>
</div>
</section>
<div class="resizer" data-rz="L" title="拖动调节宽度"></div>
<section class="panel mid" id="pMid">
<div class="phead" id="midHead" style="display:none">
<span class="ptitle t" id="artTitle"></span>
<button class="chip" id="anaBtn" onclick="analyzeAll()">解析标记</button>
<button class="chip primary" id="fullBtn" onclick="analyzeArticle()">完成阅读 · 全文解析</button>
</div>
<div class="pbody">
<div class="hint" id="readerHint" style="display:none">用鼠标选中正文里的单词或句子,会弹出「标为生词 / 标为长难句」,标记会出现在右栏。</div>
<div id="reader"><div class="empty" style="margin-top:60px">选择左栏的文章后<br>正文会显示在这里</div></div>
</div>
</section>
<div class="resizer" data-rz="R" title="拖动调节宽度"></div>
<section class="panel right" id="pRight">
<div class="phead">
<button class="icon" id="colR" title="收起" onclick="collapsePanel('right')">›</button>
<span class="ptitle">标记与解析</span>
<button class="chip" id="anaAllBtn" style="display:none" onclick="analyzeAll()">解析全部</button>
<button class="chip" id="exportBtn" title="导出全部生词为 JSON 到 vocab 文件夹(首次会让你选定文件夹,建议选 exports/)" onclick="exportVocab()">导出生词</button>
</div>
<div class="pbody" id="anaList"><div class="empty">阅读时标记的生词<br>和长难句解析会显示在这里</div></div>
</section>
</div>
<nav class="mtabs" id="mtabs">
<button data-pane="left" onclick="setPane('left')">📑<span>文章</span></button>
<button data-pane="mid" onclick="setPane('mid')">📖<span>阅读</span></button>
<button data-pane="right" onclick="setPane('right')">✍️<span>标记</span></button>
</nav>
<div id="popup">
<button onmousedown="mark('word')">查词 · 入生词本</button>
<button onmousedown="mark('sentence')">标为长难句</button>
</div>
<div id="wordCard"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script>
if(window.pdfjsLib) pdfjsLib.GlobalWorkerOptions.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js";
/* ===== 解析逻辑(与后端同算法,已在 Node 验证)===== */
const HEADING_LOW=13.0,HEADING_HIGH=27.0;
const SECTION_NAMES=["The world this week","Leaders","Letters","By Invitation","Briefing","United States","The Americas","Asia","China","Middle East & Africa","Europe","Britain","International","Business","Finance & economics","Science & technology","Culture","Economic & financial indicators","Obituary"];
const COLUMN_NAMES=["LEXINGTON","BANYAN","ASHOKA","CHAGUAN","CHARLEMAGNE","BAGEHOT","THE TELEGRAM","BARTLEBY","SCHUMPETER","BUTTONWOOD","FREE EXCHANGE","BACK STORY","BY INVITATION"];
const NOISE=["scan here","economist.com","events.economist","subscribe","to find out more","contributors include","contents"];
const AD_MARKERS=["economist.com/","events.economist","scan here","forum for business leaders","register now"];
const HINT_RE=/The Economist\s+[A-Z][a-z]+ \d{1,2}[a-z]{2} \d{4}/;
const cleanT=t=>t.replace(/fi/g,"fi").replace(/fl/g,"fl").trim();
const titleCase=s=>s.toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());
function headingBlocks(items){
let cand=items.filter(it=>{const t=it.str.trim();if(!t)return false;
const a=t.replace(/[^A-Za-z]/g,"").length;if(a<=2&&it.size>=19)return false;
return it.size>=HEADING_LOW&&it.size<=HEADING_HIGH;});
cand.sort((a,b)=>(b.y-a.y)||(a.x-b.x));
const lines=[];
for(const it of cand){const p=lines[lines.length-1];
if(p&&Math.abs(p.y-it.y)<3){p.text=(p.text+" "+it.str).trim();p.x=Math.min(p.x,it.x);}
else lines.push({y:it.y,x:it.x,text:it.str.trim()});}
const blocks=[];
for(const ln of lines){const p=blocks[blocks.length-1];
const sc=p&&Math.abs(ln.x-p.x)<18, bl=p&&(p.y-ln.y)>0&&(p.y-ln.y)<26;
if(sc&&bl){p.text=(p.text+" "+ln.text).trim();p.y=ln.y;}else blocks.push({y:ln.y,x:ln.x,text:ln.text});}
return blocks;
}
const pagePlain=items=>items.map(i=>i.str).join("\n");
function parsePages(pages){
const total=pages.length;
if(pages.slice(0,3).map(p=>pagePlain(p.items)).join("").trim().length<=150)
return {issue_hint:null,page_count:total,has_text_layer:false,sections:[]};
let hint=null,sec="(未分类)",pend=null; const arts=[];
for(let pno=0;pno<total;pno++){
if(pno===0)continue;
const items=pages[pno].items, plain=pagePlain(items), low=plain.toLowerCase();
if(hint===null&&pno<12){const m=HINT_RE.exec(plain.replace(/\s+/g," "));if(m)hint=m[0];}
if(AD_MARKERS.some(mk=>low.includes(mk)))continue;
const printed=pno+1;
for(const blk of headingBlocks(items)){
let text=cleanT(blk.text); const tl=text.toLowerCase();
if(NOISE.some(k=>tl.includes(k)))continue;
const s=SECTION_NAMES.find(x=>text===x||text.startsWith(x+" "));
if(s){sec=s;const r=text.slice(s.length).trim();if(!r)continue;text=r;}
if(COLUMN_NAMES.includes(text.toUpperCase())){pend=titleCase(text);continue;}
for(const c of COLUMN_NAMES){if(text.toUpperCase().startsWith(c+" ")){pend=titleCase(c);text=text.slice(c.length).trim();break;}}
let t=text; if(pend){t=pend+": "+t;pend=null;}
arts.push({section:sec,title:t,start_page:printed});
}
}
for(let i=0;i<arts.length;i++){const n=i+1<arts.length?arts[i+1].start_page:total;
arts[i].end_page=(n>arts[i].start_page)?Math.max(arts[i].start_page,n-1):arts[i].start_page;}
const sections=[];
for(const a of arts){if(!sections.length||sections[sections.length-1].section!==a.section)sections.push({section:a.section,articles:[]});
sections[sections.length-1].articles.push({title:a.title,start_page:a.start_page,end_page:a.end_page});}
return {issue_hint:hint,page_count:total,has_text_layer:true,sections};
}
/* 正文重排:按 x 间距还原词间空格、频率直方图分栏、去连字符、还原段落、恢复首字下沉
(多栏顺序与各类版式已在 Node 上用本期多篇文章验证)*/
function lineText(items){
items.sort((a,b)=>a.x-b.x);
let t='', prevEnd=null;
for(const it of items){ if(prevEnd!==null&&it.x-prevEnd>0.22*it.size)t+=' '; t+=it.str; prevEnd=it.x+(it.w||0); }
return t.replace(/\s+/g,' ').trim();
}
function isNoise(t){
if(!t||t.length<2)return true;
if(/the economist/i.test(t)&&/\d{4}/.test(t))return true; // 页眉
if(/^\d{1,3}\s+[A-Z]/.test(t))return true; // 跨版引用 "65 Insuring…"
if(/^[A-Z0-9][A-Z0-9 ,.'&\-]{1,30}$/.test(t)&&!/[a-z]/.test(t))return true; // 全大写地名/kicker
const letters=(t.match(/[A-Za-z]/g)||[]).length;
if(letters<t.length*0.5)return true; // 图表数字/符号为主
return false;
}
function detectCols(items){
const cnt={}; items.forEach(it=>{const k=Math.round(it.x);cnt[k]=(cnt[k]||0)+1;});
const thr=Math.max(4,items.length*0.04);
const peaks=Object.entries(cnt).map(([x,c])=>[+x,+c]).filter(([x,c])=>c>=thr).sort((a,b)=>a[0]-b[0]);
const cols=[];
for(const [x,c] of peaks){ const n=cols.find(g=>Math.abs(g.x-x)<70);
if(n){ if(c>n.c)n.c=c; n.x=Math.min(n.x,x); } else cols.push({x,c}); }
return cols.map(g=>g.x).sort((a,b)=>a-b);
}
function extractFlow(pages,start,end){
end=end||start; const out=[];
for(let pno=start-1;pno<Math.min(end,pages.length);pno++){
const all=pages[pno].items.filter(it=>it.str.trim()&&it.y<=712&&it.y>=24);
let items=all.filter(it=>it.size>=8.3&&it.size<=11);
if(!items.length)continue;
const cols=detectCols(items); if(!cols.length)continue;
const colIdx=x=>{let bi=0,bd=1e9;cols.forEach((c,i)=>{const d=Math.abs(x-c);if(d<bd){bd=d;bi=i;}});return bi;};
const caps=all.filter(it=>/^[A-Za-z]$/.test(it.str.trim())&&it.size>=15)
.map(it=>({L:it.str.trim(),x:it.x,y:it.y,col:colIdx(it.x)}));
const byCol={}; items.forEach(it=>{const c=colIdx(it.x);(byCol[c]=byCol[c]||[]).push(it);});
const pageParas=[];
for(let c=0;c<cols.length;c++){
const its=byCol[c]; if(!its)continue;
its.sort((a,b)=>(b.y-a.y)||(a.x-b.x));
const rows=[]; let cur=null;
for(const it of its){ if(cur&&Math.abs(cur.y-it.y)<3.5)cur.items.push(it); else {if(cur)rows.push(cur);cur={y:it.y,items:[it]};} }
if(cur)rows.push(cur);
const margin=cols[c];
const lines=rows.map(r=>({y:r.y,x:Math.min(...r.items.map(i=>i.x)),text:lineText(r.items)}))
.filter(l=>l.x<=margin+30&&!isNoise(l.text));
if(!lines.length)continue;
let buf='',y0=null,prevInd=false;
const flush=()=>{const t=buf.trim();if(t)pageParas.push({col:c,y:y0,text:t});buf='';};
for(const l of lines){
const ind=l.x>margin+4;
if(buf&&ind&&!prevInd) flush();
if(!buf)y0=l.y;
if(buf&&/[a-z]-$/.test(buf))buf=buf.slice(0,-1)+l.text; else buf=(buf?buf+' ':'')+l.text;
prevInd=ind;
}
flush();
}
for(const cap of caps){ // 恢复首字下沉到同列、y 最接近的段首
let best=null,bd=1e9;
for(const p of pageParas){ if(p.col!==cap.col)continue; const d=Math.abs(p.y-cap.y); if(d<bd){bd=d;best=p;} }
if(best&&bd<40) best.text=cap.L+best.text;
}
pageParas.forEach(p=>out.push(p.text));
}
return out.map(p=>p.replace(/fi/g,'fi').replace(/fl/g,'fl').replace(/\s+/g,' ').trim()).filter(p=>p.length>1);
}
/* ===== 状态 ===== */
let PAGES=[], FLAT=[], TITLE_ZH={}, curKey=null;
const ANN={}; // title -> [{kind,snippet,analysis,sentence,marked_at}]
const ART_FULL={}; // title -> 全文解析结果 {phrases,sentences}
let CUR_PARAS=[]; // 当前文章段落,供全文解析使用
let lastSel="", lastCtx="", lastRect=null; // lastCtx:选区所在段落文本;lastRect:选区位置(释义卡定位)
let vocabDirHandle=null; // File System Access:选定的导出文件夹句柄
window.CUR_ISSUE=""; // 当期期次(由 PDF 解析得到,用于导出文件名)
/* ===== 阶段一:导入 ===== */
async function upload(){
const f=document.getElementById('file').files[0]; if(!f)return;
if(!window.pdfjsLib){alert('PDF.js 未加载,请检查网络后刷新');return;}
const prog=document.getElementById('prog'),fill=document.getElementById('barFill'),label=document.getElementById('barLabel');
prog.style.display='flex'; fill.style.width='0'; label.textContent='读取文件…';
const buf=await f.arrayBuffer(); let doc;
try{doc=await pdfjsLib.getDocument({data:new Uint8Array(buf)}).promise;}
catch(e){label.textContent='无法打开 PDF:'+e.message;return;}
PAGES=[]; const total=doc.numPages;
for(let i=1;i<=total;i++){
const pg=await doc.getPage(i), tc=await pg.getTextContent();
PAGES.push({items:tc.items.filter(it=>it.str!==undefined).map(it=>({str:it.str,size:it.height,x:it.transform[4],y:it.transform[5],w:it.width}))});
const pct=Math.round(i/total*100); fill.style.width=pct+'%'; label.textContent=`解析 ${i}/${total} 页`;
if(i%4===0)await new Promise(r=>setTimeout(r));
}
const r=parsePages(PAGES);
if(!r.has_text_layer){label.textContent='无文本层(扫描版),需先 OCR';return;}
FLAT=[]; r.sections.forEach(s=>s.articles.forEach(a=>FLAT.push(Object.assign({section:s.section},a))));
const n=FLAT.length; label.textContent=`完成:${r.page_count} 页 / ${n} 篇`;
setTimeout(()=>prog.style.display='none',2500);
document.getElementById('issueHint').textContent=r.issue_hint||'';
window.CUR_ISSUE=issueToDate(r.issue_hint);
TITLE_ZH={}; renderList(r.sections);
document.getElementById('trBtn').style.display='';
if(getCfg().key) translateTitles(); // 已配置则自动中英对照
}
function renderList(sections){
const el=document.getElementById('list'); el.innerHTML='';
sections.forEach(s=>{
const h=document.createElement('div'); h.className='sec'; h.textContent=s.section; el.appendChild(h);
s.articles.forEach(a=>{
const d=document.createElement('div'); d.className='art'; d.dataset.title=a.title;
d.innerHTML=`<div class="en"><span class="pg">p.${a.start_page}</span>${esc(a.title)}</div>`+
(TITLE_ZH[a.title]?`<div class="zh">${esc(TITLE_ZH[a.title])}</div>`:``);
d.onclick=()=>openArticle(a,d); el.appendChild(d);
});
});
}
/* 批量翻译标题(一次 API 调用)*/
async function translateTitles(){
if(!getCfg().key){alert('请先在右上角「AI 设置」配置模型与 API Key');return;}
const btn=document.getElementById('trBtn'); btn.disabled=true; btn.textContent='翻译中…';
const titles=FLAT.map(a=>a.title);
const prompt=`把下列英文文章标题翻译成简洁、地道的中文,保持新闻标题风格。`+
`严格按 JSON 数组返回,顺序与输入一致,每项是一个中文字符串,不要编号、不要多余文字。\n\n`+
titles.map((t,i)=>`${i+1}. ${t}`).join("\n");
try{
const arr=await callClaude(prompt);
if(Array.isArray(arr)) titles.forEach((t,i)=>{ if(arr[i]) TITLE_ZH[t]=String(arr[i]); });
rerenderListKeepSections();
}catch(e){ alert('翻译失败:'+e.message); }
btn.disabled=false; btn.textContent='中英对照';
}
function rerenderListKeepSections(){
const sections=[];
FLAT.forEach(a=>{if(!sections.length||sections[sections.length-1].section!==a.section)sections.push({section:a.section,articles:[]});
sections[sections.length-1].articles.push(a);});
renderList(sections);
if(curKey){const d=[...document.querySelectorAll('.art')].find(x=>x.dataset.title===curKey); if(d)d.classList.add('active');}
}
/* ===== 阶段二:阅读 + 标记 ===== */
function openArticle(a,node){
curKey=a.title; if(!ANN[a.title])ANN[a.title]=[];
document.querySelectorAll('.art').forEach(x=>x.classList.remove('active')); if(node)node.classList.add('active');
document.getElementById('midHead').style.display='flex';
document.getElementById('readerHint').style.display='';
document.getElementById('artTitle').innerHTML=esc(a.title)+(TITLE_ZH[a.title]?`<span class="tzh">${esc(TITLE_ZH[a.title])}</span>`:``);
const paras=extractFlow(PAGES,a.start_page,a.end_page);
CUR_PARAS=paras;
const reader=document.getElementById('reader');
reader.innerHTML = paras.length? paras.map(p=>`<p>${esc(p)}</p>`).join("") : '<div class="empty">(未抽取到正文)</div>';
ANN[a.title].forEach(an=>highlight(an.snippet,an.kind==='word'?'mark-word':'mark-sent'));
renderAnn();
const mb=document.querySelector('#pMid .pbody'); if(mb)mb.scrollTop=0;
if(window.matchMedia('(max-width:900px)').matches) setPane('mid'); // 移动端自动切到阅读页
}
const reader=document.getElementById('reader'), popup=document.getElementById('popup');
const TOUCH=window.matchMedia('(pointer:coarse)').matches; // 触摸设备(iPad/iPhone)
function selInReader(sel){
if(!sel||!sel.rangeCount)return false;
let n=sel.getRangeAt(0).commonAncestorContainer; if(n.nodeType!==1)n=n.parentNode;
return reader.contains(n);
}
function showMarkPopup(){
const sel=window.getSelection(), txt=(sel?sel.toString():'').trim();
if(!txt||!selInReader(sel)){popup.style.display='none';return;}
lastSel=txt;
// 抓取选区所在段落文本,供导出时还原"文中原句"
try{let n=sel.getRangeAt(0).startContainer; if(n.nodeType!==1)n=n.parentNode;
let p=n; while(p&&p.tagName!=='P'&&p!==reader)p=p.parentNode;
lastCtx=(p&&p.textContent)||txt;}catch(e){lastCtx=txt;}
const rect=sel.getRangeAt(0).getBoundingClientRect();
lastRect=rect;
popup.style.display='flex'; // 先显示以测量尺寸
const pw=popup.offsetWidth||130, ph=popup.offsetHeight||42;
let left=rect.left+rect.width/2-pw/2;
left=Math.max(8,Math.min(left,window.innerWidth-pw-8)); // 横向不出屏
let top=TOUCH ? rect.bottom+10 : rect.top-ph-8; // 触摸时放选区下方,避开系统菜单
if(top<8) top=rect.bottom+10;
if(top+ph>window.innerHeight-8) top=rect.top-ph-8;
popup.style.left=left+'px'; popup.style.top=top+'px';
}
reader.addEventListener('mouseup',()=>setTimeout(showMarkPopup,0));
let _selTimer;
document.addEventListener('selectionchange',()=>{ // 触摸设备:选区变化后弹出
if(!TOUCH)return;
clearTimeout(_selTimer); _selTimer=setTimeout(showMarkPopup,350);
});
document.addEventListener('mousedown',e=>{if(!popup.contains(e.target))popup.style.display='none';});
/* 移动端分页切换:文章 / 阅读 / 标记 */
function setPane(name){
const app=document.getElementById('app'); if(!app)return;
app.dataset.pane=name;
document.querySelectorAll('#mtabs button').forEach(b=>b.classList.toggle('active',b.dataset.pane===name));
}
function mark(kind){
popup.style.display='none'; if(!lastSel||!curKey)return;
const dup=ANN[curKey].find(a=>a.snippet===lastSel&&a.kind===kind);
if(dup){ if(kind==='word') showWordCard(dup); lastSel=""; return; }
const a={kind,snippet:lastSel,analysis:null,
sentence:kind==='word'?sentenceAround(lastCtx,lastSel):lastSel,
marked_at:new Date().toISOString()};
ANN[curKey].push(a);
highlight(a.snippet,kind==='word'?'mark-word':'mark-sent');
renderAnn(); lastSel="";
if(kind==='word') lookupWord(a); // 即点即查:立即弹释义卡
}
/* ===== 即点即查释义卡 ===== */
const wordCard=document.getElementById('wordCard');
async function lookupWord(a){
showWordCard(a); // 先显示"查询中…"
if(a.analysis) return;
if(!getCfg().key){ a.analysis=mockWord(); showWordCard(a); renderAnn(); return; }
try{ a.analysis=(await callLLM(WORD_PROMPT.replace('{W}',a.snippet).replace('{C}',a.sentence||'')))||mockWord(); }
catch(e){ a.analysis={_error:e.message}; }
showWordCard(a); renderAnn();
}
function showWordCard(a){
const x=a.analysis||{}; let body;
if(!a.analysis) body='<div class="field"><span class="lbl">…</span>查询中,请稍候</div>';
else if(x._error) body=`<div class="field"><span class="lbl">✗</span>查询失败:${esc(x._error)}(可在右栏点击重试)</div>`;
else body=
`<div class="field"><span class="lbl">义</span>${esc(x.context_meaning||'')}${x.pos?' ('+esc(x.pos)+')':''}</div>`+
((x.common_meanings&&x.common_meanings.length)?`<div class="field"><span class="lbl">项</span>${esc(x.common_meanings.join(';'))}</div>`:``)+
(x.example?`<div class="field"><span class="lbl">例</span>${esc(x.example)}</div>`:``)+
`<div class="field" style="margin-top:8px;color:var(--muted);font-size:11.5px;">已加入生词本 ✓(导出时同步不背单词)</div>`;
wordCard.innerHTML=`<button class="wc-close" onclick="wordCard.style.display='none'">✕</button>`+
`<span class="wc-w">${esc(a.snippet)}</span>${x.phonetic?`<span class="wc-ph">${esc(x.phonetic)}</span>`:``}`+body;
wordCard.style.display='block';
const r=lastRect, cw=wordCard.offsetWidth||340, ch=wordCard.offsetHeight||120;
let left=r?Math.max(8,Math.min(r.left,window.innerWidth-cw-8)):(window.innerWidth-cw)/2;
let top=r?(r.bottom+12):120;
if(r&&top+ch>window.innerHeight-8) top=Math.max(8,r.top-ch-10);
wordCard.style.left=left+'px'; wordCard.style.top=top+'px';
}
document.addEventListener('mousedown',e=>{
if(!wordCard.contains(e.target)&&!popup.contains(e.target)) wordCard.style.display='none';
});
/* 从段落文本中切出包含生词的整句,作为导出的"文中原句" */
function sentenceAround(ctx,sel){
if(!ctx)return"";
const idx=ctx.indexOf(sel); if(idx<0)return ctx.trim().slice(0,300);
const before=ctx.slice(0,idx), after=ctx.slice(idx);
const bs=Math.max(before.lastIndexOf('. '),before.lastIndexOf('? '),before.lastIndexOf('! '));
const start=bs<0?0:bs+2;
const er=after.search(/[.?!](\s|$)/);
const end=er<0?ctx.length:idx+er+1;
return ctx.slice(start,end).trim();
}
function highlight(text,cls){
const safe=text.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
try{reader.innerHTML=reader.innerHTML.replace(new RegExp(safe),`<span class="${cls}">${esc(text)}</span>`);}catch(e){}
}
/* ===== 生词导出(写入 vocab 文件夹)===== */
const MONTHS={January:1,February:2,March:3,April:4,May:5,June:6,July:7,August:8,September:9,October:10,November:11,December:12};
function issueToDate(hint){
const m=(hint||'').match(/([A-Z][a-z]+)\s+(\d{1,2})[a-z]{2}\s+(\d{4})/);
if(!m||!MONTHS[m[1]])return new Date().toISOString().slice(0,10);
return `${m[3]}-${String(MONTHS[m[1]]).padStart(2,'0')}-${String(+m[2]).padStart(2,'0')}`;
}
function toast(msg,ok=true){
let t=document.getElementById('toast');
if(!t){t=document.createElement('div');t.id='toast';
t.style.cssText='position:fixed;left:50%;bottom:28px;transform:translateX(-50%);z-index:9999;'
+'padding:10px 16px;border-radius:8px;font-size:13px;color:#fff;max-width:80vw;box-shadow:0 4px 16px rgba(0,0,0,.25);';
document.body.appendChild(t);}
t.style.background=ok?'#1f8a4c':'#c0392b'; t.textContent=msg; t.style.opacity='1';
clearTimeout(t._h); t._h=setTimeout(()=>{t.style.transition='opacity .5s';t.style.opacity='0';},3500);
}
/* File System Access:首次选定文件夹,之后用 IndexedDB 记住句柄直接写入 */
function _idb(){return new Promise((res,rej)=>{const r=indexedDB.open('reader_fs',1);
r.onupgradeneeded=()=>r.result.createObjectStore('h');r.onsuccess=()=>res(r.result);r.onerror=()=>rej(r.error);});}
async function _idbGet(k){const db=await _idb();return new Promise((res,rej)=>{const q=db.transaction('h').objectStore('h').get(k);q.onsuccess=()=>res(q.result);q.onerror=()=>rej(q.error);});}
async function _idbSet(k,v){const db=await _idb();return new Promise((res,rej)=>{const q=db.transaction('h','readwrite').objectStore('h').put(v,k);q.onsuccess=()=>res();q.onerror=()=>rej(q.error);});}
async function _perm(h){const o={mode:'readwrite'};
if((await h.queryPermission(o))==='granted')return true;
if((await h.requestPermission(o))==='granted')return true; return false;}
async function ensureVocabDir(forcePick){
if(!window.showDirectoryPicker)return null; // 浏览器不支持→走下载兜底
if(!forcePick){
if(vocabDirHandle&&await _perm(vocabDirHandle))return vocabDirHandle;
try{const saved=await _idbGet('vocabDir'); if(saved&&await _perm(saved)){vocabDirHandle=saved;return saved;}}catch(e){}
}
vocabDirHandle=await window.showDirectoryPicker({mode:'readwrite'});
try{await _idbSet('vocabDir',vocabDirHandle);}catch(e){}
return vocabDirHandle;
}
function collectWords(){
const words=[];
for(const [title,anns] of Object.entries(ANN)){
for(const a of anns){
if(a.kind!=='word'||!a.snippet||!a.snippet.trim())continue;
const an=a.analysis||{};
words.push({word:a.snippet.trim(),pos:an.pos||"",sentence:a.sentence||an.example||"",
definition:an.context_meaning||"",article_title:title,
marked_at:a.marked_at||new Date().toISOString()});
}
}
return words;
}
/* 写一个文件:优先写入选定文件夹,失败/不支持则下载。返回 'dir' | 'download' */
async function writeOut(dir,fname,content,mime){
if(dir){
try{const fh=await dir.getFileHandle(fname,{create:true});
const w=await fh.createWritable(); await w.write(content); await w.close(); return 'dir';}
catch(e){console.warn('写入文件夹失败,改用下载:',e);}
}
const url=URL.createObjectURL(new Blob([content],{type:mime}));
const a=document.createElement('a'); a.href=url; a.download=fname; a.click(); URL.revokeObjectURL(url);
return 'download';
}
/* 把生词去重(忽略大小写)、小写,整理成不背单词可直接导入的「每行一词」文本 */
function toBubeiTxt(words){
const seen=new Set(), lines=[];
for(const w of words){const k=(w.word||'').trim().toLowerCase(); if(!k||seen.has(k))continue; seen.add(k); lines.push(k);}
return lines;
}
async function exportVocab(){
const words=collectWords();
if(!words.length){toast('还没有标注任何生词',false);return;}
const issue=window.CUR_ISSUE||new Date().toISOString().slice(0,10);
const lines=toBubeiTxt(words);
const txt=lines.join('\n')+'\n'; // 不背单词导入用
const json=JSON.stringify({issue,exported_at:new Date().toISOString(),source:"经济学人智能阅读器",words},null,2); // 流水线/存档用
let dir=null;
try{ dir=await ensureVocabDir(false); }
catch(e){ if(e&&e.name==='AbortError')return; console.warn('选择文件夹失败:',e); dir=null; }
const where=await writeOut(dir,`vocab_${issue}.txt`,txt,'text/plain;charset=utf-8');
await writeOut(where==='dir'?dir:null,`vocab_${issue}.json`,json,'application/json');
if(where==='dir')
toast(`已导出 ${lines.length} 个生词 → ${vocabDirHandle.name}/vocab_${issue}.txt · 运行 python3 bubei_sync.py 可全自动上传不背单词`);
else
toast(`已下载 vocab_${issue}.txt 与 .json,请放入 exports/ 后运行 bubei_sync.py 自动上传`);
}
/* ===== 阶段三:解析(右栏)===== */
const SENT_PROMPT=`你是「经济学人智能阅读助手」的长难句解析模块,为中文母语的英语学习者解析句子。仅输出 JSON:{translation,backbone,grammar_points(数组),difficulty_note}。先拆主干,译文地道。只返回 JSON。\n\n【句子】{S}`;
const WORD_PROMPT=`你是「经济学人智能阅读助手」的单词查询模块。仅输出 JSON:{phonetic,pos,context_meaning,common_meanings(数组),example}。结合【原句】优先解释该词在语境中的实际含义。只返回 JSON。\n\n【单词/短语】{W}\n【原句】{C}`;
const ART_PROMPT=`你是「经济学人智能阅读助手」的全文解析模块,面向中文母语英语学习者。通读文章,只输出 JSON:\n{"phrases":[{"phrase":"","meaning":"","usage":""}],"sentences":[{"sentence":"","translation":"","backbone":"","grammar_points":[""]}]}\nphrases 挑选 8-12 个最值得积累的高频短语、地道搭配或习语(meaning 给中文义,usage 摘录文中含该短语的原句片段);sentences 挑选全文最复杂的 4-6 个长难句(translation 给通顺中文译文,backbone 拆主谓宾主干,grammar_points 列出从句/非谓语/倒装等关键语法点并简要解释)。只返回 JSON,不要多余文字。\n\n【文章】{T}`;
/* 读取 LLM 配置(兼容早期仅存 Anthropic key 的版本)*/
function getCfg(){
let c={}; try{c=JSON.parse(localStorage.getItem('reader_llm_cfg')||'{}');}catch(e){}
if((!c||!c.key)&&localStorage.getItem('reader_api_key'))
c={format:'anthropic',base:'https://api.anthropic.com',key:localStorage.getItem('reader_api_key'),model:'claude-sonnet-4-6'};
return c||{};
}
function llmEndpoint(c){
const base=(c.base||'').replace(/\/+$/,'');
return c.format==='anthropic' ? base+'/v1/messages' : base+'/chat/completions';
}
function llmHeaders(c){
return c.format==='anthropic'
? {'content-type':'application/json','x-api-key':c.key,'anthropic-version':'2023-06-01','anthropic-dangerous-direct-browser-access':'true'}
: {'content-type':'application/json','authorization':'Bearer '+c.key};
}
function extractJSON(text){
const s=text.indexOf('{'), b=text.indexOf('['); let i=(s<0)?b:(b<0?s:Math.min(s,b));
if(i<0) return null;
const close=text.lastIndexOf(text[i]==='{'?'}':']');
return JSON.parse(text.slice(i,close+1));
}
/* 统一调用:根据配置走 Anthropic 或 OpenAI 兼容接口 */
async function callLLM(prompt,maxTokens=2500){
const c=getCfg(); if(!c.key||!c.base||!c.model) return null;
const body={model:c.model,max_tokens:maxTokens,messages:[{role:'user',content:prompt}]};
const resp=await fetch(llmEndpoint(c),{method:'POST',headers:llmHeaders(c),body:JSON.stringify(body)});
if(!resp.ok)throw new Error('API '+resp.status+':'+(await resp.text()).slice(0,160));
const data=await resp.json();
const text=c.format==='anthropic' ? data.content[0].text : data.choices[0].message.content;
return extractJSON(text);
}
const callClaude=callLLM; // 兼容旧调用名
const mockSent=()=>({translation:'(占位)填入 API Key 后返回真实译文',backbone:'(占位)',grammar_points:['填入 Key 获取语法点'],_mock:true});
const mockWord=()=>({context_meaning:'(占位)填入 API Key 后返回真实释义',common_meanings:['填入 Key 获取义项'],_mock:true});
async function analyzeAll(){
if(!curKey)return; const list=ANN[curKey]||[];
const btn=document.getElementById('anaBtn'), btn2=document.getElementById('anaAllBtn');
btn.disabled=btn2.disabled=true;
for(const a of list){ if(!a.analysis) await analyzeOne(a,false); }
renderAnn(); btn.disabled=btn2.disabled=false;
}
/* ===== 全文解析:高频短语 + 长难句精讲 ===== */
async function analyzeArticle(){
if(!curKey||!CUR_PARAS.length){toast('请先选择一篇文章',false);return;}
if(!getCfg().key){alert('请先在右上角「AI 设置」配置模型与 API Key');return;}
const btn=document.getElementById('fullBtn'); btn.disabled=true; btn.textContent='全文解析中…';
try{
const text=CUR_PARAS.join('\n\n').slice(0,16000);
const r=await callLLM(ART_PROMPT.replace('{T}',text),4000);
if(!r) throw new Error('模型未返回有效 JSON');
ART_FULL[curKey]=r;
analyzeAll(); // 顺带解析未处理的手动标记
toast(`全文解析完成:短语 ${(r.phrases||[]).length} 个 · 长难句 ${(r.sentences||[]).length} 句`);
}catch(e){ alert('全文解析失败:'+e.message); }
btn.disabled=false; btn.textContent='完成阅读 · 全文解析';
renderAnn();
if(window.matchMedia('(max-width:900px)').matches) setPane('right');
}
function addPhraseToVocab(i){
const f=ART_FULL[curKey]; if(!f||!f.phrases||!f.phrases[i])return;
const p=f.phrases[i];
if(ANN[curKey].some(a=>a.kind==='word'&&a.snippet===p.phrase)){toast('该短语已在生词本');return;}
ANN[curKey].push({kind:'word',snippet:p.phrase,
analysis:{context_meaning:p.meaning||'',common_meanings:[],example:p.usage||''},
sentence:p.usage||'',marked_at:new Date().toISOString()});
highlight(p.phrase,'mark-word'); renderAnn(); toast(`「${p.phrase}」已入生词本`);
}
async function analyzeOne(a,render=true){
try{
if(a.kind==='sentence') a.analysis=(await callClaude(SENT_PROMPT.replace('{S}',a.snippet)))||mockSent();
else a.analysis=(await callClaude(WORD_PROMPT.replace('{W}',a.snippet).replace('{C}',a.sentence||'')))||mockWord();
}catch(e){a.analysis={_error:e.message};}
if(render)renderAnn();
}
function renderAnn(){
const el=document.getElementById('anaList');
const list=curKey?(ANN[curKey]||[]):[];
const full=curKey?ART_FULL[curKey]:null;
if((!list||!list.length)&&!full){el.innerHTML='<div class="empty">阅读时标记的生词<br>和长难句解析会显示在这里</div>';return;}
el.innerHTML='';
if(full){
if(full.phrases&&full.phrases.length){
const h=document.createElement('div'); h.className='fullana-h'; h.textContent='📌 高频短语 · 地道搭配'; el.appendChild(h);
full.phrases.forEach((p,i)=>{
const w=document.createElement('div'); w.className='ana';
w.innerHTML=`<div class="snip">${esc(p.phrase||'')}<button class="addv" onclick="addPhraseToVocab(${i})">+生词本</button></div>`+
`<div class="field"><span class="lbl">义</span>${esc(p.meaning||'')}</div>`+
(p.usage?`<div class="struct">${esc(p.usage)}</div>`:``);
el.appendChild(w);
});
}
if(full.sentences&&full.sentences.length){
const h=document.createElement('div'); h.className='fullana-h'; h.textContent='🧩 长难句精讲'; el.appendChild(h);
full.sentences.forEach(s=>{
const w=document.createElement('div'); w.className='ana';
w.innerHTML=`<div class="snip">${esc(s.sentence||'')}</div>`+
`<div class="field"><span class="lbl">译</span>${esc(s.translation||'')}</div>`+
(s.backbone?`<div class="field"><span class="lbl">干</span>${esc(s.backbone)}</div>`:``)+
((s.grammar_points&&s.grammar_points.length)?`<div class="struct">${esc(s.grammar_points.join(';'))}</div>`:``);
el.appendChild(w);
});
}
}
if(list&&list.length&&full){
const h=document.createElement('div'); h.className='fullana-h'; h.textContent='✍️ 我的标记'; el.appendChild(h);
}
list.forEach((a,idx)=>{
const x=a.analysis||{}, tag=a.kind==='word'?'<span class="tag w">生词</span>':'<span class="tag s">长难句</span>';
let body;
if(!a.analysis) body=`<div class="pending">未解析 · 点此解析</div>`;
else if(x._error) body=`<div class="pending">解析失败:${esc(x._error)}</div>`;
else if(a.kind==='sentence') body=
`<div class="field"><span class="lbl">译</span>${esc(x.translation||'')}</div>`+
(x.backbone?`<div class="field"><span class="lbl">干</span>${esc(x.backbone)}</div>`:``)+
((x.grammar_points&&x.grammar_points.length)?`<div class="struct">${esc(x.grammar_points.join(';'))}</div>`:``);
else body=
`<div class="field"><span class="lbl">义</span>${esc(x.context_meaning||'')}${x.pos?' ('+esc(x.pos)+')':''}</div>`+
((x.common_meanings&&x.common_meanings.length)?`<div class="struct">常见义:${esc(x.common_meanings.join(';'))}</div>`:``)+
(x.example?`<div class="struct">${esc(x.example)}</div>`:``);
const w=document.createElement('div'); w.className='ana';
w.innerHTML=`<div class="snip">${esc(a.snippet)} ${tag} ${x._mock?'<span class="muted">占位</span>':''}</div>${body}`;
w.onclick=()=>{ if(!a.analysis||a.analysis._error) analyzeOne(a); };
el.appendChild(w);
});
document.getElementById('anaAllBtn').style.display = list.some(a=>!a.analysis)?'':'none';
}
/* ===== AI 配置与工具 ===== */
const PRESETS={
anthropic:{f:'anthropic',b:'https://api.anthropic.com',m:'claude-sonnet-4-6'},
openai:{f:'openai',b:'https://api.openai.com/v1',m:'gpt-4o-mini'},
deepseek:{f:'openai',b:'https://api.deepseek.com/v1',m:'deepseek-chat'},
moonshot:{f:'openai',b:'https://api.moonshot.cn/v1',m:'moonshot-v1-32k'},
zhipu:{f:'openai',b:'https://open.bigmodel.cn/api/paas/v4',m:'glm-4-flash'},
openrouter:{f:'openai',b:'https://openrouter.ai/api/v1',m:'anthropic/claude-3.5-sonnet'},
ollama:{f:'openai',b:'http://localhost:11434/v1',m:'llama3.1'},
};
function sanitizeKey(raw){
let k=(raw||'').trim().replace(/[-]/g,'');
return k.replace(/^["']|["']$/g,'').replace(/^Bearer\s+/i,'').trim();
}
function applyPreset(){
const p=PRESETS[document.getElementById('cfgPreset').value]; if(!p)return;
document.getElementById('cfgFormat').value=p.f;
document.getElementById('cfgBase').value=p.b;
document.getElementById('cfgModel').value=p.m;
}
function readForm(){
return {format:document.getElementById('cfgFormat').value,
base:document.getElementById('cfgBase').value.trim(),
key:sanitizeKey(document.getElementById('cfgKey').value),
model:document.getElementById('cfgModel').value.trim()};
}
function saveCfg(){
const c=readForm(), st=document.getElementById('cfgStatus');
if(!c.key||!c.base||!c.model){st.innerHTML='<span style="color:#9c1b14">请填齐 网址 / Key / 模型</span>';return;}
localStorage.setItem('reader_llm_cfg',JSON.stringify(c));
localStorage.removeItem('reader_api_key'); // 清掉旧式存储,统一走新配置
document.getElementById('cfgKey').value=c.key;
st.innerHTML='<span style="color:#2e7d32">已保存 ✓</span>';
}
async function testConn(){
const c=readForm(), st=document.getElementById('cfgStatus');
if(!c.key||!c.base||!c.model){st.innerHTML='<span style="color:#9c1b14">请填齐 网址 / Key / 模型</span>';return;}
st.textContent='测试中…';
try{
const body=c.format==='anthropic'
? {model:c.model,max_tokens:5,messages:[{role:'user',content:'hi'}]}
: {model:c.model,max_tokens:5,messages:[{role:'user',content:'hi'}]};
const r=await fetch(llmEndpoint(c),{method:'POST',headers:llmHeaders(c),body:JSON.stringify(body)});
if(r.ok){ saveCfg(); st.innerHTML='<span style="color:#2e7d32">连接成功 ✓ 模型可用</span>'; return; }
const txt=(await r.text()).slice(0,200); let hint='';
if(r.status===401||r.status===403)hint=':Key 无效或无权限';
else if(r.status===404)hint=':网址或模型名不对(检查 Base URL 与模型)';
else if(r.status===400&&/credit|balance|insufficient/i.test(txt))hint=':账户余额不足';
else if(r.status===429)hint=':频率/额度限制,请稍后再试';
st.innerHTML=`<span style="color:#9c1b14">失败 ${r.status}${esc(hint)}</span>`;
}catch(e){ st.innerHTML='<span style="color:#9c1b14">连接失败(可能被 CORS 拦截):'+esc(e.message)+'</span>'; }
}
async function fetchModels(){
const c=readForm(), st=document.getElementById('cfgStatus');
if(!c.key||!c.base){st.innerHTML='<span style="color:#9c1b14">请先填网址和 Key</span>';return;}
const base=c.base.replace(/\/+$/,'');
const url=c.format==='anthropic'?base+'/v1/models':base+'/models';
const headers=c.format==='anthropic'
? {'x-api-key':c.key,'anthropic-version':'2023-06-01','anthropic-dangerous-direct-browser-access':'true'}
: {'authorization':'Bearer '+c.key};
st.textContent='拉取模型…';
try{
const r=await fetch(url,{headers}); if(!r.ok)throw new Error('HTTP '+r.status);
const d=await r.json(); const arr=(d.data||d.models||[]).map(m=>m.id||m.name).filter(Boolean);
const dl=document.getElementById('modelList'); dl.innerHTML='';
arr.forEach(id=>{const o=document.createElement('option');o.value=id;dl.appendChild(o);});
st.innerHTML=`<span style="color:#2e7d32">已拉取 ${arr.length} 个模型,点输入框选择</span>`;
}catch(e){ st.innerHTML='<span style="color:#9c1b14">拉取失败:'+esc(e.message)+'(可手动输入模型名)</span>'; }
}
function loadCfgToForm(){
const c=getCfg(); if(!c.format)return;
document.getElementById('cfgFormat').value=c.format||'openai';
document.getElementById('cfgBase').value=c.base||'';
document.getElementById('cfgKey').value=c.key||'';
document.getElementById('cfgModel').value=c.model||'';
document.getElementById('cfgStatus').innerHTML='<span style="color:#2e7d32">已有配置 ✓</span>';
}
function esc(s){return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}
/* ===== 面板拖拽调宽 / 折叠(NotebookLM 风格)===== */
const clampW=(v,a,b)=>Math.max(a,Math.min(b,v));
function collapsePanel(side,silent){
const p=document.getElementById(side==='left'?'pLeft':'pRight');
const btn=document.getElementById(side==='left'?'colL':'colR');
const col=p.classList.toggle('collapsed');
if(!silent) localStorage.setItem('reader_col_'+side, col?'1':'0');
if(btn) btn.textContent = side==='left' ? (col?'›':'‹') : (col?'‹':'›');
}
function initLayout(){
const pL=document.getElementById('pLeft'), pR=document.getElementById('pRight');
const wL=localStorage.getItem('reader_wL'), wR=localStorage.getItem('reader_wR');
if(wL)pL.style.width=wL+'px'; if(wR)pR.style.width=wR+'px';
if(localStorage.getItem('reader_col_left')==='1') collapsePanel('left',true);
if(localStorage.getItem('reader_col_right')==='1') collapsePanel('right',true);
let active=null,sx=0,sL=0,sR=0;
document.querySelectorAll('.resizer').forEach(rz=>rz.addEventListener('mousedown',e=>{
active=rz.dataset.rz; sx=e.clientX; sL=pL.offsetWidth; sR=pR.offsetWidth;
rz.classList.add('drag'); document.body.style.userSelect='none'; e.preventDefault();
}));
window.addEventListener('mousemove',e=>{
if(!active)return; const dx=e.clientX-sx;
if(active==='L'){const w=clampW(sL+dx,210,560); pL.classList.remove('collapsed'); pL.style.width=w+'px'; localStorage.setItem('reader_wL',w);}
else{const w=clampW(sR-dx,230,640); pR.classList.remove('collapsed'); pR.style.width=w+'px'; localStorage.setItem('reader_wR',w);}
});
window.addEventListener('mouseup',()=>{active=null; document.querySelectorAll('.resizer').forEach(r=>r.classList.remove('drag')); document.body.style.userSelect='';});
}
window.addEventListener('load',()=>{ loadCfgToForm(); initLayout(); setPane('left'); });
</script>
</body>
</html>