@kevlns/xlmerge 2.0.4 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1634 +1,1635 @@
1
- <!DOCTYPE html>
2
- <html lang="zh-CN">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Excel 冲突解决工具</title>
7
- <style>
8
- :root {
9
- --bg-deep: #f4eed8;
10
- --bg-root: #e6dfc8;
11
- --bg-surface: #ffffff;
12
- --border-default: #000000;
13
- --shadow-edge: #625a4d;
14
- --gold: #f2c94c;
15
- --gold-dim: #e0b83e;
16
- --lava: #f29aa3;
17
- --emerald: #a2d2ff;
18
- --sapphire: #9dccff;
19
- --incoming: #cfe9b7;
20
- --incoming-deep: #b6d998;
21
- --tombstone: #77736b;
22
- --tombstone-dark: #58554f;
23
- --text-primary: #111111;
24
- --text-secondary: #444444;
25
- --text-muted: #777777;
26
- --shadow: 4px 4px 0 #000000;
27
- --shadow-hover: 2px 2px 0 #000000;
28
- --border-width: 3px;
29
- }
30
- * { margin: 0; padding: 0; box-sizing: border-box; }
31
- html { width: 100%; height: 100%; overflow: hidden; }
32
- body {
33
- font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
34
- background: var(--bg-deep);
35
- background-image:
36
- linear-gradient(var(--bg-root) 1px, transparent 1px),
37
- linear-gradient(90deg, var(--bg-root) 1px, transparent 1px);
38
- background-size: 20px 20px;
39
- color: var(--text-primary);
40
- width: 100%;
41
- height: 100vh;
42
- min-height: 0;
43
- overflow: hidden;
44
- display: flex;
45
- flex-direction: column;
46
- }
47
- .toolbar {
48
- background: var(--bg-surface);
49
- padding: 12px 20px;
50
- display: flex;
51
- align-items: center;
52
- gap: 16px;
53
- border-bottom: var(--border-width) solid var(--border-default);
54
- flex-wrap: nowrap;
55
- min-width: 0;
56
- }
57
- .toolbar h1 {
58
- flex: 0 0 auto;
59
- font-size: 18px;
60
- font-weight: 700;
61
- white-space: nowrap;
62
- }
63
- .file-tabs, .sheet-tabs {
64
- display: flex;
65
- gap: 6px;
66
- flex-wrap: nowrap;
67
- min-width: 0;
68
- overflow-x: auto;
69
- overflow-y: hidden;
70
- overscroll-behavior-inline: contain;
71
- scrollbar-color: var(--border-default) transparent;
72
- scrollbar-width: thin;
73
- }
74
- .file-tabs { flex: 1 1 auto; padding: 2px 4px 7px 0; }
75
- .sheet-tabs { flex: 1 1 auto; padding: 2px 4px 5px 0; }
76
- .file-tabs::-webkit-scrollbar, .sheet-tabs::-webkit-scrollbar { height: 8px; }
77
- .file-tabs::-webkit-scrollbar-track, .sheet-tabs::-webkit-scrollbar-track { background: transparent; }
78
- .file-tabs::-webkit-scrollbar-thumb, .sheet-tabs::-webkit-scrollbar-thumb {
79
- background: var(--border-default);
80
- border: 2px solid var(--bg-surface);
81
- }
82
- .file-tab, .sheet-tab {
83
- flex: 0 0 auto;
84
- padding: 8px 16px;
85
- background: var(--bg-surface);
86
- color: var(--text-secondary);
87
- cursor: pointer;
88
- font-size: 13px;
89
- font-weight: 600;
90
- border: var(--border-width) solid var(--border-default);
91
- box-shadow: var(--shadow);
92
- transition: transform 150ms ease, box-shadow 150ms ease;
93
- }
94
- .file-tab:hover, .sheet-tab:hover { transform: translate(2px, 2px); box-shadow: var(--shadow-hover); }
95
- .file-tab.active {
96
- background: var(--emerald);
97
- transform: translate(2px, 2px);
98
- box-shadow: var(--shadow-hover);
99
- }
100
- .file-tab.has-conflicts { color: var(--text-primary); }
101
- .sheet-toolbar {
102
- background: #fff8dc;
103
- padding: 9px 20px 11px;
104
- display: flex;
105
- align-items: center;
106
- gap: 12px;
107
- border-bottom: var(--border-width) solid var(--border-default);
108
- flex-wrap: nowrap;
109
- min-width: 0;
110
- }
111
- .sheet-scope {
112
- display: flex;
113
- align-items: center;
114
- gap: 9px;
115
- min-width: 0;
116
- flex: 1 1 auto;
117
- }
118
- .sheet-choice { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
119
- .macro-label { font-size: 11px; font-weight: 900; color: #3d3529; white-space: nowrap; }
120
- .macro-toggle { padding: 5px 9px; font-size: 11px; opacity: .55; }
121
- .macro-toggle.is-selected { opacity: 1; outline: 2px solid #4f4638; outline-offset: 1px; }
122
- .macro-toggle:disabled { cursor: not-allowed; filter: grayscale(.45); opacity: .45; }
123
- .macro-note { font-size: 11px; font-weight: 700; color: #6a5142; white-space: nowrap; }
124
- .diff-legend {
125
- display: flex;
126
- align-items: center;
127
- gap: 14px;
128
- padding: 7px 20px;
129
- border-bottom: 2px solid #cfc5ae;
130
- background: #f8f1de;
131
- color: #4b4438;
132
- font-size: 11px;
133
- font-weight: 700;
134
- white-space: nowrap;
135
- overflow-x: auto;
136
- }
137
- .legend-intro { color: #27231d; font-weight: 900; }
138
- .legend-item { display: inline-flex; align-items: center; gap: 5px; }
139
- .legend-swatch { width: 18px; height: 13px; border: 1px solid #6e6657; display: inline-block; }
140
- .legend-local { background: var(--sapphire); box-shadow: inset 0 0 0 2px rgba(35, 84, 130, .42); }
141
- .legend-remote { background: var(--lava); box-shadow: inset 0 0 0 2px rgba(124, 38, 47, .38); }
142
- .legend-incoming { background: var(--incoming); }
143
- .legend-deleted { background: var(--tombstone); }
144
- .sheet-label {
145
- padding: 5px 8px;
146
- background: var(--border-default);
147
- color: var(--bg-surface);
148
- font-size: 11px;
149
- font-weight: 800;
150
- letter-spacing: 1.2px;
151
- }
152
- .sheet-tab { padding: 6px 13px; box-shadow: 3px 3px 0 #000; }
153
- .sheet-tab.active {
154
- background: var(--gold);
155
- transform: translate(2px, 2px);
156
- box-shadow: 1px 1px 0 #000;
157
- }
158
- .tab-count {
159
- margin-left: 7px;
160
- font-size: 11px;
161
- color: var(--text-muted);
162
- }
163
- .actions { flex: 0 0 auto; margin-left: 0; display: flex; gap: 8px; align-items: center; }
164
- .sheet-actions {
165
- flex: 0 0 auto;
166
- display: flex;
167
- align-items: center;
168
- gap: 7px;
169
- padding: 4px 7px;
170
- border: 2px solid #b8a66d;
171
- background: rgba(255, 255, 255, .58);
172
- }
173
- .sheet-actions-label {
174
- color: #6c5518;
175
- font-size: 10px;
176
- font-weight: 900;
177
- white-space: nowrap;
178
- }
179
- .sheet-actions .btn { padding: 7px 11px; font-size: 12px; }
180
- .global-stats {
181
- flex: 0 0 auto;
182
- display: inline-flex;
183
- align-items: center;
184
- gap: 7px;
185
- padding: 5px 8px;
186
- border-left: 2px solid #bfb5a0;
187
- color: #332d24;
188
- white-space: nowrap;
189
- }
190
- .global-stats-label { font-size: 11px; font-weight: 900; }
191
- .global-stats-value { font-size: 16px; font-weight: 900; line-height: 1; }
192
- .global-stats-divider { color: #8c806c; font-size: 16px; font-weight: 700; }
193
- .btn {
194
- padding: 8px 16px;
195
- border: 1px solid #d8cfbd;
196
- border-radius: 3px;
197
- cursor: pointer;
198
- font-size: 13px;
199
- font-weight: 800;
200
- font-family: inherit;
201
- letter-spacing: .2px;
202
- box-shadow: 2px 2px 0 var(--shadow-edge);
203
- transition: transform 120ms ease, filter 120ms ease, box-shadow 120ms ease;
204
- background: linear-gradient(180deg, #f6f0e2, #dcd1bc);
205
- color: #2a261f;
206
- }
207
- .btn:hover { transform: translate(1px, 1px); filter: brightness(1.04); box-shadow: 1px 1px 0 var(--shadow-edge); }
208
- .btn:active { transform: translateY(1px); filter: brightness(.96); }
209
- .btn:focus-visible { outline: 3px solid #a2d2ff; outline-offset: 2px; }
210
- .btn-local { background: linear-gradient(180deg, #d9ecff, #91c4f1); border-color: #b8d8f4; color: #173f63; }
211
- .btn-remote { background: linear-gradient(180deg, #ffd1d5, #e9919a); border-color: #f2b3ba; color: #5a2027; }
212
- .btn-undo { background: linear-gradient(180deg, #f7f2e7, #dcd2bf); border-color: #e4ddcf; color: #2d2923; }
213
- .btn-reset { background: linear-gradient(180deg, #ffe7a5, #efc65c); border-color: #f5dfa1; color: #49360d; }
214
- .btn-cancel { background: linear-gradient(180deg, #f5c9cc, #dfa0a6); border-color: #efc2c6; color: #4a2529; }
215
- .btn-submit {
216
- position: relative;
217
- min-width: 126px;
218
- padding: 11px 28px;
219
- background: linear-gradient(180deg, #ffdc8a, #f4aa3e);
220
- border: 1px solid #f5d18d;
221
- border-bottom-color: #dbab5e;
222
- color: #3d2608;
223
- font-size: 14px;
224
- text-shadow: 0 1px 0 rgba(255, 255, 255, .35);
225
- box-shadow: 0 4px 0 #ad7626, 2px 2px 0 var(--shadow-edge);
226
- }
227
- .btn-submit:hover { transform: translateY(-1px); box-shadow: 0 5px 0 #ad7626, 2px 2px 0 var(--shadow-edge); }
228
- .btn-submit:active { transform: translateY(3px); box-shadow: 0 1px 0 #ad7626; }
229
- .btn:disabled { opacity: .38; cursor: not-allowed; transform: none; filter: none; }
230
- .stats {
231
- font-size: 13px;
232
- color: var(--text-secondary);
233
- font-weight: 600;
234
- white-space: nowrap;
235
- }
236
- .table-stage {
237
- flex: 1 1 auto;
238
- min-width: 0;
239
- min-height: 0;
240
- position: relative;
241
- }
242
- .table-container {
243
- width: 100%;
244
- height: 100%;
245
- overflow: auto;
246
- overscroll-behavior: contain;
247
- scrollbar-gutter: stable;
248
- padding: 16px;
249
- }
250
- .confirmed-overlay {
251
- position: absolute;
252
- inset: 0;
253
- z-index: 10;
254
- display: flex;
255
- align-items: center;
256
- justify-content: center;
257
- background: rgba(70, 70, 70, .58);
258
- cursor: not-allowed;
259
- }
260
- .confirmed-overlay-mark {
261
- width: 112px;
262
- height: 112px;
263
- border-radius: 50%;
264
- display: flex;
265
- align-items: center;
266
- justify-content: center;
267
- background: #2ca45d;
268
- border: 6px solid #d8ffe5;
269
- color: #fff;
270
- font-size: 76px;
271
- line-height: 1;
272
- font-weight: 900;
273
- box-shadow: 0 5px 0 #12552e, 0 0 28px rgba(0, 0, 0, .35);
274
- }
275
- table.diff-table {
276
- border-collapse: collapse;
277
- font-size: 13px;
278
- width: auto;
279
- border: var(--border-width) solid var(--border-default);
280
- box-shadow: var(--shadow);
281
- background: var(--bg-surface);
282
- }
283
- table.diff-table th, table.diff-table td {
284
- border: 2px solid var(--border-default);
285
- padding: 6px 12px;
286
- text-align: left;
287
- min-width: 80px;
288
- max-width: 240px;
289
- overflow: hidden;
290
- text-overflow: ellipsis;
291
- white-space: nowrap;
292
- }
293
- table.diff-table th {
294
- background: var(--gold);
295
- color: #111;
296
- font-weight: 800;
297
- cursor: pointer;
298
- text-shadow: none;
299
- }
300
- table.diff-table th:hover { background: var(--gold-dim); color: #111; }
301
- td.cell-local {
302
- background: var(--sapphire);
303
- color: #111;
304
- cursor: pointer;
305
- }
306
- td.cell-remote {
307
- background: var(--lava);
308
- color: #111;
309
- cursor: pointer;
310
- }
311
- td.cell-no-conflict { background: var(--bg-surface); color: var(--text-secondary); }
312
- .cell-selectable { box-shadow: inset 0 0 0 2px rgba(47, 42, 34, .38); cursor: pointer !important; }
313
- .cell-selectable:hover { filter: brightness(.92) saturate(1.12); box-shadow: inset 0 0 0 3px rgba(47, 42, 34, .58); }
314
- .row-header { cursor: pointer; }
315
- .row-header:hover { background: var(--emerald) !important; }
316
- tr.luban-header th { background: #2d2d2d; color: #f2f2f2; font-weight: 700; cursor: default; font-size: 12px; }
317
- tr.luban-header th:hover { background: #2d2d2d; color: #f2f2f2; }
318
- .axis-added-incoming {
319
- background: var(--incoming) !important;
320
- color: #29401f !important;
321
- }
322
- .axis-added-incoming:hover { background: var(--incoming-deep) !important; }
323
- .axis-tombstone {
324
- background-color: var(--tombstone) !important;
325
- background-image: repeating-linear-gradient(135deg, rgba(255,255,255,.08) 0 8px, rgba(0,0,0,.08) 8px 16px) !important;
326
- color: #f4f1e9 !important;
327
- cursor: not-allowed !important;
328
- text-decoration: line-through;
329
- }
330
- .axis-tombstone:hover { background-color: var(--tombstone-dark) !important; }
331
- .structure-control { min-width: 80px; padding: 4px 5px !important; text-align: center !important; background: #ece5d4 !important; }
332
- .structure-toggle {
333
- border: 1px solid #c6bca8;
334
- border-radius: 3px;
335
- padding: 3px 7px;
336
- background: #fff8dc;
337
- color: #332b20;
338
- font: 700 11px/1.2 inherit;
339
- cursor: pointer;
340
- box-shadow: 1px 1px 0 var(--shadow-edge);
341
- }
342
- .structure-toggle.is-delete { background: var(--tombstone); color: #fff; border-color: var(--tombstone-dark); }
343
- .structure-toggle:disabled { opacity: .42; cursor: not-allowed; box-shadow: none; }
344
- .structure-badge { display: inline-block; padding: 2px 6px; border: 1px solid rgba(0,0,0,.28); font-size: 10px; font-weight: 800; }
345
- .structure-badge.added { background: var(--incoming); color: #29401f; }
346
- .structure-badge.local-existing { background: #eee8dc; color: #4b4438; border-color: #bdb4a4; }
347
- .structure-badge.deleted { background: var(--tombstone); color: #fff; }
348
- .axis-index { display: inline-block; min-width: 22px; font-weight: 900; }
349
- .axis-index.is-removed { color: #f7f1e5; }
350
- .axis-source { display: block; margin-top: 2px; font-size: 9px; font-weight: 700; opacity: .72; }
351
- .sheet-tab.sheet-added { background: var(--incoming); }
352
- .sheet-tab.sheet-deleted { background: var(--tombstone); color: #fff; text-decoration: line-through; }
353
- .sheet-tab.sheet-structural-conflict::before { content: '◆'; margin-right: 5px; color: #a8392f; }
354
- .sheet-confirm-checkbox {
355
- width: 15px;
356
- height: 15px;
357
- margin-right: 7px;
358
- vertical-align: -2px;
359
- accent-color: #278b52;
360
- cursor: pointer;
361
- }
362
- .sheet-confirm-checkbox:focus-visible { outline: 2px solid #278b52; outline-offset: 2px; }
363
- .conflict-nav { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
364
- .conflict-nav .btn { padding: 6px 10px; font-size: 11px; }
365
- .conflict-nav-count { min-width: 48px; text-align: center; color: #4b4438; font-size: 11px; font-weight: 800; }
366
- .cell-locked { cursor: not-allowed !important; }
367
- .conflict-cell-flash { animation: conflict-cell-flash .55s ease-in-out 2; position: relative; z-index: 1; }
368
- @keyframes conflict-cell-flash {
369
- 0%, 100% { box-shadow: inset 0 0 0 2px rgba(47, 42, 34, .38); }
370
- 35%, 70% {
371
- background-color: #b86cff !important;
372
- background-image: none !important;
373
- box-shadow: inset 0 0 0 999px rgba(184, 108, 255, .96), 0 0 20px 6px rgba(147, 61, 255, .88);
374
- }
375
- }
376
- .tooltip {
377
- position: fixed;
378
- display: none;
379
- background: var(--bg-surface);
380
- color: var(--text-primary);
381
- border: var(--border-width) solid var(--border-default);
382
- padding: 10px 14px;
383
- font-size: 12px;
384
- z-index: 1000;
385
- pointer-events: none;
386
- max-width: 520px;
387
- box-shadow: var(--shadow);
388
- word-break: break-word;
389
- }
390
- .tooltip .label { color: var(--text-muted); margin-bottom: 6px; font-weight: 600; }
391
- .tooltip .val-base { color: #666; }
392
- .tooltip .val-local { color: #246aa3; }
393
- .tooltip .val-remote { color: #c0392b; }
394
- .tooltip .val-current { color: var(--text-primary); margin-top: 5px; font-weight: 700; }
395
- .tooltip .author { color: #777; margin-left: 18px; font-weight: 400; }
396
- .sheet-message {
397
- max-width: 720px;
398
- margin: 20px;
399
- padding: 24px;
400
- background: var(--bg-surface);
401
- border: var(--border-width) solid var(--border-default);
402
- box-shadow: var(--shadow);
403
- }
404
- .sheet-message h2 { font-size: 17px; margin-bottom: 8px; }
405
- .sheet-message p { color: var(--text-secondary); margin-bottom: 16px; line-height: 1.6; }
406
- .pager { display: flex; gap: 6px; padding: 12px 0; }
407
- .commit-modal { position: fixed; inset: 0; z-index: 200; display: flex; align-items: center; justify-content: center; }
408
- .commit-modal.is-hidden { display: none; }
409
- .commit-modal-backdrop { position: absolute; inset: 0; background: rgba(0, 0, 0, .55); }
410
- .commit-modal-panel {
411
- position: relative;
412
- background: var(--bg-surface);
413
- border: var(--border-width) solid var(--border-default);
414
- box-shadow: 8px 8px 0 #000;
415
- padding: 22px 26px;
416
- max-width: 520px;
417
- width: 88%;
418
- }
419
- .commit-modal-icon { font-size: 28px; margin-bottom: 8px; }
420
- .commit-modal-title { font-size: 17px; font-weight: 700; margin-bottom: 8px; }
421
- .commit-modal-body { font-size: 13px; color: var(--text-secondary); white-space: pre-wrap; word-break: break-word; margin-bottom: 10px; }
422
- .commit-modal-steps { font-size: 12px; font-family: Consolas, monospace; background: rgba(0, 0, 0, .04); border: 1px solid #ddd; padding: 8px 10px; margin-bottom: 12px; white-space: pre-wrap; word-break: break-word; max-height: 45vh; overflow-y: auto; }
423
- .commit-modal-steps:empty { display: none; }
424
- .commit-modal-actions { display: flex; gap: 10px; justify-content: flex-end; }
425
- .commit-modal.is-success .commit-modal-icon::before { content: "\2705"; }
426
- .commit-modal.is-error .commit-modal-icon::before { content: "\274C"; }
427
- .footer {
428
- position: relative;
429
- z-index: 20;
430
- flex: 0 0 auto;
431
- background: var(--bg-surface);
432
- padding: 12px 20px;
433
- display: flex;
434
- align-items: center;
435
- justify-content: space-between;
436
- gap: 20px;
437
- border-top: var(--border-width) solid var(--border-default);
438
- color: var(--text-primary);
439
- font-size: 13px;
440
- }
441
- .footer-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 12px; }
442
- @media (max-width: 900px) {
443
- .toolbar { flex-wrap: wrap; }
444
- .file-tabs { order: 3; flex: 1 0 100%; width: 100%; }
445
- .actions { width: auto; margin-left: auto; }
446
- .sheet-toolbar { align-items: flex-start; flex-wrap: wrap; }
447
- .sheet-scope { flex: 1 0 100%; }
448
- .sheet-actions { margin-left: auto; }
449
- .footer { align-items: flex-end; }
450
- }
451
- </style>
452
- </head>
453
- <body>
454
- <div class="toolbar">
455
- <h1>Excel 冲突解决工具</h1>
456
- <div class="file-tabs" id="fileTabs"></div>
457
- <div class="global-stats" id="globalConfirmationStats" aria-label="全局冲突 Sheet 确认统计">
458
- <span class="global-stats-label">冲突 Sheet 已确认</span>
459
- <span class="global-stats-value" id="confirmedSheetCount">0</span>
460
- <span class="global-stats-divider" aria-hidden="true">/</span>
461
- <span class="global-stats-value" id="totalConflictSheetCount">0</span>
462
- </div>
463
- </div>
464
- <div class="sheet-toolbar">
465
- <div class="sheet-scope" aria-label="当前 Sheet 工区">
466
- <span class="sheet-label">SHEET</span>
467
- <div class="sheet-tabs" id="sheetTabs"></div>
468
- <div class="sheet-actions" id="sheetActions" aria-label="当前 Sheet 操作">
469
- <span class="sheet-actions-label">当前 Sheet 操作</span>
470
- <button type="button" class="btn btn-local" id="allLocalBtn">全部本地</button>
471
- <button type="button" class="btn btn-remote" id="allRemoteBtn">全部远端</button>
472
- <button type="button" class="btn btn-undo" id="undoBtn">撤销</button>
473
- <button type="button" class="btn btn-reset" id="resetBtn">重置</button>
474
- </div>
475
- </div>
476
- <div class="conflict-nav" id="conflictNav" aria-label="冲突定位">
477
- <button type="button" class="btn" id="prevConflictBtn">上一个冲突</button>
478
- <span class="conflict-nav-count" id="conflictNavCount">0 / 0</span>
479
- <button type="button" class="btn" id="nextConflictBtn">下一个冲突</button>
480
- </div>
481
- <div class="sheet-choice" id="sheetChoice"></div>
482
- </div>
483
- <div class="diff-legend" id="diffLegend">
484
- <span class="legend-intro">主行列号=合并后位置</span>
485
- <span class="legend-item"><i class="legend-swatch legend-local"></i>本地值</span>
486
- <span class="legend-item"><i class="legend-swatch legend-remote"></i>远端值</span>
487
- <span class="legend-item"><i class="legend-swatch legend-incoming"></i>远端新增</span>
488
- <span class="legend-item"><i class="legend-swatch legend-deleted"></i>已删除</span>
489
- <span class="legend-item">悬停 Cell 查看 Base / 本地 / 远端</span>
490
- </div>
491
- <div class="table-stage" id="tableStage">
492
- <div class="table-container" id="tableContainer"></div>
493
- </div>
494
- <div class="tooltip" id="tooltip"></div>
495
- <div class="commit-modal is-hidden" id="commitModal" role="dialog" aria-modal="true" aria-labelledby="commitModalTitle">
496
- <div class="commit-modal-backdrop"></div>
497
- <div class="commit-modal-panel">
498
- <div class="commit-modal-icon"></div>
499
- <div class="commit-modal-title" id="commitModalTitle">提交中...</div>
500
- <div class="commit-modal-body" id="commitModalBody"></div>
501
- <div class="commit-modal-steps" id="commitModalSteps"></div>
502
- <div class="commit-modal-actions" id="commitModalActions"></div>
503
- </div>
504
- </div>
505
- <div class="footer">
506
- <span id="footerStatus">加载中...</span>
507
- <div class="footer-actions">
508
- <button type="button" class="btn btn-cancel" id="cancelBtn">取消并退出</button>
509
- <button type="button" class="btn btn-submit" id="submitBtn">提交合并</button>
510
- </div>
511
- </div>
512
- <script>
513
- let model = null;
514
- let currentFile = 0;
515
- let currentSheet = 0;
516
- let currentPage = 0;
517
- let decisions = {files: {}};
518
- let undoStack = [];
519
- const PAGE_SIZE = 500;
520
-
521
- const byId = id => document.getElementById(id);
522
- const fmtVal = value => value === null || value === undefined ? '' : String(value);
523
- function colLabel(n) { let s = ''; while (n > 0) { n--; s = String.fromCharCode(65 + n % 26) + s; n = Math.floor(n / 26); } return s; }
524
- function currentFileData() { return model && model.files[currentFile]; }
525
- function currentSheetData() { const file = currentFileData(); return file && file.diff.sheets[currentSheet]; }
526
- function fileDecision(file) {
527
- if (!decisions.files[file.id]) decisions.files[file.id] = {sheets: {}};
528
- return decisions.files[file.id];
529
- }
530
- function sheetDecision(file, sheet) {
531
- const target = fileDecision(file).sheets;
532
- if (!target[sheet.name]) target[sheet.name] = {cells: {}, rows: {}, columns: {}, confirmed: false};
533
- if (typeof target[sheet.name].confirmed !== 'boolean') target[sheet.name].confirmed = false;
534
- return target[sheet.name];
535
- }
536
- function cellKey(cell) { return cell.id || cell.coordinate; }
537
- function defaultCellChoice(cell) {
538
- if (cell.requiresChoice) return null;
539
- if (cell.resolution === 'conflict') return 'theirs';
540
- if (cell.resolution === 'same') return cell.oursPresent === false ? 'theirs' : 'ours';
541
- return cell.resolution;
542
- }
543
- function defaultSheetChoice(sheet) { return sheet.action.startsWith('conflict_') && !sheet.requiresChoice ? 'ours' : null; }
544
- function initializeDecisions() {
545
- for (const file of model.files) {
546
- const fileTarget = fileDecision(file);
547
- if (file.macro) fileTarget.macro = file.macro.default || 'ours';
548
- for (const sheet of file.diff.sheets) {
549
- const target = sheetDecision(file, sheet);
550
- target.confirmed = false;
551
- const sheetChoice = defaultSheetChoice(sheet);
552
- if (sheetChoice) target.sheet = sheetChoice;
553
- if (sheet.renameStatus === 'rename_conflict') target.rename = 'ours';
554
- if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') target.mergedCells = sheet.mergedCells.default || 'ours';
555
- for (const row of sheet.allRows || sheet.rows || []) if (row.state === 'delete_modify') target.rows[row.id] = row.default;
556
- for (const column of sheet.columns || []) if (column.state === 'delete_modify') target.columns[column.id] = column.default;
557
- for (const cell of sheet.cells || []) target.cells[cell.id || cell.coordinate] = defaultCellChoice(cell);
558
- }
559
- }
560
- }
561
- function gridVal(sheet, row, col) {
562
- const values = (sheet.contextRows || {})[String(row)];
563
- return values ? values[col - 1] : '';
564
- }
565
- function enableHorizontalWheel(host) {
566
- host.addEventListener('wheel', event => {
567
- if (host.scrollWidth <= host.clientWidth || Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return;
568
- event.preventDefault();
569
- host.scrollLeft += event.deltaY;
570
- }, {passive: false});
571
- }
572
-
573
- function autoTheirsNote(sep) {
574
- const count = (model && model.summary) ? (model.summary.autoTheirsCount || 0) : 0;
575
- return count ? `${sep}已按远端全量自动处理 ${count} 张表` : '';
576
- }
577
-
578
- async function init() {
579
- const response = await fetch('/api/diff');
580
- model = await response.json();
581
- if (!model.files || model.files.length === 0) {
582
- byId('footerStatus').textContent = '未发现冲突。' + autoTheirsNote('');
583
- return;
584
- }
585
- initializeDecisions();
586
- render();
587
- }
588
-
589
- function render() {
590
- renderFileTabs();
591
- renderSheetTabs();
592
- renderSheetChoice();
593
- renderTable();
594
- renderConflictNavigation();
595
- renderActionAvailability();
596
- updateStats();
597
- }
598
- function renderFileTabs() {
599
- const host = byId('fileTabs');
600
- host.replaceChildren();
601
- model.files.forEach((file, index) => {
602
- const tab = document.createElement('div');
603
- tab.className = 'file-tab' + (index === currentFile ? ' active' : '') + (file.diff.summary.changedCellCount ? ' has-conflicts' : '');
604
- tab.textContent = file.path;
605
- tab.onclick = () => { currentFile = index; currentSheet = 0; currentPage = 0; render(); };
606
- host.append(tab);
607
- });
608
- }
609
- function sheetDecisionCount(file, sheet) {
610
- if (sheet.action.startsWith('conflict_')) return 1;
611
- if (sheet.action !== 'merge') return 1;
612
- let total = sheet.renameStatus === 'rename_conflict' ? 1 : 0;
613
- if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') total++;
614
- total += (sheet.allRows || sheet.rows || []).filter(axis => axis.state === 'delete_modify').length;
615
- total += (sheet.columns || []).filter(axis => axis.state === 'delete_modify').length;
616
- for (const cell of sheet.cells || []) {
617
- if (!sheet.columns || !sheet.allRows || structuralCellSelectable(file, sheet, cell)) total++;
618
- }
619
- return total;
620
- }
621
- function renderSheetTabs() {
622
- const host = byId('sheetTabs');
623
- host.replaceChildren();
624
- const file = currentFileData();
625
- // 单侧修改仍可人工覆盖,与双侧冲突使用相同的审阅入口。
626
- const visible = [];
627
- file.diff.sheets.forEach((sheet, index) => {
628
- if (!sheetNeedsConfirmation(sheet)) return;
629
- visible.push({ sheet, index });
630
- });
631
- if (!visible.length) {
632
- const empty = document.createElement('div');
633
- empty.className = 'sheet-tab';
634
- empty.textContent = '该文件没有需要处理的 Sheet';
635
- host.append(empty);
636
- return;
637
- }
638
- const current = file.diff.sheets[currentSheet];
639
- if (!sheetNeedsConfirmation(current)) {
640
- currentSheet = visible[0].index;
641
- }
642
- visible.forEach(({ sheet, index }) => {
643
- const tab = document.createElement('div');
644
- const added = sheet.action === 'auto_add_theirs';
645
- const deleted = sheet.action === 'auto_delete';
646
- const structuralConflict = sheet.action.startsWith('conflict_') || sheet.renameStatus === 'rename_conflict' || (sheet.structuralConflictCount || 0) > 0;
647
- tab.className = 'sheet-tab' + (index === currentSheet ? ' active' : '') + (added ? ' sheet-added' : '') + (deleted ? ' sheet-deleted' : '') + (structuralConflict ? ' sheet-structural-conflict' : '');
648
- const target = sheetDecision(file, sheet);
649
- const confirmation = document.createElement('input');
650
- confirmation.type = 'checkbox';
651
- confirmation.className = 'sheet-confirm-checkbox';
652
- confirmation.checked = target.confirmed === true;
653
- confirmation.title = '勾选表示你已人工审阅并确认本 Sheet 的所有待处理项(含单侧改动);取消勾选可继续编辑。';
654
- confirmation.setAttribute('aria-label', `${sheet.name}:已确认(人工审阅完成)`);
655
- confirmation.onclick = event => event.stopPropagation();
656
- confirmation.onchange = event => {
657
- event.stopPropagation();
658
- if (confirmation.checked && ((sheet.requiresChoice && !target.sheet) ||
659
- (!target.sheet && (sheet.cells || []).some(cell => cell.requiresChoice && !target.cells[cellKey(cell)])))) {
660
- confirmation.checked = false;
661
- byId('footerStatus').textContent = '公式无法计算:请先明确选择这些单元格或整个 Sheet 的来源。';
662
- return;
663
- }
664
- const invalid = !target.sheet && (sheet.cells || []).find(cell => (cell.errorSides || {})[target.cells[cellKey(cell)]]);
665
- const sheetError = selectedSourceErrors(sheet, target).find(error => !validRepair(error, ((target.repairs || {})[target.sheet] || {})[error.coordinate]));
666
- if (confirmation.checked && (invalid || sheetError)) {
667
- confirmation.checked = false;
668
- byId('footerStatus').textContent = '请先填写所选整表来源的合法修复值,再确认 Sheet。';
669
- return;
670
- }
671
- target.confirmed = confirmation.checked;
672
- render();
673
- };
674
- tab.append(confirmation, document.createTextNode(sheet.name));
675
- const count = document.createElement('span');
676
- count.className = 'tab-count';
677
- count.textContent = sheetDecisionCount(file, sheet);
678
- tab.append(count);
679
- tab.onclick = () => { currentSheet = index; currentPage = 0; render(); };
680
- host.append(tab);
681
- });
682
- }
683
- function renderSheetChoice() {
684
- const host = byId('sheetChoice'); host.replaceChildren();
685
- const file = currentFileData(); const sheet = currentSheetData();
686
- const macro = file && file.macro;
687
- if (macro && macro.status !== 'same') {
688
- const label = document.createElement('span'); label.className = 'macro-label'; label.textContent = '当前文件宏 · VBA/ActiveX';
689
- host.append(label);
690
- if (macro.status === 'conflict') {
691
- const selected = fileDecision(file).macro || macro.default;
692
- const local = document.createElement('button');
693
- local.className = 'btn btn-local macro-toggle' + (selected === 'ours' ? ' is-selected' : '');
694
- local.textContent = '本地宏'; local.onclick = () => chooseMacro(file, 'ours');
695
- const remote = document.createElement('button');
696
- remote.className = 'btn btn-remote macro-toggle' + (selected === 'theirs' ? ' is-selected' : '');
697
- remote.textContent = '远端宏'; remote.onclick = () => chooseMacro(file, 'theirs');
698
- host.append(local, remote);
699
- } else {
700
- const note = document.createElement('span'); note.className = 'macro-note';
701
- note.textContent = macro.status === 'auto_theirs'
702
- ? '仅远端变更,自动采用远端宏'
703
- : macro.status === 'auto_ours'
704
- ? '仅本地变更,自动采用本地宏'
705
- : '两边宏包结构不同,安全保留本地宏';
706
- host.append(note);
707
- }
708
- }
709
- if (!sheet) return;
710
- if (sheet.replacements && sheet.replacements.length) {
711
- const note = document.createElement('span'); note.className = 'macro-label';
712
- const count = new Set(sheet.replacements.map(repair => JSON.stringify([repair.recordId, repair.field]))).size;
713
- note.textContent = sheet.replacements.some(repair => repair.manual)
714
- ? '公式错误已按人工指定值修复,请确认整表来源。'
715
- : `双方错误已按字段类型替换 ${count} 个值(ID、引用和未知类型保留人工处理)。`;
716
- note.title = sheet.replacements.map(repair => `${repair.side} / ${repair.coordinate}: ${repair.formula} → ${JSON.stringify(repair.value)}`).join('\n');
717
- host.append(note);
718
- }
719
- if (sheet.calculationErrors && sheet.calculationErrors.length) {
720
- const note = document.createElement('span'); note.className = 'macro-label';
721
- note.textContent = `有 ${sheet.calculationErrors.length} 个无法计算的值,必须选择有效来源。`;
722
- note.title = sheet.calculationErrors.map(error => `${error.side} / ${error.sheet}!${error.coordinate}: ${error.formula} → ${error.error}`).join('\n');
723
- host.append(note);
724
- if (sheet.action === 'merge') {
725
- for (const side of ['ours', 'theirs']) {
726
- const button = document.createElement('button'); button.className = 'structure-toggle';
727
- button.textContent = side === 'ours' ? '整表采用本地' : '整表采用远端';
728
- button.disabled = currentSheetIsConfirmed(); button.onclick = () => chooseSheet(file, sheet, side); host.append(button);
729
- }
730
- if (sheetDecision(file, sheet).sheet) {
731
- const button = document.createElement('button'); button.className = 'structure-toggle'; button.textContent = '返回单元格合并';
732
- button.onclick = () => { delete sheetDecision(file, sheet).sheet; sheetDecision(file, sheet).confirmed = false; render(); }; host.append(button);
733
- }
734
- }
735
- }
736
- const target = sheetDecision(file, sheet);
737
- const confirmed = sheetNeedsConfirmation(sheet) && target.confirmed;
738
- if (sheet.renameStatus === 'rename_conflict') {
739
- const local = document.createElement('button'); local.className = 'structure-toggle' + (target.rename === 'ours' ? '' : ' is-delete');
740
- local.textContent = `本地名:${sheet.names.ours}`; local.disabled = confirmed; local.onclick = () => chooseRename(file, sheet, 'ours');
741
- const remote = document.createElement('button'); remote.className = 'structure-toggle' + (target.rename === 'theirs' ? '' : ' is-delete');
742
- remote.textContent = `远端名:${sheet.names.theirs}`; remote.disabled = confirmed; remote.onclick = () => chooseRename(file, sheet, 'theirs');
743
- host.append(local, remote);
744
- }
745
- if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') {
746
- const label = document.createElement('span'); label.className = 'macro-label'; label.textContent = '合并表头';
747
- const local = document.createElement('button');
748
- local.className = 'btn btn-local macro-toggle' + (target.mergedCells === 'ours' ? ' is-selected' : '');
749
- local.textContent = '本地结构'; local.disabled = confirmed; local.onclick = () => chooseMergedCells(file, sheet, 'ours');
750
- const remote = document.createElement('button');
751
- remote.className = 'btn btn-remote macro-toggle' + (target.mergedCells === 'theirs' ? ' is-selected' : '');
752
- remote.textContent = '远端结构'; remote.disabled = confirmed; remote.onclick = () => chooseMergedCells(file, sheet, 'theirs');
753
- host.append(label, local, remote);
754
- }
755
- }
756
-
757
- function appendHeaderCell(row, value, onClick, className) {
758
- const cell = document.createElement('th');
759
- cell.textContent = value;
760
- if (className) cell.className = className;
761
- if (onClick) cell.onclick = onClick;
762
- row.append(cell);
763
- return cell;
764
- }
765
- function bindTip(cell, row, col) {
766
- cell.onmouseenter = event => showTip(event, row, col);
767
- cell.onmousemove = event => positionTip(event);
768
- cell.onmouseleave = hideTip;
769
- }
770
- function renderTable() {
771
- const file = currentFileData();
772
- const sheet = currentSheetData();
773
- const host = byId('tableContainer');
774
- host.replaceChildren();
775
- const oldOverlay = byId('confirmedOverlay');
776
- if (oldOverlay) oldOverlay.remove();
777
- if (!sheet) {
778
- renderMessage(host, '无需处理', '两侧工作簿内容一致,没有需要展示的 Sheet 差异。');
779
- return;
780
- }
781
- if (sheet.action.startsWith('conflict_') || sheetDecision(file, sheet).sheet) {
782
- renderSheetConflict(host, file, sheet);
783
- renderConfirmedOverlay(host, file, sheet);
784
- return;
785
- }
786
- if (sheet.action !== 'merge') {
787
- const labels = {
788
- auto_add_ours: '该 Sheet 仅存在于本地,将自动保留本地版本。',
789
- auto_add_theirs: '该 Sheet 仅存在于远端,将自动保留远端版本。',
790
- auto_delete: '该 Sheet 的删除只发生在一侧,另一侧未修改,将自动删除。'
791
- };
792
- renderMessage(host, sheet.name, labels[sheet.action] || `将自动执行:${sheet.action}`);
793
- renderConfirmedOverlay(host, file, sheet);
794
- return;
795
- }
796
- renderDiffTable(host, file, sheet);
797
- renderConfirmedOverlay(host, file, sheet);
798
- }
799
- function sheetNeedsConfirmation(sheet) {
800
- return !!sheet && (sheet.needsAttention !== false || sheet.decisionCellCount > 0 ||
801
- (sheet.cells || []).some(cell => cellNeedsReview(cell)));
802
- }
803
- function cellNeedsReview(cell) {
804
- return !!cell && !cell.replacement && cell.selectable !== false &&
805
- ['ours', 'theirs', 'conflict'].includes(cell.resolution);
806
- }
807
- function renderConfirmedOverlay(host, file, sheet) {
808
- if (!sheetNeedsConfirmation(sheet) || !sheetDecision(file, sheet).confirmed) return;
809
- const overlay = document.createElement('div');
810
- overlay.id = 'confirmedOverlay';
811
- overlay.className = 'confirmed-overlay';
812
- overlay.title = '本 Sheet 已确认;取消 Sheet 标签前的勾选后可继续编辑。';
813
- overlay.setAttribute('aria-label', '本 Sheet 已确认,表格交互已锁定');
814
- const mark = document.createElement('div');
815
- mark.className = 'confirmed-overlay-mark';
816
- mark.textContent = '✓';
817
- overlay.append(mark);
818
- byId('tableStage').append(overlay);
819
- }
820
- function currentSheetIsConfirmed() {
821
- const file = currentFileData(); const sheet = currentSheetData();
822
- return !!file && sheetNeedsConfirmation(sheet) && sheetDecision(file, sheet).confirmed;
823
- }
824
- function renderActionAvailability() {
825
- const confirmed = currentSheetIsConfirmed();
826
- byId('allLocalBtn').disabled = confirmed;
827
- byId('allRemoteBtn').disabled = confirmed;
828
- const file = currentFileData(); const sheet = currentSheetData();
829
- const scope = file && sheet ? `当前 Sheet:${file.path} / ${sheet.name}` : '当前 Sheet';
830
- const message = confirmed ? `${scope} 已确认;取消 Sheet 标签前的勾选后可继续编辑。` : `${scope} 的批量操作`;
831
- byId('allLocalBtn').title = `${message}:将可处理项全部采用本地。`;
832
- byId('allRemoteBtn').title = `${message}:将可处理项全部采用远端。`;
833
- byId('undoBtn').title = `${scope}:撤销最近一次选择,不影响其它 Sheet 或文件级宏。`;
834
- byId('resetBtn').title = `${scope}:恢复本 Sheet 的默认决策,不影响其它 Sheet 或文件级宏。`;
835
- }
836
- function navigableConflictCells(file, sheet) {
837
- if (!sheet || !sheetNeedsConfirmation(sheet)) return [];
838
- if (sheet.columns && sheet.allRows) {
839
- return (sheet.cells || []).filter(cell => cellNeedsReview(cell) && structuralCellSelectable(file, sheet, cell));
840
- }
841
- return (sheet.cells || []).filter(cell => cellNeedsReview(cell));
842
- }
843
- function conflictCellKey(cell) { return cell && (cell.id || cell.coordinate); }
844
- function renderConflictNavigation() {
845
- const file = currentFileData(); const sheet = currentSheetData();
846
- const cells = navigableConflictCells(file, sheet);
847
- const count = byId('conflictNavCount');
848
- const previous = byId('prevConflictBtn'); const next = byId('nextConflictBtn');
849
- if (!count || !previous || !next) return;
850
- const currentId = sheet && sheetDecision(file, sheet).lastNavigatedConflict;
851
- const currentIndex = cells.findIndex(cell => conflictCellKey(cell) === currentId);
852
- count.textContent = cells.length ? `${currentIndex < 0 ? 0 : currentIndex + 1} / ${cells.length}` : '0 / 0';
853
- previous.disabled = cells.length === 0;
854
- next.disabled = cells.length === 0;
855
- previous.title = cells.length ? '定位到当前 Sheet 的上一个待审阅改动(含单侧改动,循环)' : '当前 Sheet 没有可定位的改动';
856
- next.title = cells.length ? '定位到当前 Sheet 的下一个待审阅改动(含单侧改动,循环)' : '当前 Sheet 没有可定位的改动';
857
- }
858
- function markConflictCell(cellElement) {
859
- if (!cellElement) return;
860
- cellElement.classList.remove('conflict-cell-flash');
861
- // Force a reflow so repeated navigation to the same cell restarts the flash.
862
- void cellElement.offsetWidth;
863
- cellElement.classList.add('conflict-cell-flash');
864
- window.setTimeout(() => cellElement.classList.remove('conflict-cell-flash'), 1300);
865
- }
866
- function locateConflictCell(direction) {
867
- const file = currentFileData(); const sheet = currentSheetData();
868
- const cells = navigableConflictCells(file, sheet);
869
- if (!cells.length) return;
870
- const state = sheetDecision(file, sheet);
871
- const currentId = state.lastNavigatedConflict;
872
- let index = cells.findIndex(cell => conflictCellKey(cell) === currentId);
873
- index = index < 0 ? (direction > 0 ? 0 : cells.length - 1) : (index + direction + cells.length) % cells.length;
874
- const target = cells[index];
875
- state.lastNavigatedConflict = conflictCellKey(target);
876
- const rowNumber = target.row;
877
- if (!(sheet.columns && sheet.allRows) && rowNumber !== undefined) {
878
- const rows = [...new Set((sheet.cells || []).map(cell => cell.row))].sort((a, b) => a - b);
879
- currentPage = Math.floor(Math.max(0, rows.indexOf(rowNumber)) / PAGE_SIZE);
880
- } else if (sheet.columns && sheet.allRows) {
881
- const rows = sheet.rows || [];
882
- const rowIndex = rows.findIndex(row => row.id === target.rowId);
883
- currentPage = Math.floor(Math.max(0, rowIndex) / PAGE_SIZE);
884
- }
885
- renderTable();
886
- renderConflictNavigation();
887
- requestAnimationFrame(() => {
888
- const element = [...byId('tableContainer').querySelectorAll('[data-conflict-id]')]
889
- .find(item => item.dataset.conflictId === conflictCellKey(target));
890
- if (!element) return;
891
- const container = byId('tableContainer');
892
- container.scrollTop = Math.max(0, element.offsetTop - container.clientHeight / 2);
893
- container.scrollLeft = Math.max(0, element.offsetLeft - container.clientWidth / 2);
894
- element.scrollIntoView({block: 'nearest', inline: 'nearest'});
895
- markConflictCell(element);
896
- });
897
- }
898
- function renderMessage(host, title, message) {
899
- const box = document.createElement('div');
900
- box.className = 'sheet-message';
901
- const heading = document.createElement('h2'); heading.textContent = title;
902
- const body = document.createElement('p'); body.textContent = message;
903
- box.append(heading, body); host.append(box);
904
- }
905
- function renderSheetConflict(host, file, sheet) {
906
- const box = document.createElement('div');
907
- box.className = 'sheet-message';
908
- const heading = document.createElement('h2'); heading.textContent = `${sheet.name}:删除 / 修改冲突`;
909
- const body = document.createElement('p');
910
- body.textContent = '一侧删除了整个 Sheet,另一侧继续修改。选择某一侧后,将按该侧实际状态保留或删除 Sheet。';
911
- if (sheet.action === 'conflict_calculation_errors' || (sheet.calculationErrors || []).length) {
912
- heading.textContent = `${sheet.name}:公式错误`;
913
- body.textContent = '存在无法计算的值,且无法可靠对应行列或确认记录身份。请明确选择整个 Sheet 的有效本地或远端版本。';
914
- if (!(sheet.calculationErrors || []).length) {
915
- heading.textContent = `${sheet.name}:修复后整表选择`;
916
- body.textContent = '公式错误已修复。选择整表来源后,勾选 Sheet 标签前的确认框完成审阅。';
917
- }
918
- }
919
- const target = sheetDecision(file, sheet);
920
- const names = sheet.names || {};
921
- const local = document.createElement('button');
922
- const localLabel = names.ours ? '保留 Sheet(本地)' : '删除 Sheet(本地)';
923
- local.className = 'btn btn-local'; local.textContent = target.sheet === 'ours' ? `✓ ${localLabel}` : localLabel;
924
- local.onclick = () => chooseSheet(file, sheet, 'ours');
925
- const remote = document.createElement('button');
926
- const remoteLabel = names.theirs ? '保留 Sheet(远端)' : '删除 Sheet(远端)';
927
- remote.className = 'btn btn-remote'; remote.textContent = target.sheet === 'theirs' ? `✓ ${remoteLabel}` : remoteLabel;
928
- remote.onclick = () => chooseSheet(file, sheet, 'theirs');
929
- box.append(heading, body, local, document.createTextNode(' '), remote); host.append(box);
930
- const errors = selectedSourceErrors(sheet, target);
931
- if (errors.length) {
932
- const label = document.createElement('p'); label.textContent = '修复所选来源的错误值后,再确认整张 Sheet。ID / 引用字段需人工核对。'; box.append(label);
933
- const values = ((target.repairs || {})[target.sheet] || {});
934
- for (const error of errors) {
935
- const row = document.createElement('div'); row.style.margin = '12px 0';
936
- const title = document.createElement('label'); title.textContent = `${error.coordinate} · ${error.field || '字段未识别'} · ${error.type || '未知类型'}:`;
937
- title.title = `${error.formula} → ${error.error}`;
938
- const input = document.createElement(error.type === 'bool' ? 'select' : 'input');
939
- input.setAttribute('aria-label', `${error.coordinate} 修复值`); input.disabled = currentSheetIsConfirmed();
940
- if (error.type === 'bool') {
941
- for (const text of ['', 'true', 'false']) {const option = document.createElement('option'); option.value = text; option.textContent = text || '请选择'; input.append(option);}
942
- } else {input.type = 'text'; input.placeholder = error.type === 'string' ? '请输入文本(可为空串)' : '请输入合法数值';}
943
- if (Object.hasOwn(values, error.coordinate)) input.value = String(values[error.coordinate]);
944
- input.onchange = () => {
945
- target.repairs ||= {}; target.repairs[target.sheet] ||= {};
946
- const value = error.type === 'string' ? input.value : error.type === 'bool' ? (input.value ? input.value === 'true' : undefined) : (input.value.trim() ? Number(input.value) : undefined);
947
- if (validRepair(error, value)) target.repairs[target.sheet][error.coordinate] = value;
948
- else delete target.repairs[target.sheet][error.coordinate];
949
- target.confirmed = false; renderSheetTabs(); updateStats();
950
- };
951
- title.append(input); row.append(title);
952
- if (Object.hasOwn(error, 'defaultValue')) {
953
- const button = document.createElement('button'); button.className = 'btn'; button.textContent = `使用类型默认值 ${JSON.stringify(error.defaultValue)}`;
954
- button.onclick = () => {target.repairs ||= {}; target.repairs[target.sheet] ||= {}; target.repairs[target.sheet][error.coordinate] = error.defaultValue; target.confirmed = false; render();}; row.append(button);
955
- }
956
- box.append(row);
957
- }
958
- }
959
- }
960
- function selectedSourceErrors(sheet, target) {return (sheet.calculationErrors || []).filter(error => error.side === target.sheet);}
961
- function validRepair(error, value) {
962
- if (error.type === 'string') return typeof value === 'string';
963
- if (error.type === 'bool') return typeof value === 'boolean';
964
- if (['float', 'double', 'decimal'].includes(error.type)) return typeof value === 'number' && Number.isFinite(value);
965
- const kind = error.type || '';
966
- if (!/^(?:u?int(?:8|16|32|64)?|s?byte|u?short|u?long)$/.test(kind) || !Number.isSafeInteger(value)) return false;
967
- const sizes = {byte:8,sbyte:8,short:16,ushort:16,long:64,ulong:64};
968
- const bits = sizes[kind] || Number((kind.match(/\d+$/) || ['32'])[0]);
969
- const unsigned = kind.startsWith('u') || kind === 'byte';
970
- return value >= (unsigned ? 0 : -(2 ** (bits - 1))) && value <= 2 ** (unsigned ? bits : bits - 1) - 1;
971
- }
972
- function axisChoice(file, sheet, kind, axis) {
973
- if (axis.state !== 'delete_modify') return axis.default;
974
- return sheetDecision(file, sheet)[kind][axis.id] || axis.default;
975
- }
976
- function axisKept(file, sheet, kind, axis) { return axisChoice(file, sheet, kind, axis) !== 'delete'; }
977
- function axisClass(file, sheet, kind, axis) {
978
- if (axis.state === 'deleted' || !axisKept(file, sheet, kind, axis)) return ' axis-tombstone';
979
- if (axis.state === 'added' && axis.incoming) return ' axis-added-incoming';
980
- return '';
981
- }
982
- function axisSource(axis, kind) {
983
- if (kind === 'rows') return `Base ${axis.baseRow ?? '—'} · 本地 ${axis.oursRow ?? '—'} · 远端 ${axis.theirsRow ?? '—'}`;
984
- return `Base ${axis.baseColumn ?? '—'} · 本地 ${axis.oursColumn ?? '—'} · 远端 ${axis.theirsColumn ?? '—'}`;
985
- }
986
- function structuralOutputMaps(file, sheet) {
987
- const headerCount = (sheet.headerRows || []).length;
988
- const rows = new Map(); const columns = new Map(); let rowIndex = headerCount; let columnIndex = 0;
989
- for (const row of sheet.allRows || []) if (axisKept(file, sheet, 'rows', row)) rows.set(row.id, ++rowIndex);
990
- for (const column of sheet.columns || []) if (axisKept(file, sheet, 'columns', column)) columns.set(column.id, colLabel(++columnIndex));
991
- return {rows, columns};
992
- }
993
- function structuralCellSelectable(file, sheet, cell) {
994
- if (cell.replacement) return false;
995
- if (!cell || !cell.changed || cell.selectable === false) return false;
996
- const row = (sheet.allRows || []).find(item => item.id === cell.rowId);
997
- const column = (sheet.columns || []).find(item => item.id === cell.colId);
998
- return !!row && !!column && !row.locked && !column.locked
999
- && axisKept(file, sheet, 'rows', row) && axisKept(file, sheet, 'columns', column);
1000
- }
1001
- function defaultDisplayChoice(cell) {
1002
- const choice = defaultCellChoice(cell);
1003
- if (choice === 'same') return cell.oursPresent ? 'ours' : 'theirs';
1004
- return choice;
1005
- }
1006
- function structuralCellValue(target, cell) {
1007
- const choice = target.cells[cell.id] || defaultDisplayChoice(cell);
1008
- if (choice === 'ours' && cell.oursPresent) return cell.ours;
1009
- if (choice === 'theirs' && cell.theirsPresent) return cell.theirs;
1010
- if (cell.oursPresent) return cell.ours;
1011
- if (cell.theirsPresent) return cell.theirs;
1012
- return cell.base;
1013
- }
1014
- function appendStructureControl(row, file, sheet, kind, axis) {
1015
- const cell = document.createElement('th'); cell.className = 'structure-control' + axisClass(file, sheet, kind, axis);
1016
- cell.title = axisSource(axis, kind);
1017
- if (axis.state === 'delete_modify') {
1018
- const button = document.createElement('button'); const kept = axisKept(file, sheet, kind, axis);
1019
- button.className = 'structure-toggle' + (kept ? '' : ' is-delete');
1020
- button.textContent = kept ? '已保留' : '已删除'; button.onclick = event => { event.stopPropagation(); toggleAxis(file, sheet, kind, axis); };
1021
- cell.append(button);
1022
- } else if (axis.state === 'added') {
1023
- const badge = document.createElement('span'); badge.className = `structure-badge ${axis.incoming ? 'added' : 'local-existing'}`;
1024
- const source = kind === 'rows' ? (axis.theirsRow ?? axis.oursRow) : (axis.theirsColumn ?? axis.oursColumn);
1025
- badge.textContent = `${axis.incoming ? '远端新增' : '本地已有'} · ${source}`; cell.append(badge);
1026
- } else if (axis.state === 'deleted') {
1027
- const badge = document.createElement('span'); badge.className = 'structure-badge deleted';
1028
- badge.textContent = `已删除 · ${kind === 'rows' ? axis.baseRow : axis.baseColumn}`; cell.append(badge);
1029
- }
1030
- row.append(cell); return cell;
1031
- }
1032
- function renderDiffTable(host, file, sheet) {
1033
- if (sheet.columns && sheet.allRows) return renderStructuralTable(host, file, sheet);
1034
- return renderLegacyDiffTable(host, file, sheet);
1035
- }
1036
- function buildHeaderMergeMap(sheet, selection) {
1037
- // 构建 header cell 的合并映射:key = "rowIndex|colIndex" -> {isOrigin, colspan}
1038
- const mc = sheet.mergedCells || {};
1039
- let regions;
1040
- if (mc.status === 'conflict') {
1041
- const choice = (selection && selection.mergedCells) || mc.default || 'ours';
1042
- regions = mc[choice] || mc.ours || [];
1043
- } else {
1044
- regions = mc.resolved || [];
1045
- }
1046
- const columns = sheet.columns || [];
1047
- const headerRows = sheet.headerRows || [];
1048
- const headerRowNumbers = headerRows.map(r => r.row);
1049
- const map = {};
1050
- for (const region of regions) {
1051
- const rowIdxs = (region.rows || []).map(r => r.startsWith('header:') ? parseInt(r.slice(7)) : null).filter(r => r !== null);
1052
- const colIds = region.columns || [];
1053
- if (rowIdxs.length < 1 || colIds.length < 2) continue;
1054
- const colIdxs = colIds.map(cid => columns.findIndex(c => c.id === cid)).filter(i => i >= 0);
1055
- if (colIdxs.length < 2) continue;
1056
- const minCol = Math.min(...colIdxs);
1057
- const maxCol = Math.max(...colIdxs);
1058
- for (const rowNum of rowIdxs) {
1059
- const hrIdx = headerRowNumbers.indexOf(rowNum);
1060
- if (hrIdx < 0) continue;
1061
- map[`${rowNum}|${minCol}`] = {isOrigin: true, colspan: maxCol - minCol + 1};
1062
- for (let c = minCol + 1; c <= maxCol; c++) {
1063
- map[`${rowNum}|${c}`] = {isOrigin: false};
1064
- }
1065
- }
1066
- }
1067
- return map;
1068
- }
1069
- function renderStructuralTable(host, file, sheet) {
1070
- const columns = sheet.columns || []; const rows = sheet.rows || [];
1071
- if (!rows.length && !columns.length) { renderMessage(host, sheet.name, '该 Sheet 没有表内数据差异。'); return; }
1072
- const target = sheetDecision(file, sheet);
1073
- const output = structuralOutputMaps(file, sheet);
1074
- const grid = new Map((sheet.gridCells || []).map(cell => [`${cell.rowId}|${cell.colId}`, cell]));
1075
- const table = document.createElement('table'); table.className = 'diff-table';
1076
- const head = document.createElement('thead');
1077
- const controls = document.createElement('tr'); appendHeaderCell(controls, '结构', null, 'structure-control');
1078
- for (const column of columns) appendStructureControl(controls, file, sheet, 'columns', column);
1079
- head.append(controls);
1080
- const letters = document.createElement('tr'); appendHeaderCell(letters, '行');
1081
- for (const column of columns) {
1082
- const header = appendHeaderCell(letters, output.columns.get(column.id) || '×', () => bulkStructuralColumn(column.id));
1083
- header.className += axisClass(file, sheet, 'columns', column);
1084
- header.title = `${axisSource(column, 'columns')} · 合并后 ${output.columns.get(column.id) || '删除'}`;
1085
- }
1086
- head.append(letters);
1087
- const headerMergeMap = buildHeaderMergeMap(sheet, sheetDecision(file, sheet));
1088
- for (const headerRow of sheet.headerRows || []) {
1089
- const row = document.createElement('tr'); row.className = 'luban-header'; appendHeaderCell(row, String(headerRow.row));
1090
- headerRow.cells.forEach((value, index) => {
1091
- const merge = headerMergeMap[`${headerRow.row}|${index}`];
1092
- if (merge && !merge.isOrigin) return; // 被合并的格子跳过
1093
- const cell = appendHeaderCell(row, fmtVal(value));
1094
- cell.className += axisClass(file, sheet, 'columns', columns[index]);
1095
- if (merge && merge.colspan > 1) cell.colSpan = merge.colspan;
1096
- });
1097
- head.append(row);
1098
- }
1099
- table.append(head);
1100
- const body = document.createElement('tbody');
1101
- const start = currentPage * PAGE_SIZE; const end = Math.min(rows.length, start + PAGE_SIZE);
1102
- for (let index = start; index < end; index++) {
1103
- const axisRow = rows[index]; const row = document.createElement('tr');
1104
- const rowHeader = document.createElement('th'); rowHeader.className = 'row-header' + axisClass(file, sheet, 'rows', axisRow);
1105
- rowHeader.title = `${axisSource(axisRow, 'rows')} · 合并后 ${output.rows.get(axisRow.id) || '删除'}`;
1106
- const outputIndex = document.createElement('span'); outputIndex.className = 'axis-index' + (output.rows.has(axisRow.id) ? '' : ' is-removed');
1107
- outputIndex.textContent = output.rows.has(axisRow.id) ? String(output.rows.get(axisRow.id)) : '×'; rowHeader.append(outputIndex);
1108
- if (axisRow.state === 'delete_modify') {
1109
- const button = document.createElement('button'); const kept = axisKept(file, sheet, 'rows', axisRow);
1110
- button.className = 'structure-toggle' + (kept ? '' : ' is-delete'); button.textContent = kept ? '已保留' : '已删除';
1111
- button.onclick = event => { event.stopPropagation(); toggleAxis(file, sheet, 'rows', axisRow); }; rowHeader.append(button);
1112
- } else {
1113
- if (axisRow.state === 'added' || axisRow.state === 'deleted') {
1114
- const badge = document.createElement('span'); badge.className = `structure-badge ${axisRow.state}`;
1115
- badge.textContent = axisRow.state === 'added' ? (axisRow.incoming ? '远端新增' : '本地已有') : '已删除'; rowHeader.append(document.createTextNode(' '), badge);
1116
- }
1117
- }
1118
- const source = document.createElement('span'); source.className = 'axis-source'; source.textContent = axisSource(axisRow, 'rows'); rowHeader.append(source);
1119
- if (axisKept(file, sheet, 'rows', axisRow) && !axisRow.locked) rowHeader.onclick = () => bulkStructuralRow(axisRow.id);
1120
- row.append(rowHeader);
1121
- for (const column of columns) {
1122
- const cellData = grid.get(`${axisRow.id}|${column.id}`); const cell = document.createElement('td');
1123
- const kept = axisKept(file, sheet, 'rows', axisRow) && axisKept(file, sheet, 'columns', column);
1124
- const structurallyLocked = !kept || axisRow.locked || column.locked;
1125
- if (!kept || axisRow.state === 'deleted' || column.state === 'deleted') cell.className = 'axis-tombstone cell-locked';
1126
- else if ((axisRow.state === 'added' && axisRow.incoming) || (column.state === 'added' && column.incoming)) cell.className = 'axis-added-incoming cell-locked';
1127
- else if (axisRow.state === 'added' || column.state === 'added') cell.className = 'cell-no-conflict cell-locked';
1128
- else if (cellData && cellData.changed) {
1129
- const choice = target.cells[cellData.id] || defaultDisplayChoice(cellData);
1130
- const selectable = structuralCellSelectable(file, sheet, cellData);
1131
- cell.className = (choice === 'ours' ? 'cell-local' : 'cell-remote') + (selectable ? ' cell-selectable' : ' cell-locked');
1132
- } else cell.className = 'cell-no-conflict' + (structurallyLocked ? ' cell-locked' : '');
1133
- if (cellData) {
1134
- cell.textContent = fmtVal(structuralCellValue(target, cellData));
1135
- if (cellData.requiresChoice && !target.cells[cellData.id]) {
1136
- cell.textContent = '待选择';
1137
- cell.className = 'cell-no-conflict cell-selectable';
1138
- }
1139
- if (structuralCellSelectable(file, sheet, cellData)) {
1140
- cell.onclick = () => cycleCell(file, sheet, cellData);
1141
- if (cellNeedsReview(cellData)) cell.dataset.conflictId = cellData.id;
1142
- }
1143
- bindStructuralTip(cell, file, sheet, axisRow, column, cellData);
1144
- }
1145
- row.append(cell);
1146
- }
1147
- body.append(row);
1148
- }
1149
- table.append(body); host.append(table); if (rows.length > PAGE_SIZE) renderPager(host, rows.length);
1150
- }
1151
- function renderLegacyDiffTable(host, file, sheet) {
1152
- const changedCells = sheet.cells || [];
1153
- if (!changedCells.length) {
1154
- renderMessage(host, sheet.name, '该 Sheet 没有单元格差异。');
1155
- return;
1156
- }
1157
- const maxCol = sheet.maxCol || 1;
1158
- const changedMap = new Map(changedCells.map(cell => [`${cell.row},${cell.col}`, cell]));
1159
- const changedRows = [...new Set(changedCells.map(cell => cell.row))].sort((a, b) => a - b);
1160
- const a1 = gridVal(sheet, 1, 1);
1161
- const isVertical = typeof a1 === 'string' && a1.startsWith('##column##var');
1162
- const headerRows = [];
1163
- if (!isVertical) {
1164
- for (let row = 1; row <= 20; row++) {
1165
- const value = gridVal(sheet, row, 1);
1166
- if (typeof value === 'string' && value.startsWith('##')) headerRows.push(row);
1167
- else if (headerRows.length) break;
1168
- }
1169
- }
1170
-
1171
- const table = document.createElement('table'); table.className = 'diff-table';
1172
- const head = document.createElement('thead');
1173
- const letters = document.createElement('tr'); appendHeaderCell(letters, '行');
1174
- for (let col = 1; col <= maxCol; col++) appendHeaderCell(letters, colLabel(col), () => bulkCol(col));
1175
- head.append(letters);
1176
- if (isVertical) {
1177
- const meanings = {1: '字段名 ##var', 2: '类型 ##type', 3: '注释'};
1178
- const row = document.createElement('tr'); row.className = 'luban-header'; appendHeaderCell(row, '列义');
1179
- for (let col = 1; col <= maxCol; col++) appendHeaderCell(row, meanings[col] || '');
1180
- head.append(row);
1181
- } else {
1182
- for (const headerRow of headerRows) {
1183
- const row = document.createElement('tr'); row.className = 'luban-header'; appendHeaderCell(row, String(headerRow));
1184
- for (let col = 1; col <= maxCol; col++) {
1185
- const cell = appendHeaderCell(row, fmtVal(gridVal(sheet, headerRow, col)));
1186
- bindTip(cell, headerRow, col);
1187
- }
1188
- head.append(row);
1189
- }
1190
- }
1191
- table.append(head);
1192
-
1193
- const body = document.createElement('tbody');
1194
- const start = currentPage * PAGE_SIZE;
1195
- const end = Math.min(changedRows.length, start + PAGE_SIZE);
1196
- const target = sheetDecision(file, sheet);
1197
- for (let index = start; index < end; index++) {
1198
- const rowNumber = changedRows[index];
1199
- const row = document.createElement('tr');
1200
- appendHeaderCell(row, String(rowNumber), () => bulkRow(rowNumber), 'row-header');
1201
- for (let col = 1; col <= maxCol; col++) {
1202
- const key = `${rowNumber},${col}`;
1203
- const changed = changedMap.get(key);
1204
- const cell = document.createElement('td');
1205
- if (changed) {
1206
- const choice = target.cells[changed.coordinate] || defaultCellChoice(changed);
1207
- cell.className = choice === 'ours' ? 'cell-local' : 'cell-remote';
1208
- cell.textContent = fmtVal(choice === 'ours' ? changed.ours : changed.theirs);
1209
- cell.onclick = () => cycleCell(file, sheet, changed);
1210
- if (cellNeedsReview(changed)) cell.dataset.conflictId = changed.id || changed.coordinate;
1211
- } else {
1212
- cell.className = 'cell-no-conflict';
1213
- cell.textContent = fmtVal(gridVal(sheet, rowNumber, col));
1214
- }
1215
- bindTip(cell, rowNumber, col);
1216
- row.append(cell);
1217
- }
1218
- body.append(row);
1219
- }
1220
- table.append(body); host.append(table);
1221
- if (changedRows.length > PAGE_SIZE) renderPager(host, changedRows.length);
1222
- }
1223
- function renderPager(host, totalRows) {
1224
- const pages = Math.ceil(totalRows / PAGE_SIZE);
1225
- const pager = document.createElement('div'); pager.className = 'pager';
1226
- for (let page = 0; page < pages; page++) {
1227
- const button = document.createElement('button');
1228
- button.className = 'btn' + (page === currentPage ? ' btn-local' : '');
1229
- button.textContent = String(page + 1);
1230
- button.onclick = () => { currentPage = page; renderTable(); };
1231
- pager.append(button);
1232
- }
1233
- host.append(pager);
1234
- }
1235
-
1236
- function changedCellAt(sheet, row, col) { return (sheet.cells || []).find(cell => cell.row === row && cell.col === col); }
1237
- function bindStructuralTip(cell, file, sheet, row, column, data) {
1238
- cell.onmouseenter = event => showStructuralTip(event, file, sheet, row, column, data);
1239
- cell.onmousemove = event => positionTip(event); cell.onmouseleave = hideTip;
1240
- }
1241
- function addTipLine(host, className, label, value, author, date) {
1242
- const line = document.createElement('div'); line.className = className;
1243
- line.append(document.createTextNode(`${label}: ${fmtVal(value)}`));
1244
- const metaParts = [];
1245
- if (author) metaParts.push(`作者: ${author}`);
1246
- if (date) metaParts.push(date);
1247
- if (metaParts.length) { const span = document.createElement('span'); span.className = 'author'; span.textContent = metaParts.join(' '); line.append(span); }
1248
- host.append(line);
1249
- }
1250
- function showTip(event, row, col) {
1251
- const file = currentFileData(); const sheet = currentSheetData(); const changed = changedCellAt(sheet, row, col);
1252
- const tip = byId('tooltip'); tip.replaceChildren();
1253
- const label = document.createElement('div'); label.className = 'label';
1254
- label.textContent = `${file.path} / ${sheet.name} / 第 ${row} 行, ${colLabel(col)} 列`;
1255
- tip.append(label);
1256
- if (changed) {
1257
- const choice = sheetDecision(file, sheet).cells[changed.coordinate] || defaultCellChoice(changed);
1258
- addTipLine(tip, 'val-base', '基线', changed.base, '');
1259
- addTipLine(tip, 'val-local', '本地', changed.ours, file.oursAuthor, file.oursDate);
1260
- addTipLine(tip, 'val-remote', '远端', changed.theirs, file.theirsAuthor, file.theirsDate);
1261
- addTipLine(tip, 'val-current', '当前选择', choice === 'ours' ? '本地' : '远端', '');
1262
- if (changed.resolution !== 'conflict') addTipLine(tip, 'label', '三方建议', changed.resolution === 'ours' ? '自动采用本地' : '自动采用远端', '');
1263
- } else {
1264
- addTipLine(tip, 'val-current', '值', gridVal(sheet, row, col), '');
1265
- }
1266
- tip.style.display = 'block'; positionTip(event);
1267
- }
1268
- function showStructuralTip(event, file, sheet, row, column, cell) {
1269
- const tip = byId('tooltip'); tip.replaceChildren();
1270
- const label = document.createElement('div'); label.className = 'label';
1271
- label.textContent = `${file.path} / ${sheet.name} / ${row.id} / ${column.id}`; tip.append(label);
1272
- addTipLine(tip, 'val-base', '基线', cell.base, '');
1273
- if (cell.calculationErrors) {
1274
- for (const [side, error] of Object.entries(cell.calculationErrors)) {
1275
- addTipLine(tip, 'label', `${side === 'base' ? '历史' : side === 'ours' ? '本地' : '远端'}值未知`, `${error.coordinate}: ${error.formula} → ${error.error}`, '');
1276
- }
1277
- if (!sheetDecision(file, sheet).cells[cellKey(cell)]) addTipLine(tip, 'label', '待选择', '请点击明确选择本地或远端;当前展示不代表已选择。', '');
1278
- }
1279
- if (cell.replacement) {
1280
- for (const [side, repair] of Object.entries(cell.replacement)) {
1281
- addTipLine(tip, 'label', side === 'ours' ? '本地原错误' : '远端原错误', `${repair.coordinate}: ${repair.formula} → ${repair.error}`, '');
1282
- }
1283
- addTipLine(tip, 'label', '按类型替换', JSON.stringify(cell.replacement.ours.value), '');
1284
- }
1285
- addTipLine(tip, 'val-local', '本地', cell.ours, file.oursAuthor, file.oursDate);
1286
- addTipLine(tip, 'val-remote', '远端', cell.theirs, file.theirsAuthor, file.theirsDate);
1287
- const choice = sheetDecision(file, sheet).cells[cell.id] || defaultDisplayChoice(cell);
1288
- addTipLine(tip, 'val-current', '当前选择', choice ? (choice === 'ours' ? '本地' : '远端') : '待选择', '');
1289
- addTipLine(tip, 'label', '行来源', axisSource(row, 'rows'), '');
1290
- addTipLine(tip, 'label', '列来源', axisSource(column, 'columns'), '');
1291
- if (row.state !== 'common') addTipLine(tip, 'label', '行状态', row.status, '');
1292
- if (column.state !== 'common') addTipLine(tip, 'label', '列状态', column.status, '');
1293
- addTipLine(tip, 'label', '交互', structuralCellSelectable(file, sheet, cell) ? '可点击切换版本' : '结构已锁定', '');
1294
- tip.style.display = 'block'; positionTip(event);
1295
- }
1296
- function positionTip(event) {
1297
- const tip = byId('tooltip');
1298
- const left = Math.min(event.clientX + 12, window.innerWidth - tip.offsetWidth - 12);
1299
- const top = Math.min(event.clientY + 12, window.innerHeight - tip.offsetHeight - 12);
1300
- tip.style.left = `${Math.max(8, left)}px`; tip.style.top = `${Math.max(8, top)}px`;
1301
- }
1302
- function hideTip() { byId('tooltip').style.display = 'none'; }
1303
-
1304
- function pushCellUndo(file, sheet, cell) {
1305
- const target = sheetDecision(file, sheet); const key = cellKey(cell); const previous = target.cells[key];
1306
- undoStack.push({kind: 'cell', fileId: file.id, sheet: sheet.name, key, previous});
1307
- }
1308
- function cycleCell(file, sheet, cell) {
1309
- const target = sheetDecision(file, sheet); pushCellUndo(file, sheet, cell);
1310
- const key = cellKey(cell);
1311
- target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1312
- renderTable(); renderConflictNavigation(); updateStats();
1313
- }
1314
- function chooseSheet(file, sheet, side) {
1315
- const target = sheetDecision(file, sheet);
1316
- undoStack.push({kind: 'sheet', fileId: file.id, sheet: sheet.name, previous: target.sheet});
1317
- target.sheet = side; target.confirmed = false; render();
1318
- }
1319
- function chooseRename(file, sheet, side) {
1320
- const target = sheetDecision(file, sheet);
1321
- undoStack.push({kind: 'rename', fileId: file.id, sheet: sheet.name, previous: target.rename});
1322
- target.rename = side; renderSheetChoice(); updateStats();
1323
- }
1324
- function chooseMergedCells(file, sheet, side) {
1325
- const target = sheetDecision(file, sheet);
1326
- undoStack.push({kind: 'mergedCells', fileId: file.id, sheet: sheet.name, previous: target.mergedCells});
1327
- target.mergedCells = side; renderSheetChoice(); renderTable(); updateStats();
1328
- }
1329
- function toggleAxis(file, sheet, kind, axis) {
1330
- const target = sheetDecision(file, sheet); const previous = target[kind][axis.id] || axis.default;
1331
- undoStack.push({kind: 'axis', fileId: file.id, sheet: sheet.name, axisKind: kind, axisId: axis.id, previous});
1332
- target[kind][axis.id] = previous === 'keep' ? 'delete' : 'keep';
1333
- renderSheetTabs(); renderTable(); renderConflictNavigation(); updateStats();
1334
- }
1335
- function chooseMacro(file, side) {
1336
- const target = fileDecision(file); const previous = target.macro || file.macro.default;
1337
- if (side === 'theirs' && !file.macro.canChooseTheirs) return;
1338
- undoStack.push({kind: 'macro', fileId: file.id, previous});
1339
- target.macro = side; render();
1340
- }
1341
- function sideAxisChoice(axis, side) {
1342
- const key = side === 'ours' ? ['oursRow', 'oursCol'] : ['theirsRow', 'theirsCol'];
1343
- return key.some(name => axis[name] !== undefined && axis[name] !== null) ? 'keep' : 'delete';
1344
- }
1345
- function bulkChoose(side) {
1346
- const file = currentFileData(); const sheet = currentSheetData(); if (!sheet) return;
1347
- if (currentSheetIsConfirmed()) return;
1348
- if (sheet.action.startsWith('conflict_')) { chooseSheet(file, sheet, side); return; }
1349
- const target = sheetDecision(file, sheet);
1350
- if (sheet.renameStatus === 'rename_conflict') {
1351
- undoStack.push({kind: 'rename', fileId: file.id, sheet: sheet.name, previous: target.rename});
1352
- target.rename = side;
1353
- }
1354
- if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') {
1355
- undoStack.push({kind: 'mergedCells', fileId: file.id, sheet: sheet.name, previous: target.mergedCells});
1356
- target.mergedCells = side;
1357
- }
1358
- for (const [kind, axes] of [['rows', sheet.allRows || sheet.rows || []], ['columns', sheet.columns || []]]) {
1359
- for (const axis of axes) if (axis.state === 'delete_modify') {
1360
- undoStack.push({kind: 'axis', fileId: file.id, sheet: sheet.name, axisKind: kind, axisId: axis.id, previous: target[kind][axis.id]});
1361
- target[kind][axis.id] = sideAxisChoice(axis, side);
1362
- }
1363
- }
1364
- for (const cell of sheet.cells || []) {
1365
- const key = cellKey(cell); const selected = side === 'ours' ? cell.oursPresent !== false : cell.theirsPresent !== false;
1366
- if (!selected) continue;
1367
- pushCellUndo(file, sheet, cell); target.cells[key] = side;
1368
- }
1369
- render();
1370
- }
1371
- function bulkStructuralRow(rowId) {
1372
- const file = currentFileData(); const sheet = currentSheetData(); const target = sheetDecision(file, sheet);
1373
- const row = (sheet.allRows || []).find(item => item.id === rowId);
1374
- if (!row || !axisKept(file, sheet, 'rows', row)) return;
1375
- for (const cell of (sheet.cells || []).filter(item => item.rowId === rowId)) {
1376
- const column = (sheet.columns || []).find(item => item.id === cell.colId);
1377
- if (!column || !axisKept(file, sheet, 'columns', column) || row.locked || column.locked) continue;
1378
- pushCellUndo(file, sheet, cell); const key = cellKey(cell);
1379
- target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1380
- }
1381
- renderTable(); renderConflictNavigation(); updateStats();
1382
- }
1383
- function bulkStructuralColumn(columnId) {
1384
- const file = currentFileData(); const sheet = currentSheetData(); const target = sheetDecision(file, sheet);
1385
- const column = (sheet.columns || []).find(item => item.id === columnId);
1386
- if (!column || !axisKept(file, sheet, 'columns', column)) return;
1387
- for (const cell of (sheet.cells || []).filter(item => item.colId === columnId)) {
1388
- const row = (sheet.allRows || []).find(item => item.id === cell.rowId);
1389
- if (!row || !axisKept(file, sheet, 'rows', row) || row.locked || column.locked) continue;
1390
- pushCellUndo(file, sheet, cell); const key = cellKey(cell);
1391
- target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1392
- }
1393
- renderTable(); renderConflictNavigation(); updateStats();
1394
- }
1395
- function bulkRow(row) {
1396
- const file = currentFileData(); const sheet = currentSheetData();
1397
- for (const cell of (sheet.cells || []).filter(item => item.row === row)) {
1398
- const target = sheetDecision(file, sheet); pushCellUndo(file, sheet, cell);
1399
- const key = cellKey(cell); target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1400
- }
1401
- renderTable(); renderConflictNavigation(); updateStats();
1402
- }
1403
- function bulkCol(col) {
1404
- const file = currentFileData(); const sheet = currentSheetData();
1405
- for (const cell of (sheet.cells || []).filter(item => item.col === col)) {
1406
- const target = sheetDecision(file, sheet); pushCellUndo(file, sheet, cell);
1407
- const key = cellKey(cell); target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1408
- }
1409
- renderTable(); renderConflictNavigation(); updateStats();
1410
- }
1411
- function undo() {
1412
- const file = currentFileData(); const sheet = currentSheetData();
1413
- if (!file || !sheet) return;
1414
- let actionIndex = -1;
1415
- for (let index = undoStack.length - 1; index >= 0; index--) {
1416
- const candidate = undoStack[index];
1417
- if (candidate.fileId === file.id && candidate.sheet === sheet.name) {
1418
- actionIndex = index;
1419
- break;
1420
- }
1421
- }
1422
- if (actionIndex < 0) return;
1423
- const [action] = undoStack.splice(actionIndex, 1);
1424
- const actionFile = model.files.find(item => item.id === action.fileId);
1425
- const actionSheet = actionFile.diff.sheets.find(item => item.name === action.sheet);
1426
- const target = sheetDecision(actionFile, actionSheet);
1427
- target.confirmed = false;
1428
- if (action.kind === 'sheet') target.sheet = action.previous;
1429
- else if (action.kind === 'rename') target.rename = action.previous;
1430
- else if (action.kind === 'mergedCells') target.mergedCells = action.previous;
1431
- else if (action.kind === 'axis') target[action.axisKind][action.axisId] = action.previous;
1432
- else target.cells[action.key] = action.previous;
1433
- render();
1434
- }
1435
- function resetSheet() {
1436
- const file = currentFileData();
1437
- const sheet = currentSheetData();
1438
- if (!file || !sheet) return;
1439
- const target = sheetDecision(file, sheet); const sheetChoice = defaultSheetChoice(sheet);
1440
- target.confirmed = false;
1441
- delete target.lastNavigatedConflict;
1442
- if (sheetChoice) target.sheet = sheetChoice; else delete target.sheet;
1443
- if (sheet.renameStatus === 'rename_conflict') target.rename = 'ours'; else delete target.rename;
1444
- if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') target.mergedCells = sheet.mergedCells.default || 'ours'; else delete target.mergedCells;
1445
- target.rows = {}; target.columns = {}; target.cells = {};
1446
- delete target.repairs;
1447
- for (const row of sheet.allRows || sheet.rows || []) if (row.state === 'delete_modify') target.rows[row.id] = row.default;
1448
- for (const column of sheet.columns || []) if (column.state === 'delete_modify') target.columns[column.id] = column.default;
1449
- for (const cell of sheet.cells || []) target.cells[cellKey(cell)] = defaultCellChoice(cell);
1450
- // A reset supersedes prior choices for this Sheet, while preserving other files,
1451
- // other Sheets, and file-level macro choices in the shared undo history.
1452
- undoStack = undoStack.filter(action => action.fileId !== file.id || action.sheet !== sheet.name);
1453
- render();
1454
- }
1455
- function updateGlobalConfirmationStats() {
1456
- let confirmed = 0; let total = 0;
1457
- for (const file of model.files) for (const sheet of file.diff.sheets) {
1458
- if (!sheetNeedsConfirmation(sheet)) continue;
1459
- total++;
1460
- if (sheetDecision(file, sheet).confirmed) confirmed++;
1461
- }
1462
- byId('confirmedSheetCount').textContent = String(confirmed);
1463
- byId('totalConflictSheetCount').textContent = String(total);
1464
- }
1465
- function updateDecisionFooterStats() {
1466
- let total = 0; let local = 0;
1467
- for (const file of model.files) {
1468
- if (file.macro && file.macro.status === 'conflict') {
1469
- total++; if ((fileDecision(file).macro || file.macro.default) === 'ours') local++;
1470
- }
1471
- for (const sheet of file.diff.sheets) {
1472
- const target = sheetDecision(file, sheet);
1473
- if (sheet.action.startsWith('conflict_')) { total++; if (target.sheet === 'ours') local++; }
1474
- if (sheet.renameStatus === 'rename_conflict') { total++; if (target.rename === 'ours') local++; }
1475
- if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') { total++; if (target.mergedCells === 'ours') local++; }
1476
- for (const row of sheet.allRows || sheet.rows || []) if (row.state === 'delete_modify') {
1477
- total++; const oursChoice = row.oursRow !== null && row.oursRow !== undefined ? 'keep' : 'delete';
1478
- if ((target.rows[row.id] || row.default) === oursChoice) local++;
1479
- }
1480
- for (const column of sheet.columns || []) if (column.state === 'delete_modify') {
1481
- total++; const oursChoice = column.oursCol !== null && column.oursCol !== undefined ? 'keep' : 'delete';
1482
- if ((target.columns[column.id] || column.default) === oursChoice) local++;
1483
- }
1484
- for (const cell of sheet.cells || []) {
1485
- if (sheet.columns && sheet.allRows && !structuralCellSelectable(file, sheet, cell)) continue;
1486
- total++; if (target.cells[cellKey(cell)] === 'ours') local++;
1487
- }
1488
- }
1489
- }
1490
- const file = currentFileData(); const sheet = currentSheetData();
1491
- byId('footerStatus').textContent = `共 ${total} 个可决策项,${local} 项采用本地 · 当前:${file.path}${sheet ? ` / ${sheet.name}` : ''}${autoTheirsNote(' · ')}`;
1492
- }
1493
- function updateStats() {
1494
- updateGlobalConfirmationStats();
1495
- updateDecisionFooterStats();
1496
- }
1497
-
1498
- function renderCommitSteps(steps) {
1499
- const host = byId('commitModalSteps'); host.replaceChildren();
1500
- for (const step of steps || []) {
1501
- const line = document.createElement('div');
1502
- line.textContent = `${step.success ? '✓' : '✗'} ${step.step || ''}${step.output ? ` — ${String(step.output).slice(0, 240)}` : ''}`;
1503
- host.append(line);
1504
- }
1505
- }
1506
- function showCommitModal(kind, title, body, steps, buttons) {
1507
- const modal = byId('commitModal'); modal.classList.remove('is-hidden', 'is-success', 'is-error');
1508
- if (kind) modal.classList.add(`is-${kind}`);
1509
- byId('commitModalTitle').textContent = title; byId('commitModalBody').textContent = body || ''; renderCommitSteps(steps);
1510
- const actions = byId('commitModalActions'); actions.replaceChildren();
1511
- for (const spec of buttons || []) { const button = document.createElement('button'); button.className = `btn ${spec.className || ''}`; button.textContent = spec.label; button.onclick = spec.onclick; actions.append(button); }
1512
- }
1513
- function closeCommitModal() { byId('commitModal').classList.add('is-hidden'); }
1514
- async function cancelAndExit() {
1515
- const cancelButton = byId('cancelBtn');
1516
- const submitButton = byId('submitBtn');
1517
- cancelButton.disabled = true;
1518
- submitButton.disabled = true;
1519
- byId('footerStatus').textContent = '正在取消并退出,不会写入任何更改...';
1520
- try {
1521
- const response = await fetch('/api/shutdown', {method: 'POST'});
1522
- const result = await response.json();
1523
- if (!response.ok || !result.success) throw new Error(result.error || '无法关闭解析器');
1524
- byId('footerStatus').textContent = '已取消,未写入任何更改。';
1525
- window.close();
1526
- } catch (error) {
1527
- cancelButton.disabled = false;
1528
- submitButton.disabled = false;
1529
- byId('footerStatus').textContent = `退出失败: ${error.message}`;
1530
- }
1531
- }
1532
- function renderCommitMessage(text) {
1533
- const host = byId('commitModalSteps'); host.replaceChildren();
1534
- const line = document.createElement('div');
1535
- line.textContent = text || '(无冲突 Cell,将使用默认提交信息)';
1536
- host.append(line);
1537
- }
1538
- function unconfirmedSheets() {
1539
- const pending = [];
1540
- for (const [fileIndex, file] of model.files.entries()) {
1541
- for (const [sheetIndex, sheet] of file.diff.sheets.entries()) {
1542
- if (!sheetNeedsConfirmation(sheet) || sheetDecision(file, sheet).confirmed) continue;
1543
- pending.push({file, sheet, fileIndex, sheetIndex, label: `${file.path}-${sheet.name}`});
1544
- }
1545
- }
1546
- return pending;
1547
- }
1548
- function renderUnconfirmedSheetList(pending) {
1549
- const host = byId('commitModalSteps'); host.replaceChildren();
1550
- for (const item of pending) {
1551
- const button = document.createElement('button');
1552
- button.type = 'button';
1553
- button.className = 'btn btn-cancel';
1554
- button.style.display = 'block';
1555
- button.style.width = '100%';
1556
- button.style.marginBottom = '7px';
1557
- button.style.textAlign = 'left';
1558
- button.textContent = item.label;
1559
- button.title = `切换到 ${item.label}`;
1560
- button.onclick = () => {
1561
- currentFile = item.fileIndex;
1562
- currentSheet = item.sheetIndex;
1563
- currentPage = 0;
1564
- closeCommitModal();
1565
- render();
1566
- };
1567
- host.append(button);
1568
- }
1569
- }
1570
- async function submitResolve() {
1571
- const button = byId('submitBtn');
1572
- const pending = unconfirmedSheets();
1573
- if (pending.length) {
1574
- byId('footerStatus').textContent = `仍有 ${pending.length} 个 Sheet 未确认,请先完成审阅。`;
1575
- showCommitModal('', '仍有未确认的 Sheet', '提交前必须人工勾选确认每个需要审阅的 Sheet。点击下方条目可直接切换过去。', [], [
1576
- {label: '返回继续审阅', className: 'btn-submit', onclick: () => { closeCommitModal(); button.disabled = false; }}
1577
- ]);
1578
- renderUnconfirmedSheetList(pending);
1579
- return;
1580
- }
1581
- button.disabled = true;
1582
- byId('footerStatus').textContent = '正在生成 commit 信息预览...';
1583
- try {
1584
- const previewResponse = await fetch('/api/commit-preview', {
1585
- method: 'POST', headers: {'Content-Type': 'application/json'},
1586
- body: JSON.stringify({decisions})
1587
- });
1588
- const preview = await previewResponse.json();
1589
- if (!previewResponse.ok || preview.error) throw new Error(preview.error || '无法生成 commit 信息');
1590
- // 居中二次确认:展示 commit 信息列表(可滑动),确认后才真正执行 add / commit
1591
- showCommitModal('', '确认提交', '请核对以下 commit 信息,确认后将执行 git add / commit:', [], [
1592
- {label: '取消', className: '', onclick: () => { closeCommitModal(); button.disabled = false; byId('footerStatus').textContent = '已取消,未提交任何更改。'; }},
1593
- {label: '确认提交', className: 'btn-submit', onclick: () => { closeCommitModal(); doSubmitResolve(); }}
1594
- ]);
1595
- renderCommitMessage(preview.message || '');
1596
- } catch (error) {
1597
- button.disabled = false;
1598
- byId('footerStatus').textContent = `错误: ${error.message}`;
1599
- }
1600
- }
1601
- async function doSubmitResolve() {
1602
- byId('footerStatus').textContent = '正在合并并提交...';
1603
- showCommitModal('', '正在合并并提交...', '正在写回工作簿并执行 git add / commit,请稍候。', [], []);
1604
- try {
1605
- const response = await fetch('/api/resolve', {
1606
- method: 'POST', headers: {'Content-Type': 'application/json'},
1607
- body: JSON.stringify({decisions, commit: true, push: false})
1608
- });
1609
- const result = await response.json();
1610
- if (!result.success) throw new Error(result.error || (result.steps || []).filter(step => !step.success).map(step => `${step.step}: ${step.output}`).join('\n') || '提交失败');
1611
- byId('footerStatus').textContent = '完成!合并并提交成功。';
1612
- showCommitModal('success', '提交成功', '多 Sheet 合并结果已写入并提交。解析器即将关闭。', result.steps, [
1613
- {label: '关闭窗口', className: 'btn-submit', onclick: () => { try { window.close(); } catch (_) {} }}
1614
- ]);
1615
- } catch (error) {
1616
- const c = byId('submitBtn'); c.disabled = false; byId('footerStatus').textContent = `错误: ${error.message}`;
1617
- showCommitModal('error', '提交失败', error.message, [], [{label: '关闭', onclick: closeCommitModal}]);
1618
- }
1619
- }
1620
-
1621
- byId('allLocalBtn').onclick = () => bulkChoose('ours');
1622
- byId('allRemoteBtn').onclick = () => bulkChoose('theirs');
1623
- byId('undoBtn').onclick = undo;
1624
- byId('resetBtn').onclick = resetSheet;
1625
- byId('cancelBtn').onclick = cancelAndExit;
1626
- byId('submitBtn').onclick = submitResolve;
1627
- byId('prevConflictBtn').onclick = () => locateConflictCell(-1);
1628
- byId('nextConflictBtn').onclick = () => locateConflictCell(1);
1629
- enableHorizontalWheel(byId('fileTabs'));
1630
- enableHorizontalWheel(byId('sheetTabs'));
1631
- init().catch(error => { byId('footerStatus').textContent = `加载失败: ${error.message}`; });
1632
- </script>
1633
- </body>
1634
- </html>
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Excel 冲突解决工具</title>
7
+ <style>
8
+ :root {
9
+ --bg-deep: #f4eed8;
10
+ --bg-root: #e6dfc8;
11
+ --bg-surface: #ffffff;
12
+ --border-default: #000000;
13
+ --shadow-edge: #625a4d;
14
+ --gold: #f2c94c;
15
+ --gold-dim: #e0b83e;
16
+ --lava: #f29aa3;
17
+ --emerald: #a2d2ff;
18
+ --sapphire: #9dccff;
19
+ --incoming: #cfe9b7;
20
+ --incoming-deep: #b6d998;
21
+ --tombstone: #77736b;
22
+ --tombstone-dark: #58554f;
23
+ --text-primary: #111111;
24
+ --text-secondary: #444444;
25
+ --text-muted: #777777;
26
+ --shadow: 4px 4px 0 #000000;
27
+ --shadow-hover: 2px 2px 0 #000000;
28
+ --border-width: 3px;
29
+ }
30
+ * { margin: 0; padding: 0; box-sizing: border-box; }
31
+ html { width: 100%; height: 100%; overflow: hidden; }
32
+ body {
33
+ font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
34
+ background: var(--bg-deep);
35
+ background-image:
36
+ linear-gradient(var(--bg-root) 1px, transparent 1px),
37
+ linear-gradient(90deg, var(--bg-root) 1px, transparent 1px);
38
+ background-size: 20px 20px;
39
+ color: var(--text-primary);
40
+ width: 100%;
41
+ height: 100vh;
42
+ min-height: 0;
43
+ overflow: hidden;
44
+ display: flex;
45
+ flex-direction: column;
46
+ }
47
+ .toolbar {
48
+ background: var(--bg-surface);
49
+ padding: 12px 20px;
50
+ display: flex;
51
+ align-items: center;
52
+ gap: 16px;
53
+ border-bottom: var(--border-width) solid var(--border-default);
54
+ flex-wrap: nowrap;
55
+ min-width: 0;
56
+ }
57
+ .toolbar h1 {
58
+ flex: 0 0 auto;
59
+ font-size: 18px;
60
+ font-weight: 700;
61
+ white-space: nowrap;
62
+ }
63
+ .file-tabs, .sheet-tabs {
64
+ display: flex;
65
+ gap: 6px;
66
+ flex-wrap: nowrap;
67
+ min-width: 0;
68
+ overflow-x: auto;
69
+ overflow-y: hidden;
70
+ overscroll-behavior-inline: contain;
71
+ scrollbar-color: var(--border-default) transparent;
72
+ scrollbar-width: thin;
73
+ }
74
+ .file-tabs { flex: 1 1 auto; padding: 2px 4px 7px 0; }
75
+ .sheet-tabs { flex: 1 1 auto; padding: 2px 4px 5px 0; }
76
+ .file-tabs::-webkit-scrollbar, .sheet-tabs::-webkit-scrollbar { height: 8px; }
77
+ .file-tabs::-webkit-scrollbar-track, .sheet-tabs::-webkit-scrollbar-track { background: transparent; }
78
+ .file-tabs::-webkit-scrollbar-thumb, .sheet-tabs::-webkit-scrollbar-thumb {
79
+ background: var(--border-default);
80
+ border: 2px solid var(--bg-surface);
81
+ }
82
+ .file-tab, .sheet-tab {
83
+ flex: 0 0 auto;
84
+ padding: 8px 16px;
85
+ background: var(--bg-surface);
86
+ color: var(--text-secondary);
87
+ cursor: pointer;
88
+ font-size: 13px;
89
+ font-weight: 600;
90
+ border: var(--border-width) solid var(--border-default);
91
+ box-shadow: var(--shadow);
92
+ transition: transform 150ms ease, box-shadow 150ms ease;
93
+ }
94
+ .file-tab:hover, .sheet-tab:hover { transform: translate(2px, 2px); box-shadow: var(--shadow-hover); }
95
+ .file-tab.active {
96
+ background: var(--emerald);
97
+ transform: translate(2px, 2px);
98
+ box-shadow: var(--shadow-hover);
99
+ }
100
+ .file-tab.has-conflicts { color: var(--text-primary); }
101
+ .sheet-toolbar {
102
+ background: #fff8dc;
103
+ padding: 9px 20px 11px;
104
+ display: flex;
105
+ align-items: center;
106
+ gap: 12px;
107
+ border-bottom: var(--border-width) solid var(--border-default);
108
+ flex-wrap: nowrap;
109
+ min-width: 0;
110
+ }
111
+ .sheet-scope {
112
+ display: flex;
113
+ align-items: center;
114
+ gap: 9px;
115
+ min-width: 0;
116
+ flex: 1 1 auto;
117
+ }
118
+ .sheet-choice { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
119
+ .macro-label { font-size: 11px; font-weight: 900; color: #3d3529; white-space: nowrap; }
120
+ .macro-toggle { padding: 5px 9px; font-size: 11px; opacity: .55; }
121
+ .macro-toggle.is-selected { opacity: 1; outline: 2px solid #4f4638; outline-offset: 1px; }
122
+ .macro-toggle:disabled { cursor: not-allowed; filter: grayscale(.45); opacity: .45; }
123
+ .macro-note { font-size: 11px; font-weight: 700; color: #6a5142; white-space: nowrap; }
124
+ .diff-legend {
125
+ display: flex;
126
+ align-items: center;
127
+ gap: 14px;
128
+ padding: 7px 20px;
129
+ border-bottom: 2px solid #cfc5ae;
130
+ background: #f8f1de;
131
+ color: #4b4438;
132
+ font-size: 11px;
133
+ font-weight: 700;
134
+ white-space: nowrap;
135
+ overflow-x: auto;
136
+ }
137
+ .legend-intro { color: #27231d; font-weight: 900; }
138
+ .legend-item { display: inline-flex; align-items: center; gap: 5px; }
139
+ .legend-swatch { width: 18px; height: 13px; border: 1px solid #6e6657; display: inline-block; }
140
+ .legend-local { background: var(--sapphire); box-shadow: inset 0 0 0 2px rgba(35, 84, 130, .42); }
141
+ .legend-remote { background: var(--lava); box-shadow: inset 0 0 0 2px rgba(124, 38, 47, .38); }
142
+ .legend-incoming { background: var(--incoming); }
143
+ .legend-deleted { background: var(--tombstone); }
144
+ .sheet-label {
145
+ padding: 5px 8px;
146
+ background: var(--border-default);
147
+ color: var(--bg-surface);
148
+ font-size: 11px;
149
+ font-weight: 800;
150
+ letter-spacing: 1.2px;
151
+ }
152
+ .sheet-tab { padding: 6px 13px; box-shadow: 3px 3px 0 #000; }
153
+ .sheet-tab.active {
154
+ background: var(--gold);
155
+ transform: translate(2px, 2px);
156
+ box-shadow: 1px 1px 0 #000;
157
+ }
158
+ .tab-count {
159
+ margin-left: 7px;
160
+ font-size: 11px;
161
+ color: var(--text-muted);
162
+ }
163
+ .actions { flex: 0 0 auto; margin-left: 0; display: flex; gap: 8px; align-items: center; }
164
+ .sheet-actions {
165
+ flex: 0 0 auto;
166
+ display: flex;
167
+ align-items: center;
168
+ gap: 7px;
169
+ padding: 4px 7px;
170
+ border: 2px solid #b8a66d;
171
+ background: rgba(255, 255, 255, .58);
172
+ }
173
+ .sheet-actions-label {
174
+ color: #6c5518;
175
+ font-size: 10px;
176
+ font-weight: 900;
177
+ white-space: nowrap;
178
+ }
179
+ .sheet-actions .btn { padding: 7px 11px; font-size: 12px; }
180
+ .global-stats {
181
+ flex: 0 0 auto;
182
+ display: inline-flex;
183
+ align-items: center;
184
+ gap: 7px;
185
+ padding: 5px 8px;
186
+ border-left: 2px solid #bfb5a0;
187
+ color: #332d24;
188
+ white-space: nowrap;
189
+ }
190
+ .global-stats-label { font-size: 11px; font-weight: 900; }
191
+ .global-stats-value { font-size: 16px; font-weight: 900; line-height: 1; }
192
+ .global-stats-divider { color: #8c806c; font-size: 16px; font-weight: 700; }
193
+ .btn {
194
+ padding: 8px 16px;
195
+ border: 1px solid #d8cfbd;
196
+ border-radius: 3px;
197
+ cursor: pointer;
198
+ font-size: 13px;
199
+ font-weight: 800;
200
+ font-family: inherit;
201
+ letter-spacing: .2px;
202
+ box-shadow: 2px 2px 0 var(--shadow-edge);
203
+ transition: transform 120ms ease, filter 120ms ease, box-shadow 120ms ease;
204
+ background: linear-gradient(180deg, #f6f0e2, #dcd1bc);
205
+ color: #2a261f;
206
+ }
207
+ .btn:hover { transform: translate(1px, 1px); filter: brightness(1.04); box-shadow: 1px 1px 0 var(--shadow-edge); }
208
+ .btn:active { transform: translateY(1px); filter: brightness(.96); }
209
+ .btn:focus-visible { outline: 3px solid #a2d2ff; outline-offset: 2px; }
210
+ .btn-local { background: linear-gradient(180deg, #d9ecff, #91c4f1); border-color: #b8d8f4; color: #173f63; }
211
+ .btn-remote { background: linear-gradient(180deg, #ffd1d5, #e9919a); border-color: #f2b3ba; color: #5a2027; }
212
+ .btn-undo { background: linear-gradient(180deg, #f7f2e7, #dcd2bf); border-color: #e4ddcf; color: #2d2923; }
213
+ .btn-reset { background: linear-gradient(180deg, #ffe7a5, #efc65c); border-color: #f5dfa1; color: #49360d; }
214
+ .btn-cancel { background: linear-gradient(180deg, #f5c9cc, #dfa0a6); border-color: #efc2c6; color: #4a2529; }
215
+ .btn-submit {
216
+ position: relative;
217
+ min-width: 126px;
218
+ padding: 11px 28px;
219
+ background: linear-gradient(180deg, #ffdc8a, #f4aa3e);
220
+ border: 1px solid #f5d18d;
221
+ border-bottom-color: #dbab5e;
222
+ color: #3d2608;
223
+ font-size: 14px;
224
+ text-shadow: 0 1px 0 rgba(255, 255, 255, .35);
225
+ box-shadow: 0 4px 0 #ad7626, 2px 2px 0 var(--shadow-edge);
226
+ }
227
+ .btn-submit:hover { transform: translateY(-1px); box-shadow: 0 5px 0 #ad7626, 2px 2px 0 var(--shadow-edge); }
228
+ .btn-submit:active { transform: translateY(3px); box-shadow: 0 1px 0 #ad7626; }
229
+ .btn:disabled { opacity: .38; cursor: not-allowed; transform: none; filter: none; }
230
+ .stats {
231
+ font-size: 13px;
232
+ color: var(--text-secondary);
233
+ font-weight: 600;
234
+ white-space: nowrap;
235
+ }
236
+ .table-stage {
237
+ flex: 1 1 auto;
238
+ min-width: 0;
239
+ min-height: 0;
240
+ position: relative;
241
+ }
242
+ .table-container {
243
+ width: 100%;
244
+ height: 100%;
245
+ overflow: auto;
246
+ overscroll-behavior: contain;
247
+ scrollbar-gutter: stable;
248
+ padding: 16px;
249
+ }
250
+ .confirmed-overlay {
251
+ position: absolute;
252
+ inset: 0;
253
+ z-index: 10;
254
+ display: flex;
255
+ align-items: center;
256
+ justify-content: center;
257
+ background: rgba(70, 70, 70, .58);
258
+ cursor: not-allowed;
259
+ }
260
+ .confirmed-overlay-mark {
261
+ width: 112px;
262
+ height: 112px;
263
+ border-radius: 50%;
264
+ display: flex;
265
+ align-items: center;
266
+ justify-content: center;
267
+ background: #2ca45d;
268
+ border: 6px solid #d8ffe5;
269
+ color: #fff;
270
+ font-size: 76px;
271
+ line-height: 1;
272
+ font-weight: 900;
273
+ box-shadow: 0 5px 0 #12552e, 0 0 28px rgba(0, 0, 0, .35);
274
+ }
275
+ table.diff-table {
276
+ border-collapse: collapse;
277
+ font-size: 13px;
278
+ width: auto;
279
+ border: var(--border-width) solid var(--border-default);
280
+ box-shadow: var(--shadow);
281
+ background: var(--bg-surface);
282
+ }
283
+ table.diff-table th, table.diff-table td {
284
+ border: 2px solid var(--border-default);
285
+ padding: 6px 12px;
286
+ text-align: left;
287
+ min-width: 80px;
288
+ max-width: 240px;
289
+ overflow: hidden;
290
+ text-overflow: ellipsis;
291
+ white-space: nowrap;
292
+ }
293
+ table.diff-table th {
294
+ background: var(--gold);
295
+ color: #111;
296
+ font-weight: 800;
297
+ cursor: pointer;
298
+ text-shadow: none;
299
+ }
300
+ table.diff-table th:hover { background: var(--gold-dim); color: #111; }
301
+ td.cell-local {
302
+ background: var(--sapphire);
303
+ color: #111;
304
+ cursor: pointer;
305
+ }
306
+ td.cell-remote {
307
+ background: var(--lava);
308
+ color: #111;
309
+ cursor: pointer;
310
+ }
311
+ td.cell-no-conflict { background: var(--bg-surface); color: var(--text-secondary); }
312
+ .cell-selectable { box-shadow: inset 0 0 0 2px rgba(47, 42, 34, .38); cursor: pointer !important; }
313
+ .cell-selectable:hover { filter: brightness(.92) saturate(1.12); box-shadow: inset 0 0 0 3px rgba(47, 42, 34, .58); }
314
+ .row-header { cursor: pointer; }
315
+ .row-header:hover { background: var(--emerald) !important; }
316
+ tr.luban-header th { background: #2d2d2d; color: #f2f2f2; font-weight: 700; cursor: default; font-size: 12px; }
317
+ tr.luban-header th:hover { background: #2d2d2d; color: #f2f2f2; }
318
+ .axis-added-incoming {
319
+ background: var(--incoming) !important;
320
+ color: #29401f !important;
321
+ }
322
+ .axis-added-incoming:hover { background: var(--incoming-deep) !important; }
323
+ .axis-tombstone {
324
+ background-color: var(--tombstone) !important;
325
+ background-image: repeating-linear-gradient(135deg, rgba(255,255,255,.08) 0 8px, rgba(0,0,0,.08) 8px 16px) !important;
326
+ color: #f4f1e9 !important;
327
+ cursor: not-allowed !important;
328
+ text-decoration: line-through;
329
+ }
330
+ .axis-tombstone:hover { background-color: var(--tombstone-dark) !important; }
331
+ .structure-control { min-width: 80px; padding: 4px 5px !important; text-align: center !important; background: #ece5d4 !important; }
332
+ .structure-toggle {
333
+ border: 1px solid #c6bca8;
334
+ border-radius: 3px;
335
+ padding: 3px 7px;
336
+ background: #fff8dc;
337
+ color: #332b20;
338
+ font: 700 11px/1.2 inherit;
339
+ cursor: pointer;
340
+ box-shadow: 1px 1px 0 var(--shadow-edge);
341
+ }
342
+ .structure-toggle.is-delete { background: var(--tombstone); color: #fff; border-color: var(--tombstone-dark); }
343
+ .structure-toggle:disabled { opacity: .42; cursor: not-allowed; box-shadow: none; }
344
+ .structure-badge { display: inline-block; padding: 2px 6px; border: 1px solid rgba(0,0,0,.28); font-size: 10px; font-weight: 800; }
345
+ .structure-badge.added { background: var(--incoming); color: #29401f; }
346
+ .structure-badge.local-existing { background: #eee8dc; color: #4b4438; border-color: #bdb4a4; }
347
+ .structure-badge.deleted { background: var(--tombstone); color: #fff; }
348
+ .axis-index { display: inline-block; min-width: 22px; font-weight: 900; }
349
+ .axis-index.is-removed { color: #f7f1e5; }
350
+ .axis-source { display: block; margin-top: 2px; font-size: 9px; font-weight: 700; opacity: .72; }
351
+ .sheet-tab.sheet-added { background: var(--incoming); }
352
+ .sheet-tab.sheet-deleted { background: var(--tombstone); color: #fff; text-decoration: line-through; }
353
+ .sheet-tab.sheet-structural-conflict::before { content: '◆'; margin-right: 5px; color: #a8392f; }
354
+ .sheet-confirm-checkbox {
355
+ width: 15px;
356
+ height: 15px;
357
+ margin-right: 7px;
358
+ vertical-align: -2px;
359
+ accent-color: #278b52;
360
+ cursor: pointer;
361
+ }
362
+ .sheet-confirm-checkbox:focus-visible { outline: 2px solid #278b52; outline-offset: 2px; }
363
+ .conflict-nav { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
364
+ .conflict-nav .btn { padding: 6px 10px; font-size: 11px; }
365
+ .conflict-nav-count { min-width: 48px; text-align: center; color: #4b4438; font-size: 11px; font-weight: 800; }
366
+ .cell-locked { cursor: not-allowed !important; }
367
+ .conflict-cell-flash { animation: conflict-cell-flash .55s ease-in-out 2; position: relative; z-index: 1; }
368
+ @keyframes conflict-cell-flash {
369
+ 0%, 100% { box-shadow: inset 0 0 0 2px rgba(47, 42, 34, .38); }
370
+ 35%, 70% {
371
+ background-color: #b86cff !important;
372
+ background-image: none !important;
373
+ box-shadow: inset 0 0 0 999px rgba(184, 108, 255, .96), 0 0 20px 6px rgba(147, 61, 255, .88);
374
+ }
375
+ }
376
+ .tooltip {
377
+ position: fixed;
378
+ display: none;
379
+ background: var(--bg-surface);
380
+ color: var(--text-primary);
381
+ border: var(--border-width) solid var(--border-default);
382
+ padding: 10px 14px;
383
+ font-size: 12px;
384
+ z-index: 1000;
385
+ pointer-events: none;
386
+ max-width: 520px;
387
+ box-shadow: var(--shadow);
388
+ word-break: break-word;
389
+ }
390
+ .tooltip .label { color: var(--text-muted); margin-bottom: 6px; font-weight: 600; }
391
+ .tooltip .val-base { color: #666; }
392
+ .tooltip .val-local { color: #246aa3; }
393
+ .tooltip .val-remote { color: #c0392b; }
394
+ .tooltip .val-current { color: var(--text-primary); margin-top: 5px; font-weight: 700; }
395
+ .tooltip .author { color: #777; margin-left: 18px; font-weight: 400; }
396
+ .sheet-message {
397
+ max-width: 720px;
398
+ margin: 20px;
399
+ padding: 24px;
400
+ background: var(--bg-surface);
401
+ border: var(--border-width) solid var(--border-default);
402
+ box-shadow: var(--shadow);
403
+ }
404
+ .sheet-message h2 { font-size: 17px; margin-bottom: 8px; }
405
+ .sheet-message p { color: var(--text-secondary); margin-bottom: 16px; line-height: 1.6; }
406
+ .pager { display: flex; gap: 6px; padding: 12px 0; }
407
+ .commit-modal { position: fixed; inset: 0; z-index: 200; display: flex; align-items: center; justify-content: center; }
408
+ .commit-modal.is-hidden { display: none; }
409
+ .commit-modal-backdrop { position: absolute; inset: 0; background: rgba(0, 0, 0, .55); }
410
+ .commit-modal-panel {
411
+ position: relative;
412
+ background: var(--bg-surface);
413
+ border: var(--border-width) solid var(--border-default);
414
+ box-shadow: 8px 8px 0 #000;
415
+ padding: 22px 26px;
416
+ max-width: 520px;
417
+ width: 88%;
418
+ }
419
+ .commit-modal-icon { font-size: 28px; margin-bottom: 8px; }
420
+ .commit-modal-title { font-size: 17px; font-weight: 700; margin-bottom: 8px; }
421
+ .commit-modal-body { font-size: 13px; color: var(--text-secondary); white-space: pre-wrap; word-break: break-word; margin-bottom: 10px; }
422
+ .commit-modal-steps { font-size: 12px; font-family: Consolas, monospace; background: rgba(0, 0, 0, .04); border: 1px solid #ddd; padding: 8px 10px; margin-bottom: 12px; white-space: pre-wrap; word-break: break-word; max-height: 45vh; overflow-y: auto; }
423
+ .commit-modal-steps:empty { display: none; }
424
+ .commit-modal-actions { display: flex; gap: 10px; justify-content: flex-end; }
425
+ .commit-modal.is-success .commit-modal-icon::before { content: "\2705"; }
426
+ .commit-modal.is-error .commit-modal-icon::before { content: "\274C"; }
427
+ .footer {
428
+ position: relative;
429
+ z-index: 20;
430
+ flex: 0 0 auto;
431
+ background: var(--bg-surface);
432
+ padding: 12px 20px;
433
+ display: flex;
434
+ align-items: center;
435
+ justify-content: space-between;
436
+ gap: 20px;
437
+ border-top: var(--border-width) solid var(--border-default);
438
+ color: var(--text-primary);
439
+ font-size: 13px;
440
+ }
441
+ .footer-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 12px; }
442
+ @media (max-width: 900px) {
443
+ .toolbar { flex-wrap: wrap; }
444
+ .file-tabs { order: 3; flex: 1 0 100%; width: 100%; }
445
+ .actions { width: auto; margin-left: auto; }
446
+ .sheet-toolbar { align-items: flex-start; flex-wrap: wrap; }
447
+ .sheet-scope { flex: 1 0 100%; }
448
+ .sheet-actions { margin-left: auto; }
449
+ .footer { align-items: flex-end; }
450
+ }
451
+ </style>
452
+ </head>
453
+ <body>
454
+ <div class="toolbar">
455
+ <h1>Excel 冲突解决工具</h1>
456
+ <div class="file-tabs" id="fileTabs"></div>
457
+ <div class="global-stats" id="globalConfirmationStats" aria-label="全局冲突 Sheet 确认统计">
458
+ <span class="global-stats-label">冲突 Sheet 已确认</span>
459
+ <span class="global-stats-value" id="confirmedSheetCount">0</span>
460
+ <span class="global-stats-divider" aria-hidden="true">/</span>
461
+ <span class="global-stats-value" id="totalConflictSheetCount">0</span>
462
+ </div>
463
+ </div>
464
+ <div class="sheet-toolbar">
465
+ <div class="sheet-scope" aria-label="当前 Sheet 工区">
466
+ <span class="sheet-label">SHEET</span>
467
+ <div class="sheet-tabs" id="sheetTabs"></div>
468
+ <div class="sheet-actions" id="sheetActions" aria-label="当前 Sheet 操作">
469
+ <span class="sheet-actions-label">当前 Sheet 操作</span>
470
+ <button type="button" class="btn btn-local" id="allLocalBtn">全部本地</button>
471
+ <button type="button" class="btn btn-remote" id="allRemoteBtn">全部远端</button>
472
+ <button type="button" class="btn btn-undo" id="undoBtn">撤销</button>
473
+ <button type="button" class="btn btn-reset" id="resetBtn">重置</button>
474
+ </div>
475
+ </div>
476
+ <div class="conflict-nav" id="conflictNav" aria-label="冲突定位">
477
+ <button type="button" class="btn" id="prevConflictBtn">上一个冲突</button>
478
+ <span class="conflict-nav-count" id="conflictNavCount">0 / 0</span>
479
+ <button type="button" class="btn" id="nextConflictBtn">下一个冲突</button>
480
+ </div>
481
+ <div class="sheet-choice" id="sheetChoice"></div>
482
+ </div>
483
+ <div class="diff-legend" id="diffLegend">
484
+ <span class="legend-intro">主行列号=合并后位置</span>
485
+ <span class="legend-item"><i class="legend-swatch legend-local"></i>本地值</span>
486
+ <span class="legend-item"><i class="legend-swatch legend-remote"></i>远端值</span>
487
+ <span class="legend-item"><i class="legend-swatch legend-incoming"></i>远端新增</span>
488
+ <span class="legend-item"><i class="legend-swatch legend-deleted"></i>已删除</span>
489
+ <span class="legend-item">悬停 Cell 查看 Base / 本地 / 远端</span>
490
+ </div>
491
+ <div class="table-stage" id="tableStage">
492
+ <div class="table-container" id="tableContainer"></div>
493
+ </div>
494
+ <div class="tooltip" id="tooltip"></div>
495
+ <div class="commit-modal is-hidden" id="commitModal" role="dialog" aria-modal="true" aria-labelledby="commitModalTitle">
496
+ <div class="commit-modal-backdrop"></div>
497
+ <div class="commit-modal-panel">
498
+ <div class="commit-modal-icon"></div>
499
+ <div class="commit-modal-title" id="commitModalTitle">提交中...</div>
500
+ <div class="commit-modal-body" id="commitModalBody"></div>
501
+ <div class="commit-modal-steps" id="commitModalSteps"></div>
502
+ <div class="commit-modal-actions" id="commitModalActions"></div>
503
+ </div>
504
+ </div>
505
+ <div class="footer">
506
+ <span id="footerStatus">加载中...</span>
507
+ <div class="footer-actions">
508
+ <button type="button" class="btn btn-cancel" id="cancelBtn">取消并退出</button>
509
+ <button type="button" class="btn btn-submit" id="submitBtn">提交合并</button>
510
+ </div>
511
+ </div>
512
+ <script>
513
+ let model = null;
514
+ let currentFile = 0;
515
+ let currentSheet = 0;
516
+ let currentPage = 0;
517
+ let decisions = {files: {}};
518
+ let undoStack = [];
519
+ const PAGE_SIZE = 500;
520
+
521
+ const byId = id => document.getElementById(id);
522
+ const fmtVal = value => value === null || value === undefined ? '' : String(value);
523
+ function colLabel(n) { let s = ''; while (n > 0) { n--; s = String.fromCharCode(65 + n % 26) + s; n = Math.floor(n / 26); } return s; }
524
+ function currentFileData() { return model && model.files[currentFile]; }
525
+ function currentSheetData() { const file = currentFileData(); return file && file.diff.sheets[currentSheet]; }
526
+ function fileDecision(file) {
527
+ if (!decisions.files[file.id]) decisions.files[file.id] = {sheets: {}};
528
+ return decisions.files[file.id];
529
+ }
530
+ function sheetDecision(file, sheet) {
531
+ const target = fileDecision(file).sheets;
532
+ if (!target[sheet.name]) target[sheet.name] = {cells: {}, rows: {}, columns: {}, confirmed: false};
533
+ if (typeof target[sheet.name].confirmed !== 'boolean') target[sheet.name].confirmed = false;
534
+ return target[sheet.name];
535
+ }
536
+ function cellKey(cell) { return cell.id || cell.coordinate; }
537
+ function defaultCellChoice(cell) {
538
+ if (cell.requiresChoice) return null;
539
+ if (cell.resolution === 'conflict') return 'theirs';
540
+ if (cell.resolution === 'same') return cell.oursPresent === false ? 'theirs' : 'ours';
541
+ return cell.resolution;
542
+ }
543
+ function defaultSheetChoice(sheet) { return sheet.action.startsWith('conflict_') && !sheet.requiresChoice ? 'ours' : null; }
544
+ function initializeDecisions() {
545
+ for (const file of model.files) {
546
+ const fileTarget = fileDecision(file);
547
+ if (file.macro) fileTarget.macro = file.macro.default || 'ours';
548
+ for (const sheet of file.diff.sheets) {
549
+ const target = sheetDecision(file, sheet);
550
+ target.confirmed = false;
551
+ const sheetChoice = defaultSheetChoice(sheet);
552
+ if (sheetChoice) target.sheet = sheetChoice;
553
+ if (sheet.renameStatus === 'rename_conflict') target.rename = 'ours';
554
+ if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') target.mergedCells = sheet.mergedCells.default || 'ours';
555
+ for (const row of sheet.allRows || sheet.rows || []) if (row.state === 'delete_modify') target.rows[row.id] = row.default;
556
+ for (const column of sheet.columns || []) if (column.state === 'delete_modify') target.columns[column.id] = column.default;
557
+ for (const cell of sheet.cells || []) target.cells[cell.id || cell.coordinate] = defaultCellChoice(cell);
558
+ }
559
+ }
560
+ }
561
+ function gridVal(sheet, row, col) {
562
+ const values = (sheet.contextRows || {})[String(row)];
563
+ return values ? values[col - 1] : '';
564
+ }
565
+ function enableHorizontalWheel(host) {
566
+ host.addEventListener('wheel', event => {
567
+ if (host.scrollWidth <= host.clientWidth || Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return;
568
+ event.preventDefault();
569
+ host.scrollLeft += event.deltaY;
570
+ }, {passive: false});
571
+ }
572
+
573
+ function autoTheirsNote(sep) {
574
+ const count = (model && model.summary) ? (model.summary.autoTheirsCount || 0) : 0;
575
+ return count ? `${sep}已按远端全量自动处理 ${count} 张表` : '';
576
+ }
577
+
578
+ async function init() {
579
+ const response = await fetch('/api/diff');
580
+ model = await response.json();
581
+ if (!model.files || model.files.length === 0) {
582
+ byId('footerStatus').textContent = '未发现冲突。' + autoTheirsNote('');
583
+ return;
584
+ }
585
+ initializeDecisions();
586
+ render();
587
+ }
588
+
589
+ function render() {
590
+ renderFileTabs();
591
+ renderSheetTabs();
592
+ renderSheetChoice();
593
+ renderTable();
594
+ renderConflictNavigation();
595
+ renderActionAvailability();
596
+ updateStats();
597
+ }
598
+ function renderFileTabs() {
599
+ const host = byId('fileTabs');
600
+ host.replaceChildren();
601
+ model.files.forEach((file, index) => {
602
+ const tab = document.createElement('div');
603
+ tab.className = 'file-tab' + (index === currentFile ? ' active' : '') + (file.diff.summary.changedCellCount ? ' has-conflicts' : '');
604
+ tab.textContent = file.path;
605
+ tab.onclick = () => { currentFile = index; currentSheet = 0; currentPage = 0; render(); };
606
+ host.append(tab);
607
+ });
608
+ }
609
+ function sheetDecisionCount(file, sheet) {
610
+ if (sheet.action.startsWith('conflict_')) return 1;
611
+ if (sheet.action !== 'merge') return 1;
612
+ let total = sheet.renameStatus === 'rename_conflict' ? 1 : 0;
613
+ if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') total++;
614
+ total += (sheet.allRows || sheet.rows || []).filter(axis => axis.state === 'delete_modify').length;
615
+ total += (sheet.columns || []).filter(axis => axis.state === 'delete_modify').length;
616
+ for (const cell of sheet.cells || []) {
617
+ if (!sheet.columns || !sheet.allRows || structuralCellSelectable(file, sheet, cell)) total++;
618
+ }
619
+ return total;
620
+ }
621
+ function renderSheetTabs() {
622
+ const host = byId('sheetTabs');
623
+ host.replaceChildren();
624
+ const file = currentFileData();
625
+ // 单侧修改仍可人工覆盖,与双侧冲突使用相同的审阅入口。
626
+ const visible = [];
627
+ file.diff.sheets.forEach((sheet, index) => {
628
+ if (!sheetNeedsConfirmation(sheet)) return;
629
+ visible.push({ sheet, index });
630
+ });
631
+ if (!visible.length) {
632
+ const empty = document.createElement('div');
633
+ empty.className = 'sheet-tab';
634
+ empty.textContent = '该文件没有需要处理的 Sheet';
635
+ host.append(empty);
636
+ return;
637
+ }
638
+ const current = file.diff.sheets[currentSheet];
639
+ if (!sheetNeedsConfirmation(current)) {
640
+ currentSheet = visible[0].index;
641
+ }
642
+ visible.forEach(({ sheet, index }) => {
643
+ const tab = document.createElement('div');
644
+ const added = sheet.action === 'auto_add_theirs';
645
+ const deleted = sheet.action === 'auto_delete';
646
+ const structuralConflict = sheet.action.startsWith('conflict_') || sheet.renameStatus === 'rename_conflict' || (sheet.structuralConflictCount || 0) > 0;
647
+ tab.className = 'sheet-tab' + (index === currentSheet ? ' active' : '') + (added ? ' sheet-added' : '') + (deleted ? ' sheet-deleted' : '') + (structuralConflict ? ' sheet-structural-conflict' : '');
648
+ const target = sheetDecision(file, sheet);
649
+ const confirmation = document.createElement('input');
650
+ confirmation.type = 'checkbox';
651
+ confirmation.className = 'sheet-confirm-checkbox';
652
+ confirmation.checked = target.confirmed === true;
653
+ confirmation.title = '勾选表示你已人工审阅并确认本 Sheet 的所有待处理项(含单侧改动);取消勾选可继续编辑。';
654
+ confirmation.setAttribute('aria-label', `${sheet.name}:已确认(人工审阅完成)`);
655
+ confirmation.onclick = event => event.stopPropagation();
656
+ confirmation.onchange = event => {
657
+ event.stopPropagation();
658
+ if (confirmation.checked && ((sheet.requiresChoice && !target.sheet) ||
659
+ (!target.sheet && (sheet.cells || []).some(cell => cell.requiresChoice && !target.cells[cellKey(cell)])))) {
660
+ confirmation.checked = false;
661
+ byId('footerStatus').textContent = '公式无法计算:请先明确选择这些单元格或整个 Sheet 的来源。';
662
+ return;
663
+ }
664
+ const invalid = !target.sheet && (sheet.cells || []).find(cell => (cell.errorSides || {})[target.cells[cellKey(cell)]]);
665
+ const sheetError = selectedSourceErrors(sheet, target).find(error => !validRepair(error, ((target.repairs || {})[target.sheet] || {})[error.coordinate]));
666
+ if (confirmation.checked && (invalid || sheetError)) {
667
+ confirmation.checked = false;
668
+ byId('footerStatus').textContent = '请先填写所选整表来源的合法修复值,再确认 Sheet。';
669
+ return;
670
+ }
671
+ target.confirmed = confirmation.checked;
672
+ render();
673
+ };
674
+ tab.append(confirmation, document.createTextNode(sheet.name));
675
+ const count = document.createElement('span');
676
+ count.className = 'tab-count';
677
+ count.textContent = sheetDecisionCount(file, sheet);
678
+ tab.append(count);
679
+ tab.onclick = () => { currentSheet = index; currentPage = 0; render(); };
680
+ host.append(tab);
681
+ });
682
+ }
683
+ function renderSheetChoice() {
684
+ const host = byId('sheetChoice'); host.replaceChildren();
685
+ const file = currentFileData(); const sheet = currentSheetData();
686
+ const macro = file && file.macro;
687
+ if (macro && macro.status !== 'same') {
688
+ const label = document.createElement('span'); label.className = 'macro-label'; label.textContent = '当前文件宏 · VBA/ActiveX';
689
+ host.append(label);
690
+ if (macro.status === 'conflict') {
691
+ const selected = fileDecision(file).macro || macro.default;
692
+ const local = document.createElement('button');
693
+ local.className = 'btn btn-local macro-toggle' + (selected === 'ours' ? ' is-selected' : '');
694
+ local.textContent = '本地宏'; local.onclick = () => chooseMacro(file, 'ours');
695
+ const remote = document.createElement('button');
696
+ remote.className = 'btn btn-remote macro-toggle' + (selected === 'theirs' ? ' is-selected' : '');
697
+ remote.textContent = '远端宏'; remote.onclick = () => chooseMacro(file, 'theirs');
698
+ host.append(local, remote);
699
+ } else {
700
+ const note = document.createElement('span'); note.className = 'macro-note';
701
+ note.textContent = macro.status === 'auto_theirs'
702
+ ? '仅远端变更,自动采用远端宏'
703
+ : macro.status === 'auto_ours'
704
+ ? '仅本地变更,自动采用本地宏'
705
+ : '两边宏包结构不同,安全保留本地宏';
706
+ host.append(note);
707
+ }
708
+ }
709
+ if (!sheet) return;
710
+ if (sheet.replacements && sheet.replacements.length) {
711
+ const note = document.createElement('span'); note.className = 'macro-label';
712
+ const count = new Set(sheet.replacements.map(repair => JSON.stringify([repair.recordId, repair.field]))).size;
713
+ note.textContent = sheet.replacements.some(repair => repair.manual)
714
+ ? '公式错误已按人工指定值修复,请确认整表来源。'
715
+ : `双方错误已按字段类型替换 ${count} 个值(ID、引用和未知类型保留人工处理)。`;
716
+ note.title = sheet.replacements.map(repair => `${repair.side} / ${repair.coordinate}: ${repair.formula} → ${JSON.stringify(repair.value)}`).join('\n');
717
+ host.append(note);
718
+ }
719
+ if (sheet.calculationErrors && sheet.calculationErrors.length) {
720
+ const note = document.createElement('span'); note.className = 'macro-label';
721
+ note.textContent = `有 ${sheet.calculationErrors.length} 个无法计算的值,必须选择有效来源。`;
722
+ note.title = sheet.calculationErrors.map(error => `${error.side} / ${error.sheet}!${error.coordinate}: ${error.formula} → ${error.error}`).join('\n');
723
+ host.append(note);
724
+ if (sheet.action === 'merge') {
725
+ for (const side of ['ours', 'theirs']) {
726
+ const button = document.createElement('button'); button.className = 'structure-toggle';
727
+ button.textContent = side === 'ours' ? '整表采用本地' : '整表采用远端';
728
+ button.disabled = currentSheetIsConfirmed(); button.onclick = () => chooseSheet(file, sheet, side); host.append(button);
729
+ }
730
+ if (sheetDecision(file, sheet).sheet) {
731
+ const button = document.createElement('button'); button.className = 'structure-toggle'; button.textContent = '返回单元格合并';
732
+ button.onclick = () => { delete sheetDecision(file, sheet).sheet; sheetDecision(file, sheet).confirmed = false; render(); }; host.append(button);
733
+ }
734
+ }
735
+ }
736
+ const target = sheetDecision(file, sheet);
737
+ const confirmed = sheetNeedsConfirmation(sheet) && target.confirmed;
738
+ if (sheet.renameStatus === 'rename_conflict') {
739
+ const local = document.createElement('button'); local.className = 'structure-toggle' + (target.rename === 'ours' ? '' : ' is-delete');
740
+ local.textContent = `本地名:${sheet.names.ours}`; local.disabled = confirmed; local.onclick = () => chooseRename(file, sheet, 'ours');
741
+ const remote = document.createElement('button'); remote.className = 'structure-toggle' + (target.rename === 'theirs' ? '' : ' is-delete');
742
+ remote.textContent = `远端名:${sheet.names.theirs}`; remote.disabled = confirmed; remote.onclick = () => chooseRename(file, sheet, 'theirs');
743
+ host.append(local, remote);
744
+ }
745
+ if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') {
746
+ const label = document.createElement('span'); label.className = 'macro-label'; label.textContent = '合并表头';
747
+ const local = document.createElement('button');
748
+ local.className = 'btn btn-local macro-toggle' + (target.mergedCells === 'ours' ? ' is-selected' : '');
749
+ local.textContent = '本地结构'; local.disabled = confirmed; local.onclick = () => chooseMergedCells(file, sheet, 'ours');
750
+ const remote = document.createElement('button');
751
+ remote.className = 'btn btn-remote macro-toggle' + (target.mergedCells === 'theirs' ? ' is-selected' : '');
752
+ remote.textContent = '远端结构'; remote.disabled = confirmed; remote.onclick = () => chooseMergedCells(file, sheet, 'theirs');
753
+ host.append(label, local, remote);
754
+ }
755
+ }
756
+
757
+ function appendHeaderCell(row, value, onClick, className) {
758
+ const cell = document.createElement('th');
759
+ cell.textContent = value;
760
+ if (className) cell.className = className;
761
+ if (onClick) cell.onclick = onClick;
762
+ row.append(cell);
763
+ return cell;
764
+ }
765
+ function bindTip(cell, row, col) {
766
+ cell.onmouseenter = event => showTip(event, row, col);
767
+ cell.onmousemove = event => positionTip(event);
768
+ cell.onmouseleave = hideTip;
769
+ }
770
+ function renderTable() {
771
+ const file = currentFileData();
772
+ const sheet = currentSheetData();
773
+ const host = byId('tableContainer');
774
+ host.replaceChildren();
775
+ const oldOverlay = byId('confirmedOverlay');
776
+ if (oldOverlay) oldOverlay.remove();
777
+ if (!sheet) {
778
+ renderMessage(host, '无需处理', '两侧工作簿内容一致,没有需要展示的 Sheet 差异。');
779
+ return;
780
+ }
781
+ if (sheet.action.startsWith('conflict_') || sheetDecision(file, sheet).sheet) {
782
+ renderSheetConflict(host, file, sheet);
783
+ renderConfirmedOverlay(host, file, sheet);
784
+ return;
785
+ }
786
+ if (sheet.action !== 'merge') {
787
+ const labels = {
788
+ auto_add_ours: '该 Sheet 仅存在于本地,将自动保留本地版本。',
789
+ auto_add_theirs: '该 Sheet 仅存在于远端,将自动保留远端版本。',
790
+ auto_delete: '该 Sheet 的删除只发生在一侧,另一侧未修改,将自动删除。'
791
+ };
792
+ renderMessage(host, sheet.name, labels[sheet.action] || `将自动执行:${sheet.action}`);
793
+ renderConfirmedOverlay(host, file, sheet);
794
+ return;
795
+ }
796
+ renderDiffTable(host, file, sheet);
797
+ renderConfirmedOverlay(host, file, sheet);
798
+ }
799
+ function sheetNeedsConfirmation(sheet) {
800
+ return !!sheet && (sheet.needsAttention !== false || sheet.decisionCellCount > 0 ||
801
+ (sheet.cells || []).some(cell => cellNeedsReview(cell)));
802
+ }
803
+ function cellNeedsReview(cell) {
804
+ return !!cell && !cell.replacement && cell.selectable !== false &&
805
+ ['ours', 'theirs', 'conflict'].includes(cell.resolution);
806
+ }
807
+ function renderConfirmedOverlay(host, file, sheet) {
808
+ if (!sheetNeedsConfirmation(sheet) || !sheetDecision(file, sheet).confirmed) return;
809
+ const overlay = document.createElement('div');
810
+ overlay.id = 'confirmedOverlay';
811
+ overlay.className = 'confirmed-overlay';
812
+ overlay.title = '本 Sheet 已确认;取消 Sheet 标签前的勾选后可继续编辑。';
813
+ overlay.setAttribute('aria-label', '本 Sheet 已确认,表格交互已锁定');
814
+ const mark = document.createElement('div');
815
+ mark.className = 'confirmed-overlay-mark';
816
+ mark.textContent = '✓';
817
+ overlay.append(mark);
818
+ byId('tableStage').append(overlay);
819
+ }
820
+ function currentSheetIsConfirmed() {
821
+ const file = currentFileData(); const sheet = currentSheetData();
822
+ return !!file && sheetNeedsConfirmation(sheet) && sheetDecision(file, sheet).confirmed;
823
+ }
824
+ function renderActionAvailability() {
825
+ const confirmed = currentSheetIsConfirmed();
826
+ byId('allLocalBtn').disabled = confirmed;
827
+ byId('allRemoteBtn').disabled = confirmed;
828
+ const file = currentFileData(); const sheet = currentSheetData();
829
+ const scope = file && sheet ? `当前 Sheet:${file.path} / ${sheet.name}` : '当前 Sheet';
830
+ const message = confirmed ? `${scope} 已确认;取消 Sheet 标签前的勾选后可继续编辑。` : `${scope} 的批量操作`;
831
+ byId('allLocalBtn').title = `${message}:将可处理项全部采用本地。`;
832
+ byId('allRemoteBtn').title = `${message}:将可处理项全部采用远端。`;
833
+ byId('undoBtn').title = `${scope}:撤销最近一次选择,不影响其它 Sheet 或文件级宏。`;
834
+ byId('resetBtn').title = `${scope}:恢复本 Sheet 的默认决策,不影响其它 Sheet 或文件级宏。`;
835
+ }
836
+ function navigableConflictCells(file, sheet) {
837
+ if (!sheet || !sheetNeedsConfirmation(sheet)) return [];
838
+ if (sheet.columns && sheet.allRows) {
839
+ return (sheet.cells || []).filter(cell => cellNeedsReview(cell) && structuralCellSelectable(file, sheet, cell));
840
+ }
841
+ return (sheet.cells || []).filter(cell => cellNeedsReview(cell));
842
+ }
843
+ function conflictCellKey(cell) { return cell && (cell.id || cell.coordinate); }
844
+ function renderConflictNavigation() {
845
+ const file = currentFileData(); const sheet = currentSheetData();
846
+ const cells = navigableConflictCells(file, sheet);
847
+ const count = byId('conflictNavCount');
848
+ const previous = byId('prevConflictBtn'); const next = byId('nextConflictBtn');
849
+ if (!count || !previous || !next) return;
850
+ const currentId = sheet && sheetDecision(file, sheet).lastNavigatedConflict;
851
+ const currentIndex = cells.findIndex(cell => conflictCellKey(cell) === currentId);
852
+ count.textContent = cells.length ? `${currentIndex < 0 ? 0 : currentIndex + 1} / ${cells.length}` : '0 / 0';
853
+ previous.disabled = cells.length === 0;
854
+ next.disabled = cells.length === 0;
855
+ previous.title = cells.length ? '定位到当前 Sheet 的上一个待审阅改动(含单侧改动,循环)' : '当前 Sheet 没有可定位的改动';
856
+ next.title = cells.length ? '定位到当前 Sheet 的下一个待审阅改动(含单侧改动,循环)' : '当前 Sheet 没有可定位的改动';
857
+ }
858
+ function markConflictCell(cellElement) {
859
+ if (!cellElement) return;
860
+ cellElement.classList.remove('conflict-cell-flash');
861
+ // Force a reflow so repeated navigation to the same cell restarts the flash.
862
+ void cellElement.offsetWidth;
863
+ cellElement.classList.add('conflict-cell-flash');
864
+ window.setTimeout(() => cellElement.classList.remove('conflict-cell-flash'), 1300);
865
+ }
866
+ function locateConflictCell(direction) {
867
+ const file = currentFileData(); const sheet = currentSheetData();
868
+ const cells = navigableConflictCells(file, sheet);
869
+ if (!cells.length) return;
870
+ const state = sheetDecision(file, sheet);
871
+ const currentId = state.lastNavigatedConflict;
872
+ let index = cells.findIndex(cell => conflictCellKey(cell) === currentId);
873
+ index = index < 0 ? (direction > 0 ? 0 : cells.length - 1) : (index + direction + cells.length) % cells.length;
874
+ const target = cells[index];
875
+ state.lastNavigatedConflict = conflictCellKey(target);
876
+ const rowNumber = target.row;
877
+ if (!(sheet.columns && sheet.allRows) && rowNumber !== undefined) {
878
+ const rows = [...new Set((sheet.cells || []).map(cell => cell.row))].sort((a, b) => a - b);
879
+ currentPage = Math.floor(Math.max(0, rows.indexOf(rowNumber)) / PAGE_SIZE);
880
+ } else if (sheet.columns && sheet.allRows) {
881
+ const rows = sheet.rows || [];
882
+ const rowIndex = rows.findIndex(row => row.id === target.rowId);
883
+ currentPage = Math.floor(Math.max(0, rowIndex) / PAGE_SIZE);
884
+ }
885
+ renderTable();
886
+ renderConflictNavigation();
887
+ requestAnimationFrame(() => {
888
+ const element = [...byId('tableContainer').querySelectorAll('[data-conflict-id]')]
889
+ .find(item => item.dataset.conflictId === conflictCellKey(target));
890
+ if (!element) return;
891
+ const container = byId('tableContainer');
892
+ container.scrollTop = Math.max(0, element.offsetTop - container.clientHeight / 2);
893
+ container.scrollLeft = Math.max(0, element.offsetLeft - container.clientWidth / 2);
894
+ element.scrollIntoView({block: 'nearest', inline: 'nearest'});
895
+ markConflictCell(element);
896
+ });
897
+ }
898
+ function renderMessage(host, title, message) {
899
+ const box = document.createElement('div');
900
+ box.className = 'sheet-message';
901
+ const heading = document.createElement('h2'); heading.textContent = title;
902
+ const body = document.createElement('p'); body.textContent = message;
903
+ box.append(heading, body); host.append(box);
904
+ }
905
+ function renderSheetConflict(host, file, sheet) {
906
+ const box = document.createElement('div');
907
+ box.className = 'sheet-message';
908
+ const heading = document.createElement('h2'); heading.textContent = `${sheet.name}:删除 / 修改冲突`;
909
+ const body = document.createElement('p');
910
+ body.textContent = '一侧删除了整个 Sheet,另一侧继续修改。选择某一侧后,将按该侧实际状态保留或删除 Sheet。';
911
+ if (sheet.action === 'conflict_calculation_errors' || (sheet.calculationErrors || []).length) {
912
+ heading.textContent = `${sheet.name}:公式错误`;
913
+ body.textContent = '存在无法计算的值,且无法可靠对应行列或确认记录身份。请明确选择整个 Sheet 的有效本地或远端版本。';
914
+ if (!(sheet.calculationErrors || []).length) {
915
+ heading.textContent = `${sheet.name}:修复后整表选择`;
916
+ body.textContent = '公式错误已修复。选择整表来源后,勾选 Sheet 标签前的确认框完成审阅。';
917
+ }
918
+ }
919
+ const target = sheetDecision(file, sheet);
920
+ const names = sheet.names || {};
921
+ const local = document.createElement('button');
922
+ const localLabel = names.ours ? '保留 Sheet(本地)' : '删除 Sheet(本地)';
923
+ local.className = 'btn btn-local'; local.textContent = target.sheet === 'ours' ? `✓ ${localLabel}` : localLabel;
924
+ local.onclick = () => chooseSheet(file, sheet, 'ours');
925
+ const remote = document.createElement('button');
926
+ const remoteLabel = names.theirs ? '保留 Sheet(远端)' : '删除 Sheet(远端)';
927
+ remote.className = 'btn btn-remote'; remote.textContent = target.sheet === 'theirs' ? `✓ ${remoteLabel}` : remoteLabel;
928
+ remote.onclick = () => chooseSheet(file, sheet, 'theirs');
929
+ box.append(heading, body, local, document.createTextNode(' '), remote); host.append(box);
930
+ const errors = selectedSourceErrors(sheet, target);
931
+ if (errors.length) {
932
+ const label = document.createElement('p'); label.textContent = '修复所选来源的错误值后,再确认整张 Sheet。ID / 引用字段需人工核对。'; box.append(label);
933
+ const values = ((target.repairs || {})[target.sheet] || {});
934
+ for (const error of errors) {
935
+ const row = document.createElement('div'); row.style.margin = '12px 0';
936
+ const title = document.createElement('label'); title.textContent = `${error.coordinate} · ${error.field || '字段未识别'} · ${error.type || '未知类型'}:`;
937
+ title.title = `${error.formula} → ${error.error}`;
938
+ const input = document.createElement(error.type === 'bool' ? 'select' : 'input');
939
+ input.setAttribute('aria-label', `${error.coordinate} 修复值`); input.disabled = currentSheetIsConfirmed();
940
+ if (error.type === 'bool') {
941
+ for (const text of ['', 'true', 'false']) {const option = document.createElement('option'); option.value = text; option.textContent = text || '请选择'; input.append(option);}
942
+ } else {input.type = 'text'; input.placeholder = error.type === 'string' ? '请输入文本(可为空串)' : '请输入合法数值';}
943
+ if (Object.hasOwn(values, error.coordinate)) input.value = String(values[error.coordinate]);
944
+ input.onchange = () => {
945
+ target.repairs ||= {}; target.repairs[target.sheet] ||= {};
946
+ const value = error.type === 'string' ? input.value : error.type === 'bool' ? (input.value ? input.value === 'true' : undefined) : (input.value.trim() ? Number(input.value) : undefined);
947
+ if (validRepair(error, value)) target.repairs[target.sheet][error.coordinate] = value;
948
+ else delete target.repairs[target.sheet][error.coordinate];
949
+ target.confirmed = false; renderSheetTabs(); updateStats();
950
+ };
951
+ title.append(input); row.append(title);
952
+ if (Object.hasOwn(error, 'defaultValue')) {
953
+ const button = document.createElement('button'); button.className = 'btn'; button.textContent = `使用类型默认值 ${JSON.stringify(error.defaultValue)}`;
954
+ button.onclick = () => {target.repairs ||= {}; target.repairs[target.sheet] ||= {}; target.repairs[target.sheet][error.coordinate] = error.defaultValue; target.confirmed = false; render();}; row.append(button);
955
+ }
956
+ box.append(row);
957
+ }
958
+ }
959
+ }
960
+ function selectedSourceErrors(sheet, target) {return (sheet.calculationErrors || []).filter(error => error.side === target.sheet);}
961
+ function validRepair(error, value) {
962
+ if (error.type === 'string') return typeof value === 'string';
963
+ if (error.type === 'bool') return typeof value === 'boolean';
964
+ if (['float', 'double', 'decimal'].includes(error.type)) return typeof value === 'number' && Number.isFinite(value);
965
+ const kind = error.type || '';
966
+ if (!kind) return typeof value === 'number' && Number.isFinite(value);
967
+ if (!/^(?:u?int(?:8|16|32|64)?|s?byte|u?short|u?long)$/.test(kind) || !Number.isSafeInteger(value)) return false;
968
+ const sizes = {byte:8,sbyte:8,short:16,ushort:16,long:64,ulong:64};
969
+ const bits = sizes[kind] || Number((kind.match(/\d+$/) || ['32'])[0]);
970
+ const unsigned = kind.startsWith('u') || kind === 'byte';
971
+ return value >= (unsigned ? 0 : -(2 ** (bits - 1))) && value <= 2 ** (unsigned ? bits : bits - 1) - 1;
972
+ }
973
+ function axisChoice(file, sheet, kind, axis) {
974
+ if (axis.state !== 'delete_modify') return axis.default;
975
+ return sheetDecision(file, sheet)[kind][axis.id] || axis.default;
976
+ }
977
+ function axisKept(file, sheet, kind, axis) { return axisChoice(file, sheet, kind, axis) !== 'delete'; }
978
+ function axisClass(file, sheet, kind, axis) {
979
+ if (axis.state === 'deleted' || !axisKept(file, sheet, kind, axis)) return ' axis-tombstone';
980
+ if (axis.state === 'added' && axis.incoming) return ' axis-added-incoming';
981
+ return '';
982
+ }
983
+ function axisSource(axis, kind) {
984
+ if (kind === 'rows') return `Base ${axis.baseRow ?? '—'} · 本地 ${axis.oursRow ?? '—'} · 远端 ${axis.theirsRow ?? '—'}`;
985
+ return `Base ${axis.baseColumn ?? '—'} · 本地 ${axis.oursColumn ?? '—'} · 远端 ${axis.theirsColumn ?? '—'}`;
986
+ }
987
+ function structuralOutputMaps(file, sheet) {
988
+ const headerCount = (sheet.headerRows || []).length;
989
+ const rows = new Map(); const columns = new Map(); let rowIndex = headerCount; let columnIndex = 0;
990
+ for (const row of sheet.allRows || []) if (axisKept(file, sheet, 'rows', row)) rows.set(row.id, ++rowIndex);
991
+ for (const column of sheet.columns || []) if (axisKept(file, sheet, 'columns', column)) columns.set(column.id, colLabel(++columnIndex));
992
+ return {rows, columns};
993
+ }
994
+ function structuralCellSelectable(file, sheet, cell) {
995
+ if (cell.replacement) return false;
996
+ if (!cell || !cell.changed || cell.selectable === false) return false;
997
+ const row = (sheet.allRows || []).find(item => item.id === cell.rowId);
998
+ const column = (sheet.columns || []).find(item => item.id === cell.colId);
999
+ return !!row && !!column && !row.locked && !column.locked
1000
+ && axisKept(file, sheet, 'rows', row) && axisKept(file, sheet, 'columns', column);
1001
+ }
1002
+ function defaultDisplayChoice(cell) {
1003
+ const choice = defaultCellChoice(cell);
1004
+ if (choice === 'same') return cell.oursPresent ? 'ours' : 'theirs';
1005
+ return choice;
1006
+ }
1007
+ function structuralCellValue(target, cell) {
1008
+ const choice = target.cells[cell.id] || defaultDisplayChoice(cell);
1009
+ if (choice === 'ours' && cell.oursPresent) return cell.ours;
1010
+ if (choice === 'theirs' && cell.theirsPresent) return cell.theirs;
1011
+ if (cell.oursPresent) return cell.ours;
1012
+ if (cell.theirsPresent) return cell.theirs;
1013
+ return cell.base;
1014
+ }
1015
+ function appendStructureControl(row, file, sheet, kind, axis) {
1016
+ const cell = document.createElement('th'); cell.className = 'structure-control' + axisClass(file, sheet, kind, axis);
1017
+ cell.title = axisSource(axis, kind);
1018
+ if (axis.state === 'delete_modify') {
1019
+ const button = document.createElement('button'); const kept = axisKept(file, sheet, kind, axis);
1020
+ button.className = 'structure-toggle' + (kept ? '' : ' is-delete');
1021
+ button.textContent = kept ? '已保留' : '已删除'; button.onclick = event => { event.stopPropagation(); toggleAxis(file, sheet, kind, axis); };
1022
+ cell.append(button);
1023
+ } else if (axis.state === 'added') {
1024
+ const badge = document.createElement('span'); badge.className = `structure-badge ${axis.incoming ? 'added' : 'local-existing'}`;
1025
+ const source = kind === 'rows' ? (axis.theirsRow ?? axis.oursRow) : (axis.theirsColumn ?? axis.oursColumn);
1026
+ badge.textContent = `${axis.incoming ? '远端新增' : '本地已有'} · ${source}`; cell.append(badge);
1027
+ } else if (axis.state === 'deleted') {
1028
+ const badge = document.createElement('span'); badge.className = 'structure-badge deleted';
1029
+ badge.textContent = `已删除 · ${kind === 'rows' ? axis.baseRow : axis.baseColumn}`; cell.append(badge);
1030
+ }
1031
+ row.append(cell); return cell;
1032
+ }
1033
+ function renderDiffTable(host, file, sheet) {
1034
+ if (sheet.columns && sheet.allRows) return renderStructuralTable(host, file, sheet);
1035
+ return renderLegacyDiffTable(host, file, sheet);
1036
+ }
1037
+ function buildHeaderMergeMap(sheet, selection) {
1038
+ // 构建 header cell 的合并映射:key = "rowIndex|colIndex" -> {isOrigin, colspan}
1039
+ const mc = sheet.mergedCells || {};
1040
+ let regions;
1041
+ if (mc.status === 'conflict') {
1042
+ const choice = (selection && selection.mergedCells) || mc.default || 'ours';
1043
+ regions = mc[choice] || mc.ours || [];
1044
+ } else {
1045
+ regions = mc.resolved || [];
1046
+ }
1047
+ const columns = sheet.columns || [];
1048
+ const headerRows = sheet.headerRows || [];
1049
+ const headerRowNumbers = headerRows.map(r => r.row);
1050
+ const map = {};
1051
+ for (const region of regions) {
1052
+ const rowIdxs = (region.rows || []).map(r => r.startsWith('header:') ? parseInt(r.slice(7)) : null).filter(r => r !== null);
1053
+ const colIds = region.columns || [];
1054
+ if (rowIdxs.length < 1 || colIds.length < 2) continue;
1055
+ const colIdxs = colIds.map(cid => columns.findIndex(c => c.id === cid)).filter(i => i >= 0);
1056
+ if (colIdxs.length < 2) continue;
1057
+ const minCol = Math.min(...colIdxs);
1058
+ const maxCol = Math.max(...colIdxs);
1059
+ for (const rowNum of rowIdxs) {
1060
+ const hrIdx = headerRowNumbers.indexOf(rowNum);
1061
+ if (hrIdx < 0) continue;
1062
+ map[`${rowNum}|${minCol}`] = {isOrigin: true, colspan: maxCol - minCol + 1};
1063
+ for (let c = minCol + 1; c <= maxCol; c++) {
1064
+ map[`${rowNum}|${c}`] = {isOrigin: false};
1065
+ }
1066
+ }
1067
+ }
1068
+ return map;
1069
+ }
1070
+ function renderStructuralTable(host, file, sheet) {
1071
+ const columns = sheet.columns || []; const rows = sheet.rows || [];
1072
+ if (!rows.length && !columns.length) { renderMessage(host, sheet.name, '该 Sheet 没有表内数据差异。'); return; }
1073
+ const target = sheetDecision(file, sheet);
1074
+ const output = structuralOutputMaps(file, sheet);
1075
+ const grid = new Map((sheet.gridCells || []).map(cell => [`${cell.rowId}|${cell.colId}`, cell]));
1076
+ const table = document.createElement('table'); table.className = 'diff-table';
1077
+ const head = document.createElement('thead');
1078
+ const controls = document.createElement('tr'); appendHeaderCell(controls, '结构', null, 'structure-control');
1079
+ for (const column of columns) appendStructureControl(controls, file, sheet, 'columns', column);
1080
+ head.append(controls);
1081
+ const letters = document.createElement('tr'); appendHeaderCell(letters, '行');
1082
+ for (const column of columns) {
1083
+ const header = appendHeaderCell(letters, output.columns.get(column.id) || '×', () => bulkStructuralColumn(column.id));
1084
+ header.className += axisClass(file, sheet, 'columns', column);
1085
+ header.title = `${axisSource(column, 'columns')} · 合并后 ${output.columns.get(column.id) || '删除'}`;
1086
+ }
1087
+ head.append(letters);
1088
+ const headerMergeMap = buildHeaderMergeMap(sheet, sheetDecision(file, sheet));
1089
+ for (const headerRow of sheet.headerRows || []) {
1090
+ const row = document.createElement('tr'); row.className = 'luban-header'; appendHeaderCell(row, String(headerRow.row));
1091
+ headerRow.cells.forEach((value, index) => {
1092
+ const merge = headerMergeMap[`${headerRow.row}|${index}`];
1093
+ if (merge && !merge.isOrigin) return; // 被合并的格子跳过
1094
+ const cell = appendHeaderCell(row, fmtVal(value));
1095
+ cell.className += axisClass(file, sheet, 'columns', columns[index]);
1096
+ if (merge && merge.colspan > 1) cell.colSpan = merge.colspan;
1097
+ });
1098
+ head.append(row);
1099
+ }
1100
+ table.append(head);
1101
+ const body = document.createElement('tbody');
1102
+ const start = currentPage * PAGE_SIZE; const end = Math.min(rows.length, start + PAGE_SIZE);
1103
+ for (let index = start; index < end; index++) {
1104
+ const axisRow = rows[index]; const row = document.createElement('tr');
1105
+ const rowHeader = document.createElement('th'); rowHeader.className = 'row-header' + axisClass(file, sheet, 'rows', axisRow);
1106
+ rowHeader.title = `${axisSource(axisRow, 'rows')} · 合并后 ${output.rows.get(axisRow.id) || '删除'}`;
1107
+ const outputIndex = document.createElement('span'); outputIndex.className = 'axis-index' + (output.rows.has(axisRow.id) ? '' : ' is-removed');
1108
+ outputIndex.textContent = output.rows.has(axisRow.id) ? String(output.rows.get(axisRow.id)) : '×'; rowHeader.append(outputIndex);
1109
+ if (axisRow.state === 'delete_modify') {
1110
+ const button = document.createElement('button'); const kept = axisKept(file, sheet, 'rows', axisRow);
1111
+ button.className = 'structure-toggle' + (kept ? '' : ' is-delete'); button.textContent = kept ? '已保留' : '已删除';
1112
+ button.onclick = event => { event.stopPropagation(); toggleAxis(file, sheet, 'rows', axisRow); }; rowHeader.append(button);
1113
+ } else {
1114
+ if (axisRow.state === 'added' || axisRow.state === 'deleted') {
1115
+ const badge = document.createElement('span'); badge.className = `structure-badge ${axisRow.state}`;
1116
+ badge.textContent = axisRow.state === 'added' ? (axisRow.incoming ? '远端新增' : '本地已有') : '已删除'; rowHeader.append(document.createTextNode(' '), badge);
1117
+ }
1118
+ }
1119
+ const source = document.createElement('span'); source.className = 'axis-source'; source.textContent = axisSource(axisRow, 'rows'); rowHeader.append(source);
1120
+ if (axisKept(file, sheet, 'rows', axisRow) && !axisRow.locked) rowHeader.onclick = () => bulkStructuralRow(axisRow.id);
1121
+ row.append(rowHeader);
1122
+ for (const column of columns) {
1123
+ const cellData = grid.get(`${axisRow.id}|${column.id}`); const cell = document.createElement('td');
1124
+ const kept = axisKept(file, sheet, 'rows', axisRow) && axisKept(file, sheet, 'columns', column);
1125
+ const structurallyLocked = !kept || axisRow.locked || column.locked;
1126
+ if (!kept || axisRow.state === 'deleted' || column.state === 'deleted') cell.className = 'axis-tombstone cell-locked';
1127
+ else if ((axisRow.state === 'added' && axisRow.incoming) || (column.state === 'added' && column.incoming)) cell.className = 'axis-added-incoming cell-locked';
1128
+ else if (axisRow.state === 'added' || column.state === 'added') cell.className = 'cell-no-conflict cell-locked';
1129
+ else if (cellData && cellData.changed) {
1130
+ const choice = target.cells[cellData.id] || defaultDisplayChoice(cellData);
1131
+ const selectable = structuralCellSelectable(file, sheet, cellData);
1132
+ cell.className = (choice === 'ours' ? 'cell-local' : 'cell-remote') + (selectable ? ' cell-selectable' : ' cell-locked');
1133
+ } else cell.className = 'cell-no-conflict' + (structurallyLocked ? ' cell-locked' : '');
1134
+ if (cellData) {
1135
+ cell.textContent = fmtVal(structuralCellValue(target, cellData));
1136
+ if (cellData.requiresChoice && !target.cells[cellData.id]) {
1137
+ cell.textContent = '待选择';
1138
+ cell.className = 'cell-no-conflict cell-selectable';
1139
+ }
1140
+ if (structuralCellSelectable(file, sheet, cellData)) {
1141
+ cell.onclick = () => cycleCell(file, sheet, cellData);
1142
+ if (cellNeedsReview(cellData)) cell.dataset.conflictId = cellData.id;
1143
+ }
1144
+ bindStructuralTip(cell, file, sheet, axisRow, column, cellData);
1145
+ }
1146
+ row.append(cell);
1147
+ }
1148
+ body.append(row);
1149
+ }
1150
+ table.append(body); host.append(table); if (rows.length > PAGE_SIZE) renderPager(host, rows.length);
1151
+ }
1152
+ function renderLegacyDiffTable(host, file, sheet) {
1153
+ const changedCells = sheet.cells || [];
1154
+ if (!changedCells.length) {
1155
+ renderMessage(host, sheet.name, '该 Sheet 没有单元格差异。');
1156
+ return;
1157
+ }
1158
+ const maxCol = sheet.maxCol || 1;
1159
+ const changedMap = new Map(changedCells.map(cell => [`${cell.row},${cell.col}`, cell]));
1160
+ const changedRows = [...new Set(changedCells.map(cell => cell.row))].sort((a, b) => a - b);
1161
+ const a1 = gridVal(sheet, 1, 1);
1162
+ const isVertical = typeof a1 === 'string' && a1.startsWith('##column##var');
1163
+ const headerRows = [];
1164
+ if (!isVertical) {
1165
+ for (let row = 1; row <= 20; row++) {
1166
+ const value = gridVal(sheet, row, 1);
1167
+ if (typeof value === 'string' && value.startsWith('##')) headerRows.push(row);
1168
+ else if (headerRows.length) break;
1169
+ }
1170
+ }
1171
+
1172
+ const table = document.createElement('table'); table.className = 'diff-table';
1173
+ const head = document.createElement('thead');
1174
+ const letters = document.createElement('tr'); appendHeaderCell(letters, '行');
1175
+ for (let col = 1; col <= maxCol; col++) appendHeaderCell(letters, colLabel(col), () => bulkCol(col));
1176
+ head.append(letters);
1177
+ if (isVertical) {
1178
+ const meanings = {1: '字段名 ##var', 2: '类型 ##type', 3: '注释'};
1179
+ const row = document.createElement('tr'); row.className = 'luban-header'; appendHeaderCell(row, '列义');
1180
+ for (let col = 1; col <= maxCol; col++) appendHeaderCell(row, meanings[col] || '');
1181
+ head.append(row);
1182
+ } else {
1183
+ for (const headerRow of headerRows) {
1184
+ const row = document.createElement('tr'); row.className = 'luban-header'; appendHeaderCell(row, String(headerRow));
1185
+ for (let col = 1; col <= maxCol; col++) {
1186
+ const cell = appendHeaderCell(row, fmtVal(gridVal(sheet, headerRow, col)));
1187
+ bindTip(cell, headerRow, col);
1188
+ }
1189
+ head.append(row);
1190
+ }
1191
+ }
1192
+ table.append(head);
1193
+
1194
+ const body = document.createElement('tbody');
1195
+ const start = currentPage * PAGE_SIZE;
1196
+ const end = Math.min(changedRows.length, start + PAGE_SIZE);
1197
+ const target = sheetDecision(file, sheet);
1198
+ for (let index = start; index < end; index++) {
1199
+ const rowNumber = changedRows[index];
1200
+ const row = document.createElement('tr');
1201
+ appendHeaderCell(row, String(rowNumber), () => bulkRow(rowNumber), 'row-header');
1202
+ for (let col = 1; col <= maxCol; col++) {
1203
+ const key = `${rowNumber},${col}`;
1204
+ const changed = changedMap.get(key);
1205
+ const cell = document.createElement('td');
1206
+ if (changed) {
1207
+ const choice = target.cells[changed.coordinate] || defaultCellChoice(changed);
1208
+ cell.className = choice === 'ours' ? 'cell-local' : 'cell-remote';
1209
+ cell.textContent = fmtVal(choice === 'ours' ? changed.ours : changed.theirs);
1210
+ cell.onclick = () => cycleCell(file, sheet, changed);
1211
+ if (cellNeedsReview(changed)) cell.dataset.conflictId = changed.id || changed.coordinate;
1212
+ } else {
1213
+ cell.className = 'cell-no-conflict';
1214
+ cell.textContent = fmtVal(gridVal(sheet, rowNumber, col));
1215
+ }
1216
+ bindTip(cell, rowNumber, col);
1217
+ row.append(cell);
1218
+ }
1219
+ body.append(row);
1220
+ }
1221
+ table.append(body); host.append(table);
1222
+ if (changedRows.length > PAGE_SIZE) renderPager(host, changedRows.length);
1223
+ }
1224
+ function renderPager(host, totalRows) {
1225
+ const pages = Math.ceil(totalRows / PAGE_SIZE);
1226
+ const pager = document.createElement('div'); pager.className = 'pager';
1227
+ for (let page = 0; page < pages; page++) {
1228
+ const button = document.createElement('button');
1229
+ button.className = 'btn' + (page === currentPage ? ' btn-local' : '');
1230
+ button.textContent = String(page + 1);
1231
+ button.onclick = () => { currentPage = page; renderTable(); };
1232
+ pager.append(button);
1233
+ }
1234
+ host.append(pager);
1235
+ }
1236
+
1237
+ function changedCellAt(sheet, row, col) { return (sheet.cells || []).find(cell => cell.row === row && cell.col === col); }
1238
+ function bindStructuralTip(cell, file, sheet, row, column, data) {
1239
+ cell.onmouseenter = event => showStructuralTip(event, file, sheet, row, column, data);
1240
+ cell.onmousemove = event => positionTip(event); cell.onmouseleave = hideTip;
1241
+ }
1242
+ function addTipLine(host, className, label, value, author, date) {
1243
+ const line = document.createElement('div'); line.className = className;
1244
+ line.append(document.createTextNode(`${label}: ${fmtVal(value)}`));
1245
+ const metaParts = [];
1246
+ if (author) metaParts.push(`作者: ${author}`);
1247
+ if (date) metaParts.push(date);
1248
+ if (metaParts.length) { const span = document.createElement('span'); span.className = 'author'; span.textContent = metaParts.join(' '); line.append(span); }
1249
+ host.append(line);
1250
+ }
1251
+ function showTip(event, row, col) {
1252
+ const file = currentFileData(); const sheet = currentSheetData(); const changed = changedCellAt(sheet, row, col);
1253
+ const tip = byId('tooltip'); tip.replaceChildren();
1254
+ const label = document.createElement('div'); label.className = 'label';
1255
+ label.textContent = `${file.path} / ${sheet.name} / 第 ${row} 行, ${colLabel(col)} 列`;
1256
+ tip.append(label);
1257
+ if (changed) {
1258
+ const choice = sheetDecision(file, sheet).cells[changed.coordinate] || defaultCellChoice(changed);
1259
+ addTipLine(tip, 'val-base', '基线', changed.base, '');
1260
+ addTipLine(tip, 'val-local', '本地', changed.ours, file.oursAuthor, file.oursDate);
1261
+ addTipLine(tip, 'val-remote', '远端', changed.theirs, file.theirsAuthor, file.theirsDate);
1262
+ addTipLine(tip, 'val-current', '当前选择', choice === 'ours' ? '本地' : '远端', '');
1263
+ if (changed.resolution !== 'conflict') addTipLine(tip, 'label', '三方建议', changed.resolution === 'ours' ? '自动采用本地' : '自动采用远端', '');
1264
+ } else {
1265
+ addTipLine(tip, 'val-current', '值', gridVal(sheet, row, col), '');
1266
+ }
1267
+ tip.style.display = 'block'; positionTip(event);
1268
+ }
1269
+ function showStructuralTip(event, file, sheet, row, column, cell) {
1270
+ const tip = byId('tooltip'); tip.replaceChildren();
1271
+ const label = document.createElement('div'); label.className = 'label';
1272
+ label.textContent = `${file.path} / ${sheet.name} / ${row.id} / ${column.id}`; tip.append(label);
1273
+ addTipLine(tip, 'val-base', '基线', cell.base, '');
1274
+ if (cell.calculationErrors) {
1275
+ for (const [side, error] of Object.entries(cell.calculationErrors)) {
1276
+ addTipLine(tip, 'label', `${side === 'base' ? '历史' : side === 'ours' ? '本地' : '远端'}值未知`, `${error.coordinate}: ${error.formula} → ${error.error}`, '');
1277
+ }
1278
+ if (!sheetDecision(file, sheet).cells[cellKey(cell)]) addTipLine(tip, 'label', '待选择', '请点击明确选择本地或远端;当前展示不代表已选择。', '');
1279
+ }
1280
+ if (cell.replacement) {
1281
+ for (const [side, repair] of Object.entries(cell.replacement)) {
1282
+ addTipLine(tip, 'label', side === 'ours' ? '本地原错误' : '远端原错误', `${repair.coordinate}: ${repair.formula} → ${repair.error}`, '');
1283
+ }
1284
+ addTipLine(tip, 'label', '按类型替换', JSON.stringify(cell.replacement.ours.value), '');
1285
+ }
1286
+ addTipLine(tip, 'val-local', '本地', cell.ours, file.oursAuthor, file.oursDate);
1287
+ addTipLine(tip, 'val-remote', '远端', cell.theirs, file.theirsAuthor, file.theirsDate);
1288
+ const choice = sheetDecision(file, sheet).cells[cell.id] || defaultDisplayChoice(cell);
1289
+ addTipLine(tip, 'val-current', '当前选择', choice ? (choice === 'ours' ? '本地' : '远端') : '待选择', '');
1290
+ addTipLine(tip, 'label', '行来源', axisSource(row, 'rows'), '');
1291
+ addTipLine(tip, 'label', '列来源', axisSource(column, 'columns'), '');
1292
+ if (row.state !== 'common') addTipLine(tip, 'label', '行状态', row.status, '');
1293
+ if (column.state !== 'common') addTipLine(tip, 'label', '列状态', column.status, '');
1294
+ addTipLine(tip, 'label', '交互', structuralCellSelectable(file, sheet, cell) ? '可点击切换版本' : '结构已锁定', '');
1295
+ tip.style.display = 'block'; positionTip(event);
1296
+ }
1297
+ function positionTip(event) {
1298
+ const tip = byId('tooltip');
1299
+ const left = Math.min(event.clientX + 12, window.innerWidth - tip.offsetWidth - 12);
1300
+ const top = Math.min(event.clientY + 12, window.innerHeight - tip.offsetHeight - 12);
1301
+ tip.style.left = `${Math.max(8, left)}px`; tip.style.top = `${Math.max(8, top)}px`;
1302
+ }
1303
+ function hideTip() { byId('tooltip').style.display = 'none'; }
1304
+
1305
+ function pushCellUndo(file, sheet, cell) {
1306
+ const target = sheetDecision(file, sheet); const key = cellKey(cell); const previous = target.cells[key];
1307
+ undoStack.push({kind: 'cell', fileId: file.id, sheet: sheet.name, key, previous});
1308
+ }
1309
+ function cycleCell(file, sheet, cell) {
1310
+ const target = sheetDecision(file, sheet); pushCellUndo(file, sheet, cell);
1311
+ const key = cellKey(cell);
1312
+ target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1313
+ renderTable(); renderConflictNavigation(); updateStats();
1314
+ }
1315
+ function chooseSheet(file, sheet, side) {
1316
+ const target = sheetDecision(file, sheet);
1317
+ undoStack.push({kind: 'sheet', fileId: file.id, sheet: sheet.name, previous: target.sheet});
1318
+ target.sheet = side; target.confirmed = false; render();
1319
+ }
1320
+ function chooseRename(file, sheet, side) {
1321
+ const target = sheetDecision(file, sheet);
1322
+ undoStack.push({kind: 'rename', fileId: file.id, sheet: sheet.name, previous: target.rename});
1323
+ target.rename = side; renderSheetChoice(); updateStats();
1324
+ }
1325
+ function chooseMergedCells(file, sheet, side) {
1326
+ const target = sheetDecision(file, sheet);
1327
+ undoStack.push({kind: 'mergedCells', fileId: file.id, sheet: sheet.name, previous: target.mergedCells});
1328
+ target.mergedCells = side; renderSheetChoice(); renderTable(); updateStats();
1329
+ }
1330
+ function toggleAxis(file, sheet, kind, axis) {
1331
+ const target = sheetDecision(file, sheet); const previous = target[kind][axis.id] || axis.default;
1332
+ undoStack.push({kind: 'axis', fileId: file.id, sheet: sheet.name, axisKind: kind, axisId: axis.id, previous});
1333
+ target[kind][axis.id] = previous === 'keep' ? 'delete' : 'keep';
1334
+ renderSheetTabs(); renderTable(); renderConflictNavigation(); updateStats();
1335
+ }
1336
+ function chooseMacro(file, side) {
1337
+ const target = fileDecision(file); const previous = target.macro || file.macro.default;
1338
+ if (side === 'theirs' && !file.macro.canChooseTheirs) return;
1339
+ undoStack.push({kind: 'macro', fileId: file.id, previous});
1340
+ target.macro = side; render();
1341
+ }
1342
+ function sideAxisChoice(axis, side) {
1343
+ const key = side === 'ours' ? ['oursRow', 'oursCol'] : ['theirsRow', 'theirsCol'];
1344
+ return key.some(name => axis[name] !== undefined && axis[name] !== null) ? 'keep' : 'delete';
1345
+ }
1346
+ function bulkChoose(side) {
1347
+ const file = currentFileData(); const sheet = currentSheetData(); if (!sheet) return;
1348
+ if (currentSheetIsConfirmed()) return;
1349
+ if (sheet.action.startsWith('conflict_')) { chooseSheet(file, sheet, side); return; }
1350
+ const target = sheetDecision(file, sheet);
1351
+ if (sheet.renameStatus === 'rename_conflict') {
1352
+ undoStack.push({kind: 'rename', fileId: file.id, sheet: sheet.name, previous: target.rename});
1353
+ target.rename = side;
1354
+ }
1355
+ if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') {
1356
+ undoStack.push({kind: 'mergedCells', fileId: file.id, sheet: sheet.name, previous: target.mergedCells});
1357
+ target.mergedCells = side;
1358
+ }
1359
+ for (const [kind, axes] of [['rows', sheet.allRows || sheet.rows || []], ['columns', sheet.columns || []]]) {
1360
+ for (const axis of axes) if (axis.state === 'delete_modify') {
1361
+ undoStack.push({kind: 'axis', fileId: file.id, sheet: sheet.name, axisKind: kind, axisId: axis.id, previous: target[kind][axis.id]});
1362
+ target[kind][axis.id] = sideAxisChoice(axis, side);
1363
+ }
1364
+ }
1365
+ for (const cell of sheet.cells || []) {
1366
+ const key = cellKey(cell); const selected = side === 'ours' ? cell.oursPresent !== false : cell.theirsPresent !== false;
1367
+ if (!selected) continue;
1368
+ pushCellUndo(file, sheet, cell); target.cells[key] = side;
1369
+ }
1370
+ render();
1371
+ }
1372
+ function bulkStructuralRow(rowId) {
1373
+ const file = currentFileData(); const sheet = currentSheetData(); const target = sheetDecision(file, sheet);
1374
+ const row = (sheet.allRows || []).find(item => item.id === rowId);
1375
+ if (!row || !axisKept(file, sheet, 'rows', row)) return;
1376
+ for (const cell of (sheet.cells || []).filter(item => item.rowId === rowId)) {
1377
+ const column = (sheet.columns || []).find(item => item.id === cell.colId);
1378
+ if (!column || !axisKept(file, sheet, 'columns', column) || row.locked || column.locked) continue;
1379
+ pushCellUndo(file, sheet, cell); const key = cellKey(cell);
1380
+ target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1381
+ }
1382
+ renderTable(); renderConflictNavigation(); updateStats();
1383
+ }
1384
+ function bulkStructuralColumn(columnId) {
1385
+ const file = currentFileData(); const sheet = currentSheetData(); const target = sheetDecision(file, sheet);
1386
+ const column = (sheet.columns || []).find(item => item.id === columnId);
1387
+ if (!column || !axisKept(file, sheet, 'columns', column)) return;
1388
+ for (const cell of (sheet.cells || []).filter(item => item.colId === columnId)) {
1389
+ const row = (sheet.allRows || []).find(item => item.id === cell.rowId);
1390
+ if (!row || !axisKept(file, sheet, 'rows', row) || row.locked || column.locked) continue;
1391
+ pushCellUndo(file, sheet, cell); const key = cellKey(cell);
1392
+ target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1393
+ }
1394
+ renderTable(); renderConflictNavigation(); updateStats();
1395
+ }
1396
+ function bulkRow(row) {
1397
+ const file = currentFileData(); const sheet = currentSheetData();
1398
+ for (const cell of (sheet.cells || []).filter(item => item.row === row)) {
1399
+ const target = sheetDecision(file, sheet); pushCellUndo(file, sheet, cell);
1400
+ const key = cellKey(cell); target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1401
+ }
1402
+ renderTable(); renderConflictNavigation(); updateStats();
1403
+ }
1404
+ function bulkCol(col) {
1405
+ const file = currentFileData(); const sheet = currentSheetData();
1406
+ for (const cell of (sheet.cells || []).filter(item => item.col === col)) {
1407
+ const target = sheetDecision(file, sheet); pushCellUndo(file, sheet, cell);
1408
+ const key = cellKey(cell); target.cells[key] = target.cells[key] === 'ours' ? 'theirs' : 'ours';
1409
+ }
1410
+ renderTable(); renderConflictNavigation(); updateStats();
1411
+ }
1412
+ function undo() {
1413
+ const file = currentFileData(); const sheet = currentSheetData();
1414
+ if (!file || !sheet) return;
1415
+ let actionIndex = -1;
1416
+ for (let index = undoStack.length - 1; index >= 0; index--) {
1417
+ const candidate = undoStack[index];
1418
+ if (candidate.fileId === file.id && candidate.sheet === sheet.name) {
1419
+ actionIndex = index;
1420
+ break;
1421
+ }
1422
+ }
1423
+ if (actionIndex < 0) return;
1424
+ const [action] = undoStack.splice(actionIndex, 1);
1425
+ const actionFile = model.files.find(item => item.id === action.fileId);
1426
+ const actionSheet = actionFile.diff.sheets.find(item => item.name === action.sheet);
1427
+ const target = sheetDecision(actionFile, actionSheet);
1428
+ target.confirmed = false;
1429
+ if (action.kind === 'sheet') target.sheet = action.previous;
1430
+ else if (action.kind === 'rename') target.rename = action.previous;
1431
+ else if (action.kind === 'mergedCells') target.mergedCells = action.previous;
1432
+ else if (action.kind === 'axis') target[action.axisKind][action.axisId] = action.previous;
1433
+ else target.cells[action.key] = action.previous;
1434
+ render();
1435
+ }
1436
+ function resetSheet() {
1437
+ const file = currentFileData();
1438
+ const sheet = currentSheetData();
1439
+ if (!file || !sheet) return;
1440
+ const target = sheetDecision(file, sheet); const sheetChoice = defaultSheetChoice(sheet);
1441
+ target.confirmed = false;
1442
+ delete target.lastNavigatedConflict;
1443
+ if (sheetChoice) target.sheet = sheetChoice; else delete target.sheet;
1444
+ if (sheet.renameStatus === 'rename_conflict') target.rename = 'ours'; else delete target.rename;
1445
+ if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') target.mergedCells = sheet.mergedCells.default || 'ours'; else delete target.mergedCells;
1446
+ target.rows = {}; target.columns = {}; target.cells = {};
1447
+ delete target.repairs;
1448
+ for (const row of sheet.allRows || sheet.rows || []) if (row.state === 'delete_modify') target.rows[row.id] = row.default;
1449
+ for (const column of sheet.columns || []) if (column.state === 'delete_modify') target.columns[column.id] = column.default;
1450
+ for (const cell of sheet.cells || []) target.cells[cellKey(cell)] = defaultCellChoice(cell);
1451
+ // A reset supersedes prior choices for this Sheet, while preserving other files,
1452
+ // other Sheets, and file-level macro choices in the shared undo history.
1453
+ undoStack = undoStack.filter(action => action.fileId !== file.id || action.sheet !== sheet.name);
1454
+ render();
1455
+ }
1456
+ function updateGlobalConfirmationStats() {
1457
+ let confirmed = 0; let total = 0;
1458
+ for (const file of model.files) for (const sheet of file.diff.sheets) {
1459
+ if (!sheetNeedsConfirmation(sheet)) continue;
1460
+ total++;
1461
+ if (sheetDecision(file, sheet).confirmed) confirmed++;
1462
+ }
1463
+ byId('confirmedSheetCount').textContent = String(confirmed);
1464
+ byId('totalConflictSheetCount').textContent = String(total);
1465
+ }
1466
+ function updateDecisionFooterStats() {
1467
+ let total = 0; let local = 0;
1468
+ for (const file of model.files) {
1469
+ if (file.macro && file.macro.status === 'conflict') {
1470
+ total++; if ((fileDecision(file).macro || file.macro.default) === 'ours') local++;
1471
+ }
1472
+ for (const sheet of file.diff.sheets) {
1473
+ const target = sheetDecision(file, sheet);
1474
+ if (sheet.action.startsWith('conflict_')) { total++; if (target.sheet === 'ours') local++; }
1475
+ if (sheet.renameStatus === 'rename_conflict') { total++; if (target.rename === 'ours') local++; }
1476
+ if (sheet.mergedCells && sheet.mergedCells.status === 'conflict') { total++; if (target.mergedCells === 'ours') local++; }
1477
+ for (const row of sheet.allRows || sheet.rows || []) if (row.state === 'delete_modify') {
1478
+ total++; const oursChoice = row.oursRow !== null && row.oursRow !== undefined ? 'keep' : 'delete';
1479
+ if ((target.rows[row.id] || row.default) === oursChoice) local++;
1480
+ }
1481
+ for (const column of sheet.columns || []) if (column.state === 'delete_modify') {
1482
+ total++; const oursChoice = column.oursCol !== null && column.oursCol !== undefined ? 'keep' : 'delete';
1483
+ if ((target.columns[column.id] || column.default) === oursChoice) local++;
1484
+ }
1485
+ for (const cell of sheet.cells || []) {
1486
+ if (sheet.columns && sheet.allRows && !structuralCellSelectable(file, sheet, cell)) continue;
1487
+ total++; if (target.cells[cellKey(cell)] === 'ours') local++;
1488
+ }
1489
+ }
1490
+ }
1491
+ const file = currentFileData(); const sheet = currentSheetData();
1492
+ byId('footerStatus').textContent = `共 ${total} 个可决策项,${local} 项采用本地 · 当前:${file.path}${sheet ? ` / ${sheet.name}` : ''}${autoTheirsNote(' · ')}`;
1493
+ }
1494
+ function updateStats() {
1495
+ updateGlobalConfirmationStats();
1496
+ updateDecisionFooterStats();
1497
+ }
1498
+
1499
+ function renderCommitSteps(steps) {
1500
+ const host = byId('commitModalSteps'); host.replaceChildren();
1501
+ for (const step of steps || []) {
1502
+ const line = document.createElement('div');
1503
+ line.textContent = `${step.success ? '✓' : '✗'} ${step.step || ''}${step.output ? ` — ${String(step.output).slice(0, 240)}` : ''}`;
1504
+ host.append(line);
1505
+ }
1506
+ }
1507
+ function showCommitModal(kind, title, body, steps, buttons) {
1508
+ const modal = byId('commitModal'); modal.classList.remove('is-hidden', 'is-success', 'is-error');
1509
+ if (kind) modal.classList.add(`is-${kind}`);
1510
+ byId('commitModalTitle').textContent = title; byId('commitModalBody').textContent = body || ''; renderCommitSteps(steps);
1511
+ const actions = byId('commitModalActions'); actions.replaceChildren();
1512
+ for (const spec of buttons || []) { const button = document.createElement('button'); button.className = `btn ${spec.className || ''}`; button.textContent = spec.label; button.onclick = spec.onclick; actions.append(button); }
1513
+ }
1514
+ function closeCommitModal() { byId('commitModal').classList.add('is-hidden'); }
1515
+ async function cancelAndExit() {
1516
+ const cancelButton = byId('cancelBtn');
1517
+ const submitButton = byId('submitBtn');
1518
+ cancelButton.disabled = true;
1519
+ submitButton.disabled = true;
1520
+ byId('footerStatus').textContent = '正在取消并退出,不会写入任何更改...';
1521
+ try {
1522
+ const response = await fetch('/api/shutdown', {method: 'POST'});
1523
+ const result = await response.json();
1524
+ if (!response.ok || !result.success) throw new Error(result.error || '无法关闭解析器');
1525
+ byId('footerStatus').textContent = '已取消,未写入任何更改。';
1526
+ window.close();
1527
+ } catch (error) {
1528
+ cancelButton.disabled = false;
1529
+ submitButton.disabled = false;
1530
+ byId('footerStatus').textContent = `退出失败: ${error.message}`;
1531
+ }
1532
+ }
1533
+ function renderCommitMessage(text) {
1534
+ const host = byId('commitModalSteps'); host.replaceChildren();
1535
+ const line = document.createElement('div');
1536
+ line.textContent = text || '(无冲突 Cell,将使用默认提交信息)';
1537
+ host.append(line);
1538
+ }
1539
+ function unconfirmedSheets() {
1540
+ const pending = [];
1541
+ for (const [fileIndex, file] of model.files.entries()) {
1542
+ for (const [sheetIndex, sheet] of file.diff.sheets.entries()) {
1543
+ if (!sheetNeedsConfirmation(sheet) || sheetDecision(file, sheet).confirmed) continue;
1544
+ pending.push({file, sheet, fileIndex, sheetIndex, label: `${file.path}-${sheet.name}`});
1545
+ }
1546
+ }
1547
+ return pending;
1548
+ }
1549
+ function renderUnconfirmedSheetList(pending) {
1550
+ const host = byId('commitModalSteps'); host.replaceChildren();
1551
+ for (const item of pending) {
1552
+ const button = document.createElement('button');
1553
+ button.type = 'button';
1554
+ button.className = 'btn btn-cancel';
1555
+ button.style.display = 'block';
1556
+ button.style.width = '100%';
1557
+ button.style.marginBottom = '7px';
1558
+ button.style.textAlign = 'left';
1559
+ button.textContent = item.label;
1560
+ button.title = `切换到 ${item.label}`;
1561
+ button.onclick = () => {
1562
+ currentFile = item.fileIndex;
1563
+ currentSheet = item.sheetIndex;
1564
+ currentPage = 0;
1565
+ closeCommitModal();
1566
+ render();
1567
+ };
1568
+ host.append(button);
1569
+ }
1570
+ }
1571
+ async function submitResolve() {
1572
+ const button = byId('submitBtn');
1573
+ const pending = unconfirmedSheets();
1574
+ if (pending.length) {
1575
+ byId('footerStatus').textContent = `仍有 ${pending.length} 个 Sheet 未确认,请先完成审阅。`;
1576
+ showCommitModal('', '仍有未确认的 Sheet', '提交前必须人工勾选确认每个需要审阅的 Sheet。点击下方条目可直接切换过去。', [], [
1577
+ {label: '返回继续审阅', className: 'btn-submit', onclick: () => { closeCommitModal(); button.disabled = false; }}
1578
+ ]);
1579
+ renderUnconfirmedSheetList(pending);
1580
+ return;
1581
+ }
1582
+ button.disabled = true;
1583
+ byId('footerStatus').textContent = '正在生成 commit 信息预览...';
1584
+ try {
1585
+ const previewResponse = await fetch('/api/commit-preview', {
1586
+ method: 'POST', headers: {'Content-Type': 'application/json'},
1587
+ body: JSON.stringify({decisions})
1588
+ });
1589
+ const preview = await previewResponse.json();
1590
+ if (!previewResponse.ok || preview.error) throw new Error(preview.error || '无法生成 commit 信息');
1591
+ // 居中二次确认:展示 commit 信息列表(可滑动),确认后才真正执行 add / commit
1592
+ showCommitModal('', '确认提交', '请核对以下 commit 信息,确认后将执行 git add / commit:', [], [
1593
+ {label: '取消', className: '', onclick: () => { closeCommitModal(); button.disabled = false; byId('footerStatus').textContent = '已取消,未提交任何更改。'; }},
1594
+ {label: '确认提交', className: 'btn-submit', onclick: () => { closeCommitModal(); doSubmitResolve(); }}
1595
+ ]);
1596
+ renderCommitMessage(preview.message || '');
1597
+ } catch (error) {
1598
+ button.disabled = false;
1599
+ byId('footerStatus').textContent = `错误: ${error.message}`;
1600
+ }
1601
+ }
1602
+ async function doSubmitResolve() {
1603
+ byId('footerStatus').textContent = '正在合并并提交...';
1604
+ showCommitModal('', '正在合并并提交...', '正在写回工作簿并执行 git add / commit,请稍候。', [], []);
1605
+ try {
1606
+ const response = await fetch('/api/resolve', {
1607
+ method: 'POST', headers: {'Content-Type': 'application/json'},
1608
+ body: JSON.stringify({decisions, commit: true, push: false})
1609
+ });
1610
+ const result = await response.json();
1611
+ if (!result.success) throw new Error(result.error || (result.steps || []).filter(step => !step.success).map(step => `${step.step}: ${step.output}`).join('\n') || '提交失败');
1612
+ byId('footerStatus').textContent = '完成!合并并提交成功。';
1613
+ showCommitModal('success', '提交成功', '多 Sheet 合并结果已写入并提交。解析器即将关闭。', result.steps, [
1614
+ {label: '关闭窗口', className: 'btn-submit', onclick: () => { try { window.close(); } catch (_) {} }}
1615
+ ]);
1616
+ } catch (error) {
1617
+ const c = byId('submitBtn'); c.disabled = false; byId('footerStatus').textContent = `错误: ${error.message}`;
1618
+ showCommitModal('error', '提交失败', error.message, [], [{label: '关闭', onclick: closeCommitModal}]);
1619
+ }
1620
+ }
1621
+
1622
+ byId('allLocalBtn').onclick = () => bulkChoose('ours');
1623
+ byId('allRemoteBtn').onclick = () => bulkChoose('theirs');
1624
+ byId('undoBtn').onclick = undo;
1625
+ byId('resetBtn').onclick = resetSheet;
1626
+ byId('cancelBtn').onclick = cancelAndExit;
1627
+ byId('submitBtn').onclick = submitResolve;
1628
+ byId('prevConflictBtn').onclick = () => locateConflictCell(-1);
1629
+ byId('nextConflictBtn').onclick = () => locateConflictCell(1);
1630
+ enableHorizontalWheel(byId('fileTabs'));
1631
+ enableHorizontalWheel(byId('sheetTabs'));
1632
+ init().catch(error => { byId('footerStatus').textContent = `加载失败: ${error.message}`; });
1633
+ </script>
1634
+ </body>
1635
+ </html>