Repository navigation
Expand file tree
/
Copy pathdiff_report_extended.test.js
More file actions
1234 lines (1135 loc) · 55.6 KB
/
Copy pathdiff_report_extended.test.js
File metadata and controls
1234 lines (1135 loc) · 55.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Extended unit tests for diff_report JS modules — covering gaps in the original test suite.
* diff_report JS モジュールの拡張ユニットテスト — 元テストスイートのカバレッジギャップを補完。
*/
const { TextEncoder, TextDecoder } = require('util');
// Polyfill TextEncoder/TextDecoder for jsdom environment
// jsdom 環境用の TextEncoder/TextDecoder ポリフィル
if (typeof globalThis.TextEncoder === 'undefined') {
globalThis.TextEncoder = TextEncoder;
}
if (typeof globalThis.TextDecoder === 'undefined') {
globalThis.TextDecoder = TextDecoder;
}
const fs = require('fs');
const path = require('path');
// Load all JS module files in order and concatenate them
// 全 JS モジュールファイルを順序どおりに読み込み結合する
const JS_MODULE_FILES = [
'diff_report_state.js',
'diff_report_export.js',
'diff_report_diffview.js',
'diff_report_lazy.js',
'diff_report_virtualscroll.js',
'diff_report_layout.js',
'diff_report_filter.js',
'diff_report_excel.js',
'diff_report_theme.js',
'diff_report_celebrate.js',
'diff_report_highlight.js',
'diff_report_keyboard.js',
'diff_report_init.js',
];
const JS_SOURCE = JS_MODULE_FILES.map(function(f) {
return fs.readFileSync(
path.join(__dirname, '..', 'Services', 'HtmlReport', 'js', f),
'utf-8'
);
}).join('\n');
/**
* Load diff_report JS modules into the current jsdom window with given options.
* diff_report JS モジュールを指定オプションで現在の jsdom window にロードする。
*/
function loadScript(options = {}) {
const {
storageKey = 'test-key',
reportDate = '2026-01-01',
savedState = null,
bodyHtml = '',
totalFiles = 0,
totalFilesDetail = '',
} = options;
document.documentElement.innerHTML = '<head><title>diff_report</title></head><body></body>';
document.body.innerHTML = bodyHtml;
localStorage.clear();
if (typeof Element.prototype.scrollIntoView !== 'function') {
Element.prototype.scrollIntoView = function() {};
}
let js = JS_SOURCE
.replace("'{{STORAGE_KEY}}'", JSON.stringify(storageKey))
.replace("'{{REPORT_DATE}}'", JSON.stringify(reportDate))
.replace('{{TOTAL_FILES}}', String(totalFiles))
.replace('{{TOTAL_FILES_DETAIL}}', totalFilesDetail);
if (savedState !== null) {
js = js.replace(
'const __savedState__ = null;',
'const __savedState__ = ' + JSON.stringify(savedState) + ';'
);
}
const indirectEval = eval;
indirectEval(js);
}
function fireDOMContentLoaded() {
document.dispatchEvent(new Event('DOMContentLoaded'));
}
/** Build filter controls HTML shared by many tests / 多くのテストで共有するフィルタコントロール HTML */
function filterControlsHtml() {
return `
<input type="checkbox" id="filter-imp-high" checked />
<input type="checkbox" id="filter-imp-medium" checked />
<input type="checkbox" id="filter-imp-low" checked />
<input type="checkbox" id="filter-diff-sha256match" checked />
<input type="checkbox" id="filter-diff-sha256mismatch" checked />
<input type="checkbox" id="filter-diff-ilmatch" checked />
<input type="checkbox" id="filter-diff-ilmismatch" checked />
<input type="checkbox" id="filter-diff-textmatch" checked />
<input type="checkbox" id="filter-diff-textmismatch" checked />
<input type="checkbox" id="filter-unchecked" />
<input type="text" id="filter-search" value="" />
<span id="save-status"></span>
<div id="progress-bar-fill"></div>
<span id="progress-text"></span>
`;
}
// ─── getStoredTheme ─────────────────────────────────────────────────────────
// テーマ保存の読み取りテスト
describe('getStoredTheme', () => {
test('returns null when no theme is stored', () => {
loadScript({ storageKey: 'theme-test' });
expect(window.getStoredTheme()).toBeNull();
});
test('returns stored theme value', () => {
loadScript({ storageKey: 'theme-test' });
localStorage.setItem('theme-test-theme', 'dark');
expect(window.getStoredTheme()).toBe('dark');
});
test('returns null on localStorage error', () => {
loadScript({ storageKey: 'theme-test' });
const orig = localStorage.getItem;
localStorage.getItem = () => { throw new Error('blocked'); };
expect(window.getStoredTheme()).toBeNull();
localStorage.getItem = orig;
});
});
// ─── highlightAllILDiffs ────────────────────────────────────────────────────
// 全 IL diff テーブルへのハイライト一括適用テスト
describe('highlightAllILDiffs', () => {
test('applies highlighting to all diff-table elements with ILMismatch parent', () => {
const html = `
<table><tbody>
<tr data-section="mod" data-diff="ILMismatch"><td>1</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr class="diff-row"><td colspan="8">
<details open>
<summary>Diff</summary>
<table class="diff-table"><tbody>
<tr><td class="diff-ctx-td">.method public void Test()</td></tr>
</tbody></table>
</details>
</td></tr>
</tbody></table>
${filterControlsHtml()}
`;
loadScript({ bodyHtml: html });
window.highlightAllILDiffs();
const td = document.querySelector('.diff-ctx-td');
expect(td.innerHTML).toContain('hl-');
});
test('skips non-IL diff tables (SHA256Mismatch)', () => {
const html = `
<table><tbody>
<tr data-section="mod" data-diff="SHA256Mismatch"><td>1</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr class="diff-row"><td colspan="8">
<details open>
<summary>Diff</summary>
<table class="diff-table"><tbody>
<tr><td class="diff-ctx-td">.method public void Test()</td></tr>
</tbody></table>
</details>
</td></tr>
</tbody></table>
${filterControlsHtml()}
`;
loadScript({ bodyHtml: html });
window.highlightAllILDiffs();
const td = document.querySelector('.diff-ctx-td');
expect(td.innerHTML).not.toContain('hl-');
});
});
// ─── wrapInputWithClear ─────────────────────────────────────────────────────
// テキスト入力のクリアボタン生成テスト
describe('wrapInputWithClear', () => {
test('wraps input with container and clear button', () => {
loadScript({
bodyHtml: '<div><input type="text" id="test-input" value="hello" /></div>',
});
const inp = document.getElementById('test-input');
window.wrapInputWithClear(inp);
expect(inp.parentElement.classList.contains('input-wrap')).toBe(true);
const btn = inp.parentElement.querySelector('.btn-input-clear');
expect(btn).not.toBeNull();
});
test('clear button clears input value and dispatches events', () => {
loadScript({
bodyHtml: '<div><input type="text" id="test-input" value="hello" /></div>',
});
const inp = document.getElementById('test-input');
window.wrapInputWithClear(inp);
const btn = inp.parentElement.querySelector('.btn-input-clear');
let inputFired = false;
let changeFired = false;
inp.addEventListener('input', () => { inputFired = true; });
inp.addEventListener('change', () => { changeFired = true; });
btn.click();
expect(inp.value).toBe('');
expect(inputFired).toBe(true);
expect(changeFired).toBe(true);
});
test('uses filter-search-wrap class for filter-search inputs', () => {
loadScript({
bodyHtml: '<div><input type="text" id="filter-search" class="filter-search" value="" /></div>',
});
const inp = document.getElementById('filter-search');
window.wrapInputWithClear(inp);
expect(inp.parentElement.classList.contains('filter-search-wrap')).toBe(true);
});
test('does not double-wrap already-wrapped inputs', () => {
loadScript({
bodyHtml: '<div><input type="text" id="test-input" value="" /></div>',
});
const inp = document.getElementById('test-input');
window.wrapInputWithClear(inp);
window.wrapInputWithClear(inp);
// Should still have only one wrapper / ラッパーは1つだけであるべき
expect(document.querySelectorAll('.input-wrap').length).toBe(1);
});
test('has-text class toggles based on input value', () => {
loadScript({
bodyHtml: '<div><input type="text" id="test-input" value="x" /></div>',
});
const inp = document.getElementById('test-input');
window.wrapInputWithClear(inp);
const wrap = inp.parentElement;
expect(wrap.classList.contains('has-text')).toBe(true);
inp.value = '';
inp.dispatchEvent(new Event('input'));
expect(wrap.classList.contains('has-text')).toBe(false);
});
});
// ─── initClearButtons ───────────────────────────────────────────────────────
// フィルター検索のクリアボタン初期化テスト
describe('initClearButtons', () => {
test('wraps filter-search input with clear button', () => {
loadScript({
bodyHtml: '<div><input type="text" id="filter-search" value="" /></div>' + filterControlsHtml(),
});
fireDOMContentLoaded();
const inp = document.getElementById('filter-search');
const btn = inp.parentElement.querySelector('.btn-input-clear');
expect(btn).not.toBeNull();
});
});
// ─── initColResizeSingle ────────────────────────────────────────────────────
// 列リサイズハンドル初期化テスト
describe('initColResizeSingle', () => {
test('wraps th content in span.th-label and adds resize handle', () => {
loadScript({
bodyHtml: `
<table class="semantic-changes-table"><thead><tr>
<th class="th-resizable" data-col-var="--sc-name-w">Name</th>
</tr></thead><tbody></tbody></table>
${filterControlsHtml()}
`,
});
const th = document.querySelector('.th-resizable');
window.initColResizeSingle(th);
expect(th.querySelector('.th-label')).not.toBeNull();
expect(th.querySelector('.th-label').textContent).toBe('Name');
expect(th.querySelector('.col-resize-handle')).not.toBeNull();
});
test('mousedown on handle starts resize and mousemove updates CSS variable', () => {
loadScript({
bodyHtml: `
<table class="semantic-changes-table"><thead><tr>
<th class="th-resizable" data-col-var="--sc-name-w">Name</th>
</tr></thead><tbody></tbody></table>
${filterControlsHtml()}
`,
});
const th = document.querySelector('.th-resizable');
window.initColResizeSingle(th);
const handle = th.querySelector('.col-resize-handle');
// Simulate drag / ドラッグをシミュレート
handle.dispatchEvent(new MouseEvent('mousedown', { clientX: 100, bubbles: true }));
document.dispatchEvent(new MouseEvent('mousemove', { clientX: 200, bubbles: true }));
const root = document.documentElement;
const val = root.style.getPropertyValue('--sc-name-w');
expect(val).toBeTruthy();
// Cleanup / クリーンアップ
document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
});
});
// ─── syncScTableWidths ──────────────────────────────────────────────────────
// セマンティック変更テーブル幅同期テスト
describe('syncScTableWidths', () => {
test('sets width on sc-detail tables', () => {
loadScript({
bodyHtml: `
<table class="sc-detail semantic-changes-table"><thead><tr><th>A</th></tr></thead><tbody></tbody></table>
${filterControlsHtml()}
`,
});
window.syncScTableWidths();
const table = document.querySelector('.sc-detail');
expect(table.style.width).toBeTruthy();
expect(table.style.width).toContain('px');
});
test('sets width on dc-detail tables', () => {
loadScript({
bodyHtml: `
<table class="dc-detail"><thead><tr><th>A</th></tr></thead><tbody></tbody></table>
${filterControlsHtml()}
`,
});
window.syncScTableWidths();
const table = document.querySelector('.dc-detail');
expect(table.style.width).toBeTruthy();
expect(table.style.width).toContain('px');
});
});
// ─── syncFilterRowHeight ────────────────────────────────────────────────────
// フィルター行高さ同期テスト
describe('syncFilterRowHeight', () => {
test('does not throw when no filter-table exists', () => {
loadScript();
expect(() => window.syncFilterRowHeight()).not.toThrow();
});
});
// ─── Virtual scroll ─────────────────────────────────────────────────────────
// 仮想スクロール機能テスト
describe('initVirtualScroll', () => {
/** Generate a table with N rows for virtual scroll testing / 仮想スクロールテスト用にN行テーブルを生成 */
function buildVsTable(rowCount, sectionPrefix) {
const prefix = sectionPrefix || 'mod';
let rows = '';
for (let i = 0; i < rowCount; i++) {
rows += `<tr data-sc-importance="${i % 3 === 0 ? 'High' : i % 3 === 1 ? 'Medium' : 'Low'}"><td><input type="checkbox" id="sc_${prefix}_${i}" /></td><td>Row ${i}</td></tr>`;
}
return `<table class="semantic-changes-table sc-detail"><thead><tr><th>CB</th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>`;
}
test('returns false for table with <= 100 rows (below threshold)', () => {
loadScript({
bodyHtml: buildVsTable(50) + filterControlsHtml(),
});
const table = document.querySelector('.semantic-changes-table');
expect(window.initVirtualScroll(table)).toBe(false);
expect(table.__vs).toBeUndefined();
});
test('returns true and wraps table in vs-viewport for > 100 rows', () => {
loadScript({
bodyHtml: buildVsTable(150) + filterControlsHtml(),
});
const table = document.querySelector('.semantic-changes-table');
const result = window.initVirtualScroll(table);
expect(result).toBe(true);
expect(table.parentElement.classList.contains('vs-viewport')).toBe(true);
expect(table.__vs).toBeDefined();
expect(table.__vs.rowData.length).toBe(150);
});
test('creates row count indicator after viewport', () => {
loadScript({
bodyHtml: buildVsTable(120) + filterControlsHtml(),
});
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
const indicator = table.__vs.indicator;
expect(indicator).toBeDefined();
expect(indicator.textContent).toContain('120');
expect(indicator.textContent).toContain('of');
});
test('renders only a subset of rows (not all 150)', () => {
loadScript({
bodyHtml: buildVsTable(150) + filterControlsHtml(),
});
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
const renderedRows = table.__vs.tbody.querySelectorAll('tr:not(.vs-spacer)');
// Should render fewer than all 150 rows / 150行未満がレンダリングされるはず
expect(renderedRows.length).toBeLessThan(150);
expect(renderedRows.length).toBeGreaterThan(0);
});
test('returns false when table has no tbody', () => {
loadScript({
bodyHtml: '<table class="semantic-changes-table"></table>' + filterControlsHtml(),
});
const table = document.querySelector('.semantic-changes-table');
expect(window.initVirtualScroll(table)).toBe(false);
});
});
describe('vsRender', () => {
function setupVsTable(rowCount) {
let rows = '';
for (let i = 0; i < rowCount; i++) {
rows += `<tr data-sc-importance="High"><td><input type="checkbox" id="sc_r_${i}" /></td><td>Row ${i}</td></tr>`;
}
const html = `<table class="semantic-changes-table sc-detail"><thead><tr><th>CB</th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
return table;
}
test('skips re-render when range is unchanged', () => {
const table = setupVsTable(150);
const startBefore = table.__vs.renderedStart;
// Call render again without scrolling — should be no-op / スクロールなしで再度呼出 — 何もしないはず
window.vsRender(table);
expect(table.__vs.renderedStart).toBe(startBefore);
});
test('does nothing if table has no __vs', () => {
loadScript({
bodyHtml: '<table id="plain"><tbody><tr><td>x</td></tr></tbody></table>' + filterControlsHtml(),
});
const table = document.getElementById('plain');
expect(() => window.vsRender(table)).not.toThrow();
});
});
describe('vsRefreshVisibility', () => {
test('hides rows based on importance filter state', () => {
let rows = '';
for (let i = 0; i < 120; i++) {
const imp = i % 2 === 0 ? 'High' : 'Low';
rows += `<tr data-sc-importance="${imp}"><td><input type="checkbox" id="sc_f_${i}" /></td><td>Row ${i}</td></tr>`;
}
const html = `<table class="semantic-changes-table sc-detail __vs-active"><thead><tr><th>A</th><th>B</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
// Uncheck Low filter / Low フィルターをオフ
document.getElementById('filter-imp-low').checked = false;
window.vsRefreshVisibility(table);
// Only High rows should be visible / High 行のみ表示されるはず
const visibleCount = table.__vs.rowData.filter(r => !r.hidden).length;
expect(visibleCount).toBe(60); // half are High / 半分が High
expect(table.__vs.indicator.textContent).toContain('60');
});
test('does nothing if table has no __vs', () => {
loadScript({ bodyHtml: '<table id="t"><tbody></tbody></table>' + filterControlsHtml() });
expect(() => window.vsRefreshVisibility(document.getElementById('t'))).not.toThrow();
});
});
describe('vsMaterializeAll', () => {
test('restores full DOM from virtual scroll and removes viewport wrapper', () => {
let rows = '';
for (let i = 0; i < 120; i++) {
rows += `<tr data-sc-importance="High"><td><input type="checkbox" id="sc_m_${i}" /></td><td>Row ${i}</td></tr>`;
}
const html = `<table class="semantic-changes-table sc-detail"><thead><tr><th>A</th><th>B</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
table.classList.add('vs-active');
// Verify it's in virtual scroll mode / 仮想スクロールモードであることを確認
expect(table.__vs).toBeDefined();
window.vsMaterializeAll();
// After materialize, __vs should be removed / マテリアライズ後、__vs は削除されるはず
expect(table.__vs).toBeUndefined();
expect(table.classList.contains('vs-active')).toBe(false);
// All 120 rows should be in DOM / 全120行がDOMにあるはず
const allRows = table.querySelectorAll('tbody tr');
expect(allRows.length).toBe(120);
// Viewport wrapper should be removed / ビューポートラッパーは削除されるはず
expect(document.querySelector('.vs-viewport')).toBeNull();
});
});
// ─── Toggle-all header checkbox ─────────────────────────────────────────────
// 一括ヘッダーチェックボックステスト
describe('toggleAllInSection', () => {
function buildMainTable(sectionPrefix, rowCount) {
let rows = '';
for (let i = 0; i < rowCount; i++) {
rows += `<tr data-section="${sectionPrefix}"><td class="col-cb"><input type="checkbox" id="cb_${sectionPrefix}_${i}" /></td><td>File ${i}</td></tr>`;
}
return `<table><thead><tr><th class="col-cb"><input type="checkbox" class="cb-all" data-section="${sectionPrefix}" onchange="toggleAllInSection(this)" /></th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>`;
}
test('checks all row checkboxes when header is checked', () => {
loadScript({ bodyHtml: buildMainTable('add', 5) + filterControlsHtml() });
const headerCb = document.querySelector('.cb-all');
headerCb.checked = true;
window.toggleAllInSection(headerCb);
const rowCbs = document.querySelectorAll('tbody input[type="checkbox"]');
rowCbs.forEach(cb => expect(cb.checked).toBe(true));
});
test('unchecks all row checkboxes when header is unchecked', () => {
loadScript({ bodyHtml: buildMainTable('rem', 3) + filterControlsHtml() });
// First check all / まず全チェック
document.querySelectorAll('tbody input[type="checkbox"]').forEach(cb => { cb.checked = true; });
const headerCb = document.querySelector('.cb-all');
headerCb.checked = false;
window.toggleAllInSection(headerCb);
document.querySelectorAll('tbody input[type="checkbox"]').forEach(cb => expect(cb.checked).toBe(false));
});
});
describe('toggleAllInDetailTable', () => {
function buildDetailTable(rowCount) {
let rows = '';
for (let i = 0; i < rowCount; i++) {
rows += `<tr><td><input type="checkbox" id="sc_x_${i}" /></td><td>Member ${i}</td></tr>`;
}
return `<table class="semantic-changes-table sc-detail"><thead><tr><th class="sc-col-cb"><input type="checkbox" class="cb-all-detail" onchange="toggleAllInDetailTable(this)" /></th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>`;
}
test('checks all row checkboxes in non-virtual-scroll table', () => {
loadScript({ bodyHtml: buildDetailTable(5) + filterControlsHtml() });
const headerCb = document.querySelector('.cb-all-detail');
headerCb.checked = true;
window.toggleAllInDetailTable(headerCb);
document.querySelectorAll('tbody input[type="checkbox"]').forEach(cb => expect(cb.checked).toBe(true));
});
test('updates rowData.cbChecked for all rows in virtual scroll table', () => {
// Build table with >100 rows to trigger virtual scroll / 仮想スクロール起動のため100行超テーブル構築
let rows = '';
for (let i = 0; i < 120; i++) {
rows += `<tr data-sc-importance="High"><td><input type="checkbox" id="sc_vs_${i}" /></td><td>Member ${i}</td></tr>`;
}
const html = `<table class="semantic-changes-table sc-detail"><thead><tr><th class="sc-col-cb"><input type="checkbox" class="cb-all-detail" onchange="toggleAllInDetailTable(this)" /></th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
table.classList.add('vs-active');
// Toggle all on / 全チェック
const headerCb = document.querySelector('.cb-all-detail');
headerCb.checked = true;
window.toggleAllInDetailTable(headerCb);
// All rowData entries should be checked / 全 rowData エントリがチェック済みであること
table.__vs.rowData.forEach(rd => {
if (rd.cbId) expect(rd.cbChecked).toBe(true);
});
// Currently rendered DOM checkboxes should also be checked / 描画済み DOM チェックボックスもチェック済み
table.__vs.tbody.querySelectorAll('input[type="checkbox"]').forEach(cb => expect(cb.checked).toBe(true));
});
test('virtual scroll: unchecked state persists after re-render', () => {
let rows = '';
for (let i = 0; i < 120; i++) {
rows += `<tr data-sc-importance="High"><td><input type="checkbox" id="sc_vr_${i}" /></td><td>Member ${i}</td></tr>`;
}
const html = `<table class="semantic-changes-table sc-detail"><thead><tr><th class="sc-col-cb"><input type="checkbox" class="cb-all-detail" onchange="toggleAllInDetailTable(this)" /></th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
table.classList.add('vs-active');
// Check all then uncheck all / 全チェック後に全チェック解除
const headerCb = document.querySelector('.cb-all-detail');
headerCb.checked = true;
window.toggleAllInDetailTable(headerCb);
headerCb.checked = false;
window.toggleAllInDetailTable(headerCb);
// Force re-render / 再レンダリングを強制
table.__vs.renderedStart = -1;
table.__vs.renderedEnd = -1;
window.vsRender(table);
// Rendered checkboxes should be unchecked / 描画済みチェックボックスが未チェックであること
table.__vs.tbody.querySelectorAll('input[type="checkbox"]').forEach(cb => expect(cb.checked).toBe(false));
});
});
describe('syncHeaderCheckboxes', () => {
test('sets indeterminate when partially checked', () => {
let rows = '';
for (let i = 0; i < 3; i++) {
rows += `<tr data-section="mod"><td class="col-cb"><input type="checkbox" id="cb_mod_${i}" /></td><td>File ${i}</td></tr>`;
}
const html = `<table><thead><tr><th class="col-cb"><input type="checkbox" class="cb-all" data-section="mod" /></th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
// Check only first row / 最初の行のみチェック
document.getElementById('cb_mod_0').checked = true;
window.syncHeaderCheckboxes();
const hcb = document.querySelector('.cb-all');
expect(hcb.indeterminate).toBe(true);
expect(hcb.checked).toBe(false);
});
test('sets checked when all rows checked', () => {
let rows = '';
for (let i = 0; i < 3; i++) {
rows += `<tr data-section="add"><td class="col-cb"><input type="checkbox" id="cb_add_${i}" /></td><td>File ${i}</td></tr>`;
}
const html = `<table><thead><tr><th class="col-cb"><input type="checkbox" class="cb-all" data-section="add" /></th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
document.querySelectorAll('tbody input[type="checkbox"]').forEach(cb => { cb.checked = true; });
window.syncHeaderCheckboxes();
const hcb = document.querySelector('.cb-all');
expect(hcb.checked).toBe(true);
expect(hcb.indeterminate).toBe(false);
});
test('reads from rowData for virtual scroll detail tables', () => {
let rows = '';
for (let i = 0; i < 120; i++) {
rows += `<tr data-sc-importance="High"><td><input type="checkbox" id="sc_sh_${i}" /></td><td>M ${i}</td></tr>`;
}
const html = `<table class="semantic-changes-table sc-detail"><thead><tr><th class="sc-col-cb"><input type="checkbox" class="cb-all-detail" /></th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
table.classList.add('vs-active');
// Mark all rowData as checked / 全 rowData をチェック済みに
table.__vs.rowData.forEach(rd => { rd.cbChecked = true; });
window.syncHeaderCheckboxes();
const hcb = document.querySelector('.cb-all-detail');
expect(hcb.checked).toBe(true);
expect(hcb.indeterminate).toBe(false);
});
test('virtual scroll: partial check shows indeterminate on detail header', () => {
let rows = '';
for (let i = 0; i < 120; i++) {
rows += `<tr data-sc-importance="High"><td><input type="checkbox" id="sc_si_${i}" /></td><td>M ${i}</td></tr>`;
}
const html = `<table class="semantic-changes-table sc-detail"><thead><tr><th class="sc-col-cb"><input type="checkbox" class="cb-all-detail" /></th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
table.classList.add('vs-active');
// Mark only first half as checked / 前半のみチェック済みに
table.__vs.rowData.forEach((rd, i) => { rd.cbChecked = i < 60; });
window.syncHeaderCheckboxes();
const hcb = document.querySelector('.cb-all-detail');
expect(hcb.checked).toBe(false);
expect(hcb.indeterminate).toBe(true);
});
});
describe('collectState with virtual scroll', () => {
test('includes virtual scroll rowData entries not in DOM', () => {
let rows = '';
for (let i = 0; i < 120; i++) {
rows += `<tr data-sc-importance="High"><td><input type="checkbox" id="sc_cs_${i}" /></td><td>M ${i}</td></tr>`;
}
const html = `<table class="semantic-changes-table sc-detail"><thead><tr><th>CB</th><th>Name</th></tr></thead><tbody>${rows}</tbody></table>${filterControlsHtml()}`;
loadScript({ bodyHtml: html });
const table = document.querySelector('.semantic-changes-table');
window.initVirtualScroll(table);
table.classList.add('vs-active');
// Mark some non-rendered rows as checked / 非描画行をチェック済みに
table.__vs.rowData[119].cbChecked = true;
const state = window.collectState();
// The last row (likely not rendered) should still appear in state
// 最後の行(おそらく非描画)もstateに含まれるはず
expect(state['sc_cs_119']).toBe(true);
});
});
// ─── Excel export ───────────────────────────────────────────────────────────
// Excel エクスポートパイプラインテスト
describe('buildExcelFramework', () => {
test('produces complete Excel-compatible HTML with header, legend, sections', () => {
loadScript({
bodyHtml: `
<div class="header-card"><span class="header-card-label">App Version</span><span class="header-card-value">1.14.0</span></div>
<div class="header-path"><span class="header-path-label">Old Folder</span><span class="header-path-value">/old</span></div>
<div class="header-path"><span class="header-path-label">New Folder</span><span class="header-path-value">/new</span></div>
<table class="stat-table"><tbody>
<tr><td>Added</td><td>3</td></tr>
<tr><td>Removed</td><td>1</td></tr>
</tbody></table>
${filterControlsHtml()}
`,
});
const builtRows = {
add: ['<tr><td>row1</td></tr>'],
rem: ['<tr><td>row2</td></tr>'],
mod: [],
unch: [],
};
const result = window.buildExcelFramework(builtRows);
expect(result).toContain('<!DOCTYPE html>');
expect(result).toContain('1.14.0');
expect(result).toContain('/old');
expect(result).toContain('/new');
expect(result).toContain('Added Files');
expect(result).toContain('Removed Files');
expect(result).toContain('Legend');
expect(result).toContain('Summary');
});
test('includes ignored section when builtRows has ign entries', () => {
loadScript({ bodyHtml: filterControlsHtml() });
const builtRows = { ign: ['<tr><td>ignored</td></tr>'], unch: [], add: [], rem: [], mod: [] };
const result = window.buildExcelFramework(builtRows);
expect(result).toContain('Ignored Files');
});
test('includes warning sections for sha256w and tsw keys', () => {
loadScript({ bodyHtml: filterControlsHtml() });
const builtRows = {
unch: [], add: [], rem: [], mod: [],
sha256w: ['<tr><td>warn1</td></tr>'],
tsw: ['<tr><td>warn2</td></tr>'],
};
const result = window.buildExcelFramework(builtRows);
expect(result).toContain('Warnings');
expect(result).toContain('SHA256Mismatch');
expect(result).toContain('timestamps older');
});
test('shifts header and legend rows one column further right, and renders checklist as a 4-column block offset by 7 columns', () => {
loadScript({
bodyHtml: `
<div class="header-card"><span class="header-card-label">App Version</span><span class="header-card-value">1.14.0</span></div>
${filterControlsHtml()}
`,
});
const builtRows = {
unch: [],
add: [],
rem: [],
mod: [],
checklist: ['<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td class="bd">\u2713</td><td class="bd">Checklist item</td><td class="bd">Notes</td><td></td><td></td></tr>'],
};
const result = window.buildExcelFramework(builtRows);
expect(result).toContain('<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td class="bd" style="font-weight:bold;background:#f0f0f2">App Version</td>');
expect(result).toContain('<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td style="color:#000;font-weight:bold;padding:8px">Legend \u2014 Diff Detail</td>');
expect(result).toContain('<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td style="color:#000;font-weight:bold;padding:8px">Review Checklist (1)</td>');
expect(result).toContain('<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td class="bd" style="background:#f0f0f2;font-weight:bold">\u2713</td><td class="bd" style="background:#f0f0f2;font-weight:bold">Checklist Item</td><td class="bd" style="background:#f0f0f2;font-weight:bold">Notes</td><td></td><td></td></tr>');
expect(result).not.toContain('Review Checklist (1)</td><td></td><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td class="bd" style="background:#f0f0f2;font-weight:bold">#</td>');
});
});
describe('downloadExcelCompatibleHtml', () => {
test('calls downloadExcelImmediate for small reports (<=500 rows)', () => {
// Mock URL.createObjectURL and Blob / URL.createObjectURL と Blob をモック
const origCreateObjectURL = URL.createObjectURL;
const origRevokeObjectURL = URL.revokeObjectURL;
URL.createObjectURL = () => 'blob:test';
URL.revokeObjectURL = () => {};
loadScript({
bodyHtml: `
<table><tbody>
<tr data-section="mod"><td>1</td><td></td><td></td><td></td><td>Changed</td><td><span class="path-text">a.dll</span></td><td>2026-01-01</td><td>ILMismatch</td><td></td><td></td></tr>
</tbody></table>
${filterControlsHtml()}
`,
});
// Should not throw / エラーにならないはず
expect(() => window.downloadExcelCompatibleHtml()).not.toThrow();
URL.createObjectURL = origCreateObjectURL;
URL.revokeObjectURL = origRevokeObjectURL;
});
});
describe('downloadExcelImmediate', () => {
test('creates blob download with correct filename', () => {
const origCreateObjectURL = URL.createObjectURL;
const origRevokeObjectURL = URL.revokeObjectURL;
URL.createObjectURL = () => 'blob:test';
URL.revokeObjectURL = () => {};
loadScript({
reportDate: '20260101',
bodyHtml: `
<table><tbody>
<tr data-section="add"><td>1</td><td></td><td></td><td></td><td>Added</td><td><span class="path-text">new.dll</span></td><td>2026-01-01</td><td>N/A</td><td></td><td></td></tr>
</tbody></table>
${filterControlsHtml()}
`,
});
let downloadName = '';
const origAppendChild = document.body.appendChild.bind(document.body);
const origRemoveChild = document.body.removeChild.bind(document.body);
// Capture the download filename / ダウンロードファイル名をキャプチャ
const origClick = HTMLAnchorElement.prototype.click;
HTMLAnchorElement.prototype.click = function() {
downloadName = this.download || '';
};
window.downloadExcelImmediate();
expect(downloadName).toContain('Excel-compatible.html');
expect(downloadName).toContain('20260101');
HTMLAnchorElement.prototype.click = origClick;
URL.createObjectURL = origCreateObjectURL;
URL.revokeObjectURL = origRevokeObjectURL;
});
});
// ─── downloadAsPdf ──────────────────────────────────────────────────────────
// PDF ダウンロードテスト
describe('downloadAsPdf', () => {
test('injects pdf-print-header/footer and calls window.print', () => {
let printCalled = false;
window.print = () => { printCalled = true; };
loadScript({
bodyHtml: `
<div class="header-card"><span class="header-card-label">App Version</span><span class="header-card-value">1.14.0</span></div>
<div class="header-card"><span class="header-card-label">Computer</span><span class="header-card-value">WORKSTATION</span></div>
<div class="header-path"><span class="header-path-label">Old Folder</span><span class="header-path-value">/old</span></div>
<div class="header-path"><span class="header-path-label">New Folder</span><span class="header-path-value">/new</span></div>
${filterControlsHtml()}
`,
});
window.downloadAsPdf();
expect(printCalled).toBe(true);
expect(document.querySelector('.pdf-print-header')).not.toBeNull();
expect(document.querySelector('.pdf-print-footer')).not.toBeNull();
expect(document.body.classList.contains('pdf-print-mode')).toBe(true);
});
test('cleanup removes header/footer after afterprint event', () => {
window.print = () => {};
loadScript({ bodyHtml: filterControlsHtml() });
window.downloadAsPdf();
// Fire afterprint / afterprint を発火
window.dispatchEvent(new Event('afterprint'));
expect(document.querySelector('.pdf-print-header')).toBeNull();
expect(document.querySelector('.pdf-print-footer')).toBeNull();
expect(document.body.classList.contains('pdf-print-mode')).toBe(false);
});
});
// ─── downloadReviewed ───────────────────────────────────────────────────────
// レビュー済み HTML ダウンロードテスト
describe('downloadReviewed', () => {
test('produces reviewed HTML with embedded state and SHA256 hash', async () => {
// Mock crypto.subtle.digest / crypto.subtle.digest をモック
const fakeHash = new Uint8Array(32);
for (let i = 0; i < 32; i++) fakeHash[i] = i;
const origDigest = crypto.subtle && crypto.subtle.digest;
if (!crypto.subtle) {
Object.defineProperty(globalThis, 'crypto', {
value: { subtle: { digest: async () => fakeHash.buffer } },
writable: true,
configurable: true,
});
} else {
crypto.subtle.digest = async () => fakeHash.buffer;
}
const origCreateObjectURL = URL.createObjectURL;
const origRevokeObjectURL = URL.revokeObjectURL;
const origClick = HTMLAnchorElement.prototype.click;
const origBlob = globalThis.Blob;
const createdBlobs = [];
globalThis.Blob = class {
constructor(parts, options = {}) {
this.parts = parts;
this.type = options.type || '';
}
};
URL.createObjectURL = blob => {
createdBlobs.push(blob);
return 'blob:reviewed';
};
URL.revokeObjectURL = () => {};
let downloadedFiles = [];
HTMLAnchorElement.prototype.click = function() {
downloadedFiles.push(this.download);
};
loadScript({
storageKey: 'review-dl-test',
reportDate: '20260101',
bodyHtml: `
<style>:root { --col-reason-w: 10em; --col-notes-w: 10em; --col-path-w: 22em; --col-ts-w: 29em; --col-diff-w: 10.8em; --col-tag-w: 14em; --col-disasm-w: 28em; --col-sdk-w: 14em; --sc-class-w: 14em; --sc-basetype-w: 16em; --sc-type-w: 12em; --sc-name-w: 10em; --sc-rettype-w: 12em; --sc-params-w: 18em; --sc-body-w: 5em; --dc-refs-w: 16em; }</style>
<!--CTRL--><button>Download</button><!--/CTRL-->
<input type="checkbox" id="cb_mod_1" checked />
<input type="text" id="note_1" value="ok" />
<div class="filter-zone">
<button id="filter-zone-toggle" aria-expanded="true">Filters and legends</button>
<div id="filter-zone-content">${filterControlsHtml()}</div>
</div>
`,
});
document.documentElement.style.setProperty('--col-ts-w', '27em');
localStorage.setItem('review-dl-test-filter-zone-collapsed', 'false');
const liveZone = document.querySelector('.filter-zone');
const liveContent = document.getElementById('filter-zone-content');
const liveToggle = document.getElementById('filter-zone-toggle');
expect(liveZone.classList.contains('filter-zone-collapsed')).toBe(false);
expect(liveContent.hidden).toBe(false);
expect(liveToggle.getAttribute('aria-expanded')).toBe('true');
await window.downloadReviewed();
// Should have triggered at least one download / 少なくとも1つのダウンロードがトリガーされるはず
expect(downloadedFiles.length).toBeGreaterThanOrEqual(1);
expect(downloadedFiles[0]).toContain('reviewed.html');
const reviewedHtml = createdBlobs[0].parts.join('');
expect(reviewedHtml).toContain('--col-ts-w: 27em;');
const reviewedDoc = new DOMParser().parseFromString(reviewedHtml, 'text/html');
expect(reviewedDoc.querySelector('.filter-zone').classList.contains('filter-zone-collapsed')).toBe(false);
expect(reviewedDoc.getElementById('filter-zone-content').hidden).toBe(false);
expect(reviewedDoc.getElementById('filter-zone-toggle').getAttribute('aria-expanded')).toBe('true');
expect(liveZone.classList.contains('filter-zone-collapsed')).toBe(false);
expect(liveContent.hidden).toBe(false);
expect(liveToggle.getAttribute('aria-expanded')).toBe('true');
expect(localStorage.getItem('review-dl-test-filter-zone-collapsed')).toBe('false');
globalThis.Blob = origBlob;
HTMLAnchorElement.prototype.click = origClick;
URL.createObjectURL = origCreateObjectURL;
URL.revokeObjectURL = origRevokeObjectURL;
if (origDigest) crypto.subtle.digest = origDigest;
});
test('expands filters and legends only in the reviewed HTML clone', async () => {
const fakeHash = new Uint8Array(32);
fakeHash.fill(42);
const origDigest = crypto.subtle && crypto.subtle.digest;
if (!crypto.subtle) {
Object.defineProperty(globalThis, 'crypto', {
value: { subtle: { digest: async () => fakeHash.buffer } },
writable: true,
configurable: true,
});
} else {
crypto.subtle.digest = async () => fakeHash.buffer;
}
const origCreateObjectURL = URL.createObjectURL;
const origRevokeObjectURL = URL.revokeObjectURL;
const origClick = HTMLAnchorElement.prototype.click;
const origBlob = globalThis.Blob;
const createdBlobs = [];
globalThis.Blob = class {
constructor(parts, options = {}) {
this.parts = parts;
this.type = options.type || '';
}
};
URL.createObjectURL = blob => {
createdBlobs.push(blob);
return 'blob:reviewed-collapsed';
};
URL.revokeObjectURL = () => {};
HTMLAnchorElement.prototype.click = function() {};
loadScript({
storageKey: 'review-dl-collapsed-test',
reportDate: '20260103',
bodyHtml: `
<style>:root { --col-reason-w: 10em; --col-notes-w: 10em; --col-path-w: 22em; --col-ts-w: 29em; --col-diff-w: 10.8em; --col-tag-w: 14em; --col-disasm-w: 28em; --col-sdk-w: 14em; --sc-class-w: 14em; --sc-basetype-w: 16em; --sc-type-w: 12em; --sc-name-w: 10em; --sc-rettype-w: 12em; --sc-params-w: 18em; --sc-body-w: 5em; --dc-refs-w: 16em; }</style>
<script>
const __savedState__ = null;
const __reviewedSha256__ = null;
const __finalSha256__ = null;
</script>
<!--CTRL--><button>Download</button><!--/CTRL-->
<input type="checkbox" id="cb_mod_1" checked />
<textarea id="note_1">reviewed note</textarea>
<details id="diff-detail" open><summary>Diff</summary><p>detail</p></details>
<table><tbody>
<tr id="hidden-row" class="filter-hidden" data-section="mod" data-diff="SHA256Mismatch"><td>row</td></tr>
<tr id="hidden-parent" class="filter-hidden-parent"><td>detail row</td></tr>
</tbody></table>
<div class="filter-zone filter-zone-collapsed">
<button id="filter-zone-toggle" aria-expanded="false">Filters and legends</button>
<div id="filter-zone-content" hidden>${filterControlsHtml()}</div>
</div>
`,
});
localStorage.setItem('review-dl-collapsed-test-filter-zone-collapsed', 'true');
const liveZone = document.querySelector('.filter-zone');
const liveContent = document.getElementById('filter-zone-content');
const liveToggle = document.getElementById('filter-zone-toggle');
expect(liveZone.classList.contains('filter-zone-collapsed')).toBe(true);
expect(liveContent.hidden).toBe(true);
expect(liveToggle.getAttribute('aria-expanded')).toBe('false');
await window.downloadReviewed();
const reviewedHtml = createdBlobs[0].parts.join('');
const reviewedDoc = new DOMParser().parseFromString(reviewedHtml, 'text/html');
expect(reviewedDoc.querySelector('.filter-zone').classList.contains('filter-zone-collapsed')).toBe(false);
expect(reviewedDoc.getElementById('filter-zone-content').hidden).toBe(false);
expect(reviewedDoc.getElementById('filter-zone-toggle').getAttribute('aria-expanded')).toBe('true');
expect(reviewedDoc.getElementById('diff-detail').open).toBe(false);
expect(reviewedDoc.querySelector('tr.filter-hidden')).toBeNull();
expect(reviewedDoc.querySelector('tr.filter-hidden-parent')).toBeNull();
expect(reviewedHtml).toContain('decodeEmbeddedState(');
expect(reviewedHtml).toMatch(/const __reviewedSha256__ = '[0-9a-f]{64}';/);