-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
906 lines (835 loc) · 35.8 KB
/
Copy pathindex.html
File metadata and controls
906 lines (835 loc) · 35.8 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文本差异对比工具</title>
<link rel="icon" type="image/svg+xml" href="favicon.svg">
<style>
:root {
--bg: #f6f7f9;
--panel: #ffffff;
--border: #e5e7eb;
--border-strong: #d1d5db;
--text: #1f2328;
--text-muted: #6b7280;
--text-faint: #9ca3af;
--accent: #2563eb;
--accent-hover: #1d4ed8;
--accent-soft: #eff6ff;
--danger: #dc2626;
--danger-soft: #fef2f2;
--shadow: 0 1px 3px rgba(0,0,0,.06), 0 1px 2px rgba(0,0,0,.04);
--radius: 10px;
/* diff 专用配色(新增变量) */
--c-add: #16a34a;
--c-add-bg: #dcfce7;
--c-add-strong: #bbf7d0;
--c-del: #dc2626;
--c-del-bg: #fee2e2;
--c-del-strong: #fecaca;
--c-change-bg: #fef9c3;
}
html.dark {
--bg: #0d1117;
--panel: #161b22;
--border: #30363d;
--border-strong: #484f58;
--text: #e6edf3;
--text-muted: #9198a1;
--text-faint: #6e7681;
--accent: #58a6ff;
--accent-hover: #79b8ff;
--accent-soft: #1a2332;
--danger: #f87171;
--danger-soft: #2a1a1c;
--shadow: 0 1px 3px rgba(0,0,0,.4);
--c-add: #4ade80;
--c-add-bg: #14532d;
--c-add-strong: #166534;
--c-del: #f87171;
--c-del-bg: #7f1d1d;
--c-del-strong: #991b1b;
--c-change-bg: #713f12;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC",
"Hiragino Sans GB", "Microsoft YaHei", Roboto, Helvetica, Arial, sans-serif;
background: var(--bg);
color: var(--text);
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
}
/* ---------- Header ---------- */
header {
display: flex; align-items: center; gap: 12px;
padding: 14px 20px; background: var(--panel);
border-bottom: 1px solid var(--border); flex-shrink: 0;
}
.logo { display: flex; align-items: center; gap: 10px; font-size: 16px; font-weight: 650; }
.logo .mark {
width: 30px; height: 30px; border-radius: 8px;
display: grid; place-items: center;
background: linear-gradient(135deg, #2563eb, #7c3aed);
color: #fff; font-size: 16px; font-weight: 700; line-height: 1;
}
.logo .sub { font-size: 12px; color: var(--text-muted); font-weight: 400; }
.spacer { flex: 1; }
.icon-btn {
width: 36px; height: 36px; border-radius: 8px;
border: 1px solid var(--border); background: var(--panel);
color: var(--text-muted); cursor: pointer;
display: grid; place-items: center; transition: all .15s;
}
.icon-btn:hover { color: var(--text); border-color: var(--border-strong); background: var(--bg); }
.icon-btn svg { width: 18px; height: 18px; }
header .icon-btn { border: none; background: transparent; }
header .icon-btn:hover { background: var(--bg); border-color: transparent; }
/* ---------- Toolbar ---------- */
.toolbar {
display: flex; flex-wrap: wrap; align-items: center; gap: 8px;
padding: 10px 20px; background: var(--panel);
border-bottom: 1px solid var(--border); flex-shrink: 0;
}
.btn {
display: inline-flex; align-items: center; gap: 6px;
height: 34px; padding: 0 12px; border-radius: 8px;
border: 1px solid var(--border); background: var(--panel); color: var(--text);
font-size: 13px; cursor: pointer; transition: all .15s; white-space: nowrap;
}
.btn:hover:not(:disabled) { border-color: var(--border-strong); background: var(--bg); }
.btn:disabled { opacity: .45; cursor: not-allowed; }
.btn svg { width: 15px; height: 15px; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn.primary:hover:not(:disabled) { background: var(--accent-hover); border-color: var(--accent-hover); }
.btn.ghost { border-color: transparent; color: var(--text-muted); }
.btn.ghost:hover { background: var(--bg); color: var(--text); }
.btn.toggle.active { background: var(--accent-soft); color: var(--accent); border-color: var(--accent); }
.divider { width: 1px; height: 22px; background: var(--border); margin: 0 4px; }
.seg {
display: inline-flex; border: 1px solid var(--border); border-radius: 8px; overflow: hidden;
}
.seg button {
height: 34px; padding: 0 11px; border: 0; background: var(--panel);
color: var(--text-muted); font-size: 12.5px; cursor: pointer;
border-right: 1px solid var(--border); transition: all .15s;
}
.seg button:last-child { border-right: 0; }
.seg button:hover { background: var(--bg); color: var(--text); }
.seg button.active { background: var(--accent-soft); color: var(--accent); }
.stat { font-size: 12px; display: inline-flex; align-items: center; gap: 6px; }
.stat.hidden { display: none !important; }
.stat .add { color: var(--c-add); font-weight: 600; }
.stat .del { color: var(--c-del); font-weight: 600; }
.stat .mod { color: #ca8a04; font-weight: 600; }
html.dark .stat .mod { color: #facc15; }
.stat .dot { color: var(--text-faint); }
/* ---------- Main ---------- */
main {
flex: 1; overflow: hidden;
display: flex; flex-direction: column;
padding: 16px 20px 40px; gap: 16px;
}
main.input-only .input-panel { flex: 1; }
main.input-only .diff-panel { display: none; }
main.has-diff .input-panel { flex: 0 0 220px; }
main.has-diff .diff-panel { display: flex; }
/* ---------- 输入区 ---------- */
.input-panel {
display: flex; gap: 14px;
min-height: 220px; transition: flex .2s;
}
.input-col {
flex: 1; display: flex; flex-direction: column;
background: var(--panel);
border: 1px solid var(--border); border-radius: var(--radius);
box-shadow: var(--shadow); overflow: hidden;
}
.input-head {
display: flex; align-items: center; gap: 8px;
padding: 8px 12px; border-bottom: 1px solid var(--border);
background: var(--bg); font-size: 13px; color: var(--text-muted);
}
.input-head .input-title { flex: 1; font-weight: 600; color: var(--text); }
.input-head .icon-btn { width: 28px; height: 28px; border: none; background: transparent; }
.input-col textarea {
flex: 1; width: 100%; min-height: 120px;
border: 0; background: var(--panel); color: var(--text);
padding: 12px; font-family: "SF Mono", "JetBrains Mono", "Fira Code", Menlo, Consolas, monospace;
font-size: 13px; line-height: 1.7; resize: none; outline: none;
white-space: pre; overflow: auto;
}
.input-col textarea::placeholder { color: var(--text-faint); }
.input-col textarea.dragover { background: var(--accent-soft); }
/* ---------- Diff 结果区 ---------- */
.diff-panel {
flex: 1; flex-direction: column;
background: var(--panel);
border: 1px solid var(--border); border-radius: var(--radius);
box-shadow: var(--shadow); overflow: hidden;
}
.diff-head {
display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
padding: 10px 14px; border-bottom: 1px solid var(--border);
background: var(--bg); font-size: 13px; color: var(--text-muted);
}
.diff-head .diff-title { font-weight: 600; color: var(--text); }
.diff-head .notice {
display: none; align-items: center; gap: 6px;
padding: 4px 10px; border-radius: 6px;
background: var(--c-change-bg); color: var(--text);
font-size: 12px;
}
.diff-head .notice.show { display: inline-flex; }
.diff-body { flex: 1; overflow: auto; }
/* ---------- 并排视图 ---------- */
.diff-side { min-width: 640px; }
.diff-row {
display: grid;
grid-template-columns: 44px 1fr 44px 1fr;
border-bottom: 1px solid var(--border);
font-family: "SF Mono", "JetBrains Mono", "Fira Code", Menlo, Consolas, monospace;
font-size: 13px; line-height: 1.7;
}
.diff-row > * { padding: 4px 8px; border-right: 1px solid var(--border); overflow: hidden; }
.diff-row > *:last-child { border-right: none; }
.ln {
background: var(--bg); color: var(--text-faint);
text-align: right; white-space: nowrap;
user-select: none; font-size: 12px;
}
.lc, .rc { white-space: pre; }
.row-eq { background: var(--panel); }
.row-del { background: var(--c-del-bg); }
.row-add { background: var(--c-add-bg); }
.row-empty { background: var(--bg); }
.del-part { background: var(--c-del-strong); border-radius: 2px; }
.ins-part { background: var(--c-add-strong); border-radius: 2px; }
.empty-line { display: inline-block; min-width: 1px; min-height: 1em; }
/* ---------- 统一视图 ---------- */
.diff-unified {
min-width: 320px;
font-family: "SF Mono", "JetBrains Mono", "Fira Code", Menlo, Consolas, monospace;
font-size: 13px; line-height: 1.7;
}
.u-row { display: flex; border-bottom: 1px solid var(--border); }
.u-sign {
width: 34px; text-align: center; font-weight: 700;
background: var(--bg); border-right: 1px solid var(--border);
user-select: none;
}
.u-line { flex: 1; padding: 4px 10px; white-space: pre; overflow: hidden; }
.u-eq { background: var(--panel); }
.u-del { background: var(--c-del-bg); }
.u-add { background: var(--c-add-bg); }
.u-del .u-sign { color: var(--c-del); }
.u-add .u-sign { color: var(--c-add); }
/* ---------- Toast ---------- */
#toast {
position: fixed; bottom: 28px; left: 50%; transform: translateX(-50%) translateY(20px);
background: var(--text); color: var(--panel);
padding: 9px 16px; border-radius: 8px; font-size: 13px;
box-shadow: 0 8px 24px rgba(0,0,0,.2);
opacity: 0; pointer-events: none; transition: all .22s;
z-index: 200; display: flex; align-items: center; gap: 7px;
}
#toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
#toast svg { width: 15px; height: 15px; }
.hidden { display: none !important; }
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 6px; border: 2px solid var(--bg); }
::-webkit-scrollbar-thumb:hover { background: var(--text-faint); }
@media (max-width: 760px) {
header { padding: 12px 14px; }
.toolbar { padding: 8px 12px; gap: 6px; }
main { padding: 12px 12px 50px; gap: 12px; }
.logo .sub { display: none; }
.input-panel { flex-direction: column; min-height: 320px; }
main.has-diff .input-panel { flex: 0 0 320px; }
.diff-row { grid-template-columns: 30px 1fr 30px 1fr; }
.ln { font-size: 11px; padding: 4px 5px; }
}
</style>
</head>
<body>
<header>
<div class="logo">
<div class="mark">±</div>
<div>
文本差异对比工具
<div class="sub">行级 diff · 字符高亮 · 并排与统一视图</div>
</div>
</div>
<div class="spacer"></div>
<a class="icon-btn" href="https://github.com/wangruofeng/diff-viewer" target="_blank" rel="noopener noreferrer" title="查看 GitHub 源码" aria-label="GitHub 源码仓库">
<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 .5C5.37.5 0 5.78 0 12.292c0 5.211 3.438 9.63 8.205 11.188.6.111.82-.254.82-.567 0-.28-.01-1.022-.015-2.005-3.338.711-4.042-1.582-4.042-1.582-.546-1.361-1.335-1.725-1.335-1.725-1.087-.731.084-.716.084-.716 1.205.082 1.838 1.215 1.838 1.215 1.07 1.803 2.809 1.282 3.495.981.108-.763.417-1.282.76-1.577-2.665-.295-5.466-1.309-5.466-5.827 0-1.287.465-2.339 1.235-3.164-.135-.297-.54-1.498.105-3.121 0 0 1.005-.316 3.3 1.209.96-.262 1.98-.392 3-.397 1.02.005 2.04.135 3 .397 2.28-1.525 3.285-1.209 3.285-1.209.645 1.623.24 2.824.12 3.121.765.825 1.23 1.877 1.23 3.164 0 4.53-2.805 5.527-5.475 5.817.42.354.81 1.077.81 2.182 0 1.578-.015 2.846-.015 3.229 0 .309.21.678.825.562C20.565 21.917 24 17.495 24 12.292 24 5.78 18.627.5 12 .5z"/></svg>
</a>
<button class="icon-btn" id="themeBtn" title="切换深浅色"></button>
</header>
<div class="toolbar">
<button class="btn" id="sampleBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2l2.4 7.2h7.6l-6 4.8 2.4 7.2-6-4.8-6 4.8 2.4-7.2-6-4.8h7.6z"/></svg>
示例
</button>
<button class="btn" id="swapBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 16V4M7 4L3 8M7 4l4 4"/><path d="M17 8v12m0 0l4-4m-4 4l-4-4"/></svg>
交换
</button>
<button class="btn ghost" id="clearBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
清空
</button>
<div class="divider"></div>
<div class="seg" id="viewSeg">
<button data-view="side" class="active">并排</button>
<button data-view="unified">统一</button>
</div>
<div class="divider"></div>
<button class="btn toggle" id="ignoreWSBtn" title="忽略行首行尾空白差异" aria-pressed="false">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="15" y2="12"/><line x1="3" y1="18" x2="18" y2="18"/></svg>
忽略空白
</button>
<button class="btn toggle" id="ignoreCaseBtn" title="忽略大小写差异" aria-pressed="false">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>
忽略大小写
</button>
<div class="divider"></div>
<button class="btn" id="copyDiffBtn" disabled>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
复制差异
</button>
<button class="btn" id="downloadDiffBtn" disabled>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
下载
</button>
<div class="spacer"></div>
<div class="stat hidden" id="statBar">
<span class="add" id="statAdd">+0 新增</span>
<span class="dot">·</span>
<span class="del" id="statDel">−0 删除</span>
<span class="dot">·</span>
<span class="mod" id="statMod">~0 修改</span>
</div>
</div>
<input type="file" id="leftFile" accept=".txt,text/plain" class="hidden">
<input type="file" id="rightFile" accept=".txt,text/plain" class="hidden">
<main id="main" class="input-only">
<div class="input-panel" id="inputPanel">
<div class="input-col">
<div class="input-head">
<span class="input-title">原文</span>
<button class="icon-btn" id="importLeftBtn" title="导入原文文件" aria-label="导入原文">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
</button>
</div>
<textarea id="leftInput" placeholder="在此粘贴原文,或将 .txt 文件拖拽到此处…" spellcheck="false" wrap="off"></textarea>
</div>
<div class="input-col">
<div class="input-head">
<span class="input-title">新文</span>
<button class="icon-btn" id="importRightBtn" title="导入新文文件" aria-label="导入新文">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
</button>
</div>
<textarea id="rightInput" placeholder="在此粘贴新文,或将 .txt 文件拖拽到此处…" spellcheck="false" wrap="off"></textarea>
</div>
</div>
<div class="diff-panel" id="diffPanel">
<div class="diff-head">
<span class="diff-title" id="diffTitle">并排对比</span>
<span class="notice" id="degradeNotice">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
文本较长,已使用前缀/后缀裁剪 + 中段 LCS 进行快速对比,结果可能存在偏差。
</span>
</div>
<div class="diff-body" id="diffBody"></div>
</div>
</main>
<div id="toast"></div>
<script>
/* =========================================================
文本差异对比工具
- 双栏输入:支持粘贴与拖拽 .txt 文件
- 行级 LCS diff,字符级高亮
- 并排 / 统一视图切换
- 忽略空白 / 忽略大小写
- 复制 / 下载 unified diff
========================================================= */
const $ = (s) => document.querySelector(s);
const state = {
left: '',
right: '',
ops: [],
degraded: false,
view: 'side',
ignoreWS: false,
ignoreCase: false,
debounceTimer: null
};
/* ---------- 通用工具 ---------- */
function escapeHtml(s) {
return String(s)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
}
function splitLines(t) {
if (t === '') return [];
const arr = t.split(/\r?\n/);
if (arr.length && arr[arr.length - 1] === '') arr.pop();
return arr;
}
let toastTimer;
function showToast(msg, ok = true) {
const t = $('#toast');
t.innerHTML = (ok
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'
: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>'
) + '<span>' + escapeHtml(msg) + '</span>';
t.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => t.classList.remove('show'), 1600);
}
async function copyText(text) {
try { await navigator.clipboard.writeText(text); return true; } catch {}
const ta = document.createElement('textarea');
ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0';
document.body.appendChild(ta); ta.select();
let ok = false;
try { ok = document.execCommand('copy'); } catch {}
document.body.removeChild(ta);
return ok;
}
function readFile(file, cb) {
const reader = new FileReader();
reader.onload = (ev) => cb(ev.target.result);
reader.onerror = () => showToast('读取文件失败', false);
reader.readAsText(file, 'utf-8');
}
/* ---------- 行级 diff ---------- */
function normalizeLine(s) {
let t = s;
if (state.ignoreWS) t = t.replace(/^\s+|\s+$/g, '');
if (state.ignoreCase) t = t.toLowerCase();
return t;
}
function lcsDiff(a, b, oldOffset = 0, newOffset = 0) {
const n = a.length, m = b.length;
const Arr = m <= 32767 ? Int16Array : Int32Array;
const dp = Array.from({ length: n + 1 }, () => new Arr(m + 1));
for (let i = 1; i <= n; i++) {
const ai = a[i - 1];
for (let j = 1; j <= m; j++) {
dp[i][j] = (normalizeLine(ai) === normalizeLine(b[j - 1]))
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
const rev = [];
let i = n, j = m, oldNum = n + oldOffset, newNum = m + newOffset;
while (i > 0 || j > 0) {
if (i > 0 && j > 0 && normalizeLine(a[i - 1]) === normalizeLine(b[j - 1])) {
rev.push({ type: 'equal', oldLine: a[i - 1], newLine: b[j - 1], oldNum, newNum });
i--; j--; oldNum--; newNum--;
} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
rev.push({ type: 'insert', newLine: b[j - 1], newNum });
j--; newNum--;
} else {
rev.push({ type: 'delete', oldLine: a[i - 1], oldNum });
i--; oldNum--;
}
}
return rev.reverse();
}
function computeLineDiff(oldLines, newLines) {
const LIMIT = 3000;
let degraded = false;
let ops;
if (oldLines.length === 0) {
ops = newLines.map((l, i) => ({ type: 'insert', newLine: l, newNum: i + 1 }));
} else if (newLines.length === 0) {
ops = oldLines.map((l, i) => ({ type: 'delete', oldLine: l, oldNum: i + 1 }));
} else if (oldLines.length + newLines.length > LIMIT) {
degraded = true;
let pre = 0;
const maxPre = Math.min(oldLines.length, newLines.length);
while (pre < maxPre && normalizeLine(oldLines[pre]) === normalizeLine(newLines[pre])) pre++;
let suf = 0;
const maxSuf = Math.min(oldLines.length - pre, newLines.length - pre);
while (suf < maxSuf && normalizeLine(oldLines[oldLines.length - 1 - suf]) === normalizeLine(newLines[newLines.length - 1 - suf])) suf++;
const aMid = oldLines.slice(pre, oldLines.length - suf);
const bMid = newLines.slice(pre, newLines.length - suf);
const midOps = lcsDiff(aMid, bMid, pre, pre);
ops = [];
for (let i = 0; i < pre; i++) {
ops.push({ type: 'equal', oldLine: oldLines[i], newLine: newLines[i], oldNum: i + 1, newNum: i + 1 });
}
ops.push(...midOps);
const oldSufStart = oldLines.length - suf, newSufStart = newLines.length - suf;
for (let i = 0; i < suf; i++) {
ops.push({
type: 'equal',
oldLine: oldLines[oldSufStart + i],
newLine: newLines[newSufStart + i],
oldNum: oldSufStart + i + 1,
newNum: newSufStart + i + 1
});
}
} else {
ops = lcsDiff(oldLines, newLines, 0, 0);
}
// 将连续变更块内的删除与新增按顺序配对为“修改”,剩余的行保持纯删除/新增
const paired = [];
for (let i = 0; i < ops.length;) {
const op = ops[i];
if (op.type === 'equal') { paired.push(op); i++; continue; }
let j = i;
const dels = [], ins = [];
while (j < ops.length && ops[j].type !== 'equal') {
if (ops[j].type === 'delete') dels.push(ops[j]);
else if (ops[j].type === 'insert') ins.push(ops[j]);
j++;
}
const pairCount = Math.min(dels.length, ins.length);
for (let k = 0; k < pairCount; k++) {
paired.push({
type: 'replace',
oldLine: dels[k].oldLine,
newLine: ins[k].newLine,
oldNum: dels[k].oldNum,
newNum: ins[k].newNum
});
}
for (let k = pairCount; k < dels.length; k++) paired.push(dels[k]);
for (let k = pairCount; k < ins.length; k++) paired.push(ins[k]);
i = j;
}
return { ops: paired, degraded };
}
/* ---------- 字符级 diff(行内高亮) ---------- */
function charDiff(oldStr, newStr) {
const a = Array.from(oldStr), b = Array.from(newStr);
const n = a.length, m = b.length;
if (n === 0 && m === 0) return [];
if (n === 0) return [{ type: 'ins', text: newStr }];
if (m === 0) return [{ type: 'del', text: oldStr }];
const Arr = m <= 32767 ? Int16Array : Int32Array;
const dp = Array.from({ length: n + 1 }, () => new Arr(m + 1));
for (let i = 1; i <= n; i++) {
const ai = a[i - 1];
for (let j = 1; j <= m; j++) {
dp[i][j] = (ai === b[j - 1]) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
const rev = [];
let i = n, j = m;
while (i > 0 || j > 0) {
if (i > 0 && j > 0 && a[i - 1] === b[j - 1]) {
rev.push({ type: 'eq', text: a[i - 1] }); i--; j--;
} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
rev.push({ type: 'ins', text: b[j - 1] }); j--;
} else {
rev.push({ type: 'del', text: a[i - 1] }); i--;
}
}
rev.reverse();
const out = [{ type: rev[0].type, text: rev[0].text }];
for (let k = 1; k < rev.length; k++) {
const last = out[out.length - 1], cur = rev[k];
if (last.type === cur.type) last.text += cur.text;
else out.push({ type: cur.type, text: cur.text });
}
return out;
}
function renderCharDiff(segments, kind) {
return segments.map(seg => {
const t = escapeHtml(seg.text);
if (seg.type === 'eq') return t;
if (seg.type === 'del' && (kind === 'del' || kind === 'both')) return '<span class="del-part">' + t + '</span>';
if (seg.type === 'ins' && (kind === 'ins' || kind === 'both')) return '<span class="ins-part">' + t + '</span>';
return t;
}).join('');
}
/* ---------- 渲染 diff ---------- */
function renderSide(ops) {
return ops.map(op => {
let leftNum = '', rightNum = '', leftClass = 'row-empty', rightClass = 'row-empty';
let leftHtml = '<span class="empty-line"></span>', rightHtml = '<span class="empty-line"></span>';
if (op.type === 'equal') {
leftNum = op.oldNum; rightNum = op.newNum;
leftClass = rightClass = 'row-eq';
leftHtml = rightHtml = escapeHtml(op.oldLine || ' ');
if (!op.oldLine) { leftHtml = rightHtml = '<span class="empty-line"></span>'; }
} else if (op.type === 'delete') {
leftNum = op.oldNum; leftClass = 'row-del';
leftHtml = escapeHtml(op.oldLine || ' ');
if (!op.oldLine) leftHtml = '<span class="empty-line"></span>';
} else if (op.type === 'insert') {
rightNum = op.newNum; rightClass = 'row-add';
rightHtml = escapeHtml(op.newLine || ' ');
if (!op.newLine) rightHtml = '<span class="empty-line"></span>';
} else if (op.type === 'replace') {
leftNum = op.oldNum; rightNum = op.newNum;
leftClass = 'row-del'; rightClass = 'row-add';
const segs = charDiff(op.oldLine, op.newLine);
leftHtml = renderCharDiff(segs, 'del');
rightHtml = renderCharDiff(segs, 'ins');
}
return '<div class="diff-row">' +
'<div class="ln">' + leftNum + '</div>' +
'<div class="lc ' + leftClass + '">' + leftHtml + '</div>' +
'<div class="ln">' + rightNum + '</div>' +
'<div class="rc ' + rightClass + '">' + rightHtml + '</div>' +
'</div>';
}).join('');
}
function renderUnified(ops) {
return ops.map(op => {
if (op.type === 'equal') {
const html = escapeHtml(op.oldLine || '');
return '<div class="u-row u-eq"><span class="u-sign"> </span><span class="u-line">' + html + '</span></div>';
}
if (op.type === 'delete') {
const html = escapeHtml(op.oldLine || '');
return '<div class="u-row u-del"><span class="u-sign">−</span><span class="u-line">' + html + '</span></div>';
}
if (op.type === 'insert') {
const html = escapeHtml(op.newLine || '');
return '<div class="u-row u-add"><span class="u-sign">+</span><span class="u-line">' + html + '</span></div>';
}
// replace
const segs = charDiff(op.oldLine, op.newLine);
const oldHtml = renderCharDiff(segs, 'del');
const newHtml = renderCharDiff(segs, 'ins');
return '<div class="u-row u-del"><span class="u-sign">−</span><span class="u-line">' + oldHtml + '</span></div>' +
'<div class="u-row u-add"><span class="u-sign">+</span><span class="u-line">' + newHtml + '</span></div>';
}).join('');
}
function renderDiff() {
if (state.ops.length === 0) {
$('#main').classList.remove('has-diff');
$('#main').classList.add('input-only');
$('#statBar').classList.add('hidden');
$('#copyDiffBtn').disabled = true;
$('#downloadDiffBtn').disabled = true;
return;
}
$('#main').classList.remove('input-only');
$('#main').classList.add('has-diff');
$('#statBar').classList.remove('hidden');
$('#copyDiffBtn').disabled = false;
$('#downloadDiffBtn').disabled = false;
$('#diffTitle').textContent = state.view === 'side' ? '并排对比' : '统一视图';
$('#degradeNotice').classList.toggle('show', state.degraded);
$('#diffBody').innerHTML = state.view === 'side'
? '<div class="diff-side">' + renderSide(state.ops) + '</div>'
: '<div class="diff-unified">' + renderUnified(state.ops) + '</div>';
}
/* ---------- 统计 ---------- */
function updateStats() {
const s = state.ops.reduce((acc, op) => {
if (op.type === 'insert') acc.added++;
else if (op.type === 'delete') acc.deleted++;
else if (op.type === 'replace') acc.modified++;
return acc;
}, { added: 0, deleted: 0, modified: 0 });
$('#statAdd').textContent = '+' + s.added + ' 新增';
$('#statDel').textContent = '−' + s.deleted + ' 删除';
$('#statMod').textContent = '~' + s.modified + ' 修改';
}
/* ---------- 对比调度 ---------- */
function runDiff() {
state.left = $('#leftInput').value;
state.right = $('#rightInput').value;
if (!state.left && !state.right) {
state.ops = [];
state.degraded = false;
renderDiff();
return;
}
const oldLines = splitLines(state.left);
const newLines = splitLines(state.right);
const res = computeLineDiff(oldLines, newLines);
state.ops = res.ops;
state.degraded = res.degraded;
updateStats();
renderDiff();
}
function scheduleDiff() {
clearTimeout(state.debounceTimer);
state.debounceTimer = setTimeout(runDiff, 250);
}
/* ---------- unified diff 文本生成 ---------- */
function buildUnifiedDiffText() {
if (state.ops.length === 0) return '';
const lines = ['--- 原文', '+++ 新文', ''];
const change = state.ops.map(op => op.type !== 'equal');
const n = state.ops.length;
const CTX = 3;
let i = 0;
while (i < n) {
while (i < n && !change[i]) i++;
if (i >= n) break;
let start = Math.max(0, i - CTX);
let end = Math.min(n - 1, i + CTX);
// 合并相邻的变更块
while (true) {
let next = end + 1;
while (next < n && !change[next]) next++;
if (next < n && next - end <= 2 * CTX) {
end = Math.min(n - 1, next + CTX);
i = next;
} else break;
}
// 计算块内行号与长度
let oldStart = 0, newStart = 0, oldLen = 0, newLen = 0;
for (let k = start; k <= end; k++) {
const op = state.ops[k];
if (k === start) {
if (op.type === 'equal' || op.type === 'delete' || op.type === 'replace') oldStart = op.oldNum;
else if (op.type === 'insert') oldStart = op.newNum - 1;
if (op.type === 'equal' || op.type === 'insert' || op.type === 'replace') newStart = op.newNum;
else if (op.type === 'delete') newStart = op.oldNum - 1;
}
if (op.type === 'equal') { oldLen++; newLen++; }
else if (op.type === 'delete') { oldLen++; }
else if (op.type === 'insert') { newLen++; }
else if (op.type === 'replace') { oldLen++; newLen++; }
}
lines.push('@@ -' + oldStart + ',' + oldLen + ' +' + newStart + ',' + newLen + ' @@');
for (let k = start; k <= end; k++) {
const op = state.ops[k];
if (op.type === 'equal') lines.push(' ' + op.oldLine);
else if (op.type === 'delete') lines.push('-' + op.oldLine);
else if (op.type === 'insert') lines.push('+' + op.newLine);
else if (op.type === 'replace') { lines.push('-' + op.oldLine); lines.push('+' + op.newLine); }
}
lines.push('');
i = end + 1;
}
return lines.join('\n');
}
/* ---------- 文件拖拽 ---------- */
function setupDrop(textarea) {
let counter = 0;
textarea.addEventListener('dragenter', (e) => {
e.preventDefault(); counter++;
textarea.classList.add('dragover');
});
textarea.addEventListener('dragover', (e) => e.preventDefault());
textarea.addEventListener('dragleave', (e) => {
e.preventDefault(); counter--;
if (counter <= 0) { counter = 0; textarea.classList.remove('dragover'); }
});
textarea.addEventListener('drop', (e) => {
e.preventDefault(); counter = 0;
textarea.classList.remove('dragover');
const file = e.dataTransfer.files[0];
if (!file) return;
readFile(file, (text) => {
textarea.value = text;
showToast('已导入:' + file.name);
scheduleDiff();
});
});
}
function setupFileInput(input, textarea) {
input.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
readFile(file, (text) => {
textarea.value = text;
showToast('已导入:' + file.name);
scheduleDiff();
});
}
input.value = '';
});
}
setupDrop($('#leftInput'));
setupDrop($('#rightInput'));
setupFileInput($('#leftFile'), $('#leftInput'));
setupFileInput($('#rightFile'), $('#rightInput'));
$('#importLeftBtn').addEventListener('click', () => $('#leftFile').click());
$('#importRightBtn').addEventListener('click', () => $('#rightFile').click());
/* ---------- 工具栏事件 ---------- */
$('#leftInput').addEventListener('input', scheduleDiff);
$('#rightInput').addEventListener('input', scheduleDiff);
$('#sampleBtn').addEventListener('click', () => {
const left = '项目配置 v1.0\n名称:Alpha 系统\n端口:8080\n调试模式:false\n允许注册:true\n管理员:\n- 张三\n- 李四\n日志级别:info';
const right = '项目配置 v1.1\n名称:Alpha 系统 Pro\n端口:3000\n调试模式:true\n允许注册:true\n管理员:\n- 张三\n- 王五\n- 赵六\n日志级别:debug\n新增:缓存 TTL 60s';
$('#leftInput').value = left;
$('#rightInput').value = right;
scheduleDiff();
showToast('已填充示例');
});
$('#swapBtn').addEventListener('click', () => {
const t = $('#leftInput').value;
$('#leftInput').value = $('#rightInput').value;
$('#rightInput').value = t;
scheduleDiff();
showToast('已交换左右文本');
});
$('#clearBtn').addEventListener('click', () => {
$('#leftInput').value = '';
$('#rightInput').value = '';
scheduleDiff();
showToast('已清空');
});
function setView(view) {
state.view = view;
document.querySelectorAll('#viewSeg button').forEach(b => b.classList.toggle('active', b.dataset.view === view));
renderDiff();
}
document.querySelectorAll('#viewSeg button').forEach(b => {
b.addEventListener('click', () => setView(b.dataset.view));
});
function toggleBtn(id, key) {
const btn = $(id);
btn.addEventListener('click', () => {
state[key] = !state[key];
btn.classList.toggle('active', state[key]);
btn.setAttribute('aria-pressed', String(state[key]));
scheduleDiff();
});
}
toggleBtn('#ignoreWSBtn', 'ignoreWS');
toggleBtn('#ignoreCaseBtn', 'ignoreCase');
$('#copyDiffBtn').addEventListener('click', async () => {
const text = buildUnifiedDiffText();
if (!text) return;
if (await copyText(text)) showToast('已复制 unified diff');
else showToast('复制失败', false);
});
$('#downloadDiffBtn').addEventListener('click', () => {
const text = buildUnifiedDiffText();
if (!text) return;
const blob = new Blob([text], { type: 'text/x-diff;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = 'diff.diff';
document.body.appendChild(a); a.click(); document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 1000);
showToast('已下载 diff.diff');
});
/* ---------- 主题切换 ---------- */
const themeBtn = $('#themeBtn');
const SUN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>';
const MOON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>';
function setTheme(dark) {
document.documentElement.classList.toggle('dark', dark);
themeBtn.innerHTML = dark ? SUN : MOON;
themeBtn.title = dark ? '切换到浅色' : '切换到深色';
try { localStorage.setItem('diff-theme', dark ? 'dark' : 'light'); } catch {}
}
themeBtn.addEventListener('click', () => setTheme(!document.documentElement.classList.contains('dark')));
try {
const saved = localStorage.getItem('diff-theme');
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
setTheme(saved ? saved === 'dark' : prefersDark);
} catch { setTheme(false); }
</script>
</body>
</html>