-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff-viewer.js
More file actions
1547 lines (1372 loc) · 61.3 KB
/
diff-viewer.js
File metadata and controls
1547 lines (1372 loc) · 61.3 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
// =============================================================================
// modcore Source Diff - diff-viewer.js
// =============================================================================
// ---------------------------------------------------------------------------
// FILE TYPE MAPS (inherited from modcore Source)
// ---------------------------------------------------------------------------
const LANG_MAP = {
js: 'javascript', mjs: 'javascript', cjs: 'javascript',
jsx: 'javascript', ts: 'typescript', tsx: 'typescript',
json: 'json', json5: 'json',
css: 'css', scss: 'scss', sass: 'scss', less: 'less',
html: 'html', htm: 'html', xhtml: 'html',
xml: 'xml', svg: 'xml',
md: 'markdown', markdown: 'markdown',
py: 'python', rb: 'ruby', php: 'php',
java: 'java', c: 'c', cpp: 'cpp', cs: 'csharp',
go: 'go', rs: 'rust', swift: 'swift', kt: 'kotlin',
sh: 'shell', bash: 'shell', zsh: 'shell',
yaml: 'yaml', yml: 'yaml',
toml: 'ini', ini: 'ini', conf: 'ini',
sql: 'sql', graphql: 'graphql', gql: 'graphql',
txt: 'plaintext', log: 'plaintext',
wasm: '__binary__', map: 'json',
};
const IMAGE_EXTS = new Set(['png','jpg','jpeg','gif','webp','ico','bmp','tiff','tif','avif','svg','cur']);
const AUDIO_EXTS = new Set(['mp3','ogg','wav','flac','aac','m4a','opus','weba']);
const VIDEO_EXTS = new Set(['mp4','webm','ogv','mov','avi','mkv','m4v']);
const FONT_EXTS = new Set(['woff','woff2','ttf','otf','eot']);
const BINARY_EXTS = new Set(['wasm','bin','dat','db','pak','pyc','class','so','dll','exe']);
const MEDIA_EXTS = new Set([...IMAGE_EXTS, ...AUDIO_EXTS, ...VIDEO_EXTS, ...FONT_EXTS]);
const BINARY_LIMIT = 2 * 1024 * 1024;
const IMAGE_MIME = { png:'image/png', jpg:'image/jpeg', jpeg:'image/jpeg', gif:'image/gif', webp:'image/webp', ico:'image/x-icon', bmp:'image/bmp', tiff:'image/tiff', tif:'image/tiff', avif:'image/avif', svg:'image/svg+xml', cur:'image/x-win-bitmap' };
const AUDIO_MIME = { mp3:'audio/mpeg', ogg:'audio/ogg', wav:'audio/wav', flac:'audio/flac', aac:'audio/aac', m4a:'audio/mp4', opus:'audio/ogg; codecs=opus', weba:'audio/webm' };
const VIDEO_MIME = { mp4:'video/mp4', webm:'video/webm', ogv:'video/ogg', mov:'video/quicktime', avi:'video/x-msvideo', mkv:'video/x-matroska', m4v:'video/mp4' };
const FONT_MIME = { woff:'font/woff', woff2:'font/woff2', ttf:'font/ttf', otf:'font/otf', eot:'application/vnd.ms-fontobject' };
// ---------------------------------------------------------------------------
// DIFF STATUS CONSTANTS
// ---------------------------------------------------------------------------
const STATUS = { ADDED: 'added', REMOVED: 'removed', MODIFIED: 'modified', SAME: 'same' };
// ---------------------------------------------------------------------------
// STATE
// ---------------------------------------------------------------------------
const state = {
pkgA: null, // { zip, fileMap, manifest, name }
pkgB: null, // { zip, fileMap, manifest, name }
diffMap: {}, // path -> { status, fileA, fileB }
allPaths: [], // sorted union of all paths
activePath: null,
monacoLoaded: false,
monacoDiffEditor: null,
singleEditor: null,
mediaZoom: 1,
currentFilter: 'all',
diffMode: 'side', // 'side' | 'inline'
wrapEnabled: false,
changesOnlyMode: false,
activeBlobUrls: [],
currentChanges: [], // list of diff change objects for navigation
currentChangeIdx: -1,
};
// ---------------------------------------------------------------------------
// DOM CACHE
// ---------------------------------------------------------------------------
const $ = id => document.getElementById(id);
const el = {};
function cacheElements() {
const ids = [
'fileTree','diffTree','treePlaceholder',
'crxInputA','crxInputB','dropZoneA','dropZoneB','heroDiffBtn',
'searchBox','filterRow','filterCount',
'sidebarMeta','fileCountLabel','collapseAllBtn',
'fileStatusPanel','infoStatus','infoSizeA','infoSizeB','infoLines',
'headerVersions','headerVerA','headerVerB',
'diffModeToggle','modeSideBySide','modeInline',
'filterToggle','showChangesOnly',
'statsBtn','resetBtn',
'editorToolbar','activeStatusBadge','filePathDisplay',
'prevChangeBtn','nextChangeBtn','changeCounter','changeSep',
'formatBtn','wrapBtn','copyDiffBtn',
'viewerContainer',
'welcomeScreen','noFileSelected',
'monacoDiffHost','singleFileViewer','singleFileHeader','singleMonacoHost',
'mediaDiffViewer','mediaLabelA','mediaLabelB',
'mediaContainerLeft','mediaContainerRight',
'mediaSizeLeft','mediaSizeRight',
'mediaZoomIn','mediaZoomOut','mediaZoomReset','mediaZoomDisplay',
'binaryDiffViewer',
'binaryIconLeft','binaryNameLeft','binarySizeLeft',
'binaryIconRight','binaryNameRight','binarySizeRight','binaryDiffMsg',
'statsPanel','statsContent',
'statusDot','statusMsg','diffSummaryBar',
'diffAddedCount','diffRemovedCount','diffModifiedCount','langDisplay','cursorInfo',
'contextMenu','ctxDiffFile','ctxViewLeft','ctxViewRight','ctxCopyPath',
'loadingOverlay','loadingMsg',
'toast','toastMsg','toastIcon',
'resizeHandle', 'mainContent', 'sidebar',
];
ids.forEach(id => {
el[id] = $(id);
if (!el[id]) console.warn(`Missing #${id}`);
});
}
// ---------------------------------------------------------------------------
// INIT
// ---------------------------------------------------------------------------
window.addEventListener('load', async () => {
cacheElements();
await loadMonaco();
initEventListeners();
initResizeHandle();
});
// ---------------------------------------------------------------------------
// MONACO SETUP
// ---------------------------------------------------------------------------
async function loadMonaco() {
return new Promise(resolve => {
require.config({ paths: { vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.44.0/min/vs' } });
require(['vs/editor/editor.main'], () => {
monaco.editor.defineTheme('crx-dark', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: '', foreground: 'd4d4d4', background: '000000' },
{ token: 'comment', foreground: '4b5563', fontStyle: 'italic' },
{ token: 'keyword', foreground: '60a5fa' },
{ token: 'string', foreground: '86efac' },
{ token: 'number', foreground: 'fcd34d' },
{ token: 'regexp', foreground: 'fb923c' },
{ token: 'type', foreground: 'a78bfa' },
{ token: 'function', foreground: '60a5fa' },
{ token: 'variable', foreground: 'e2e8f0' },
{ token: 'constant', foreground: 'fbbf24' },
{ token: 'delimiter', foreground: '64748b' },
{ token: 'tag', foreground: '60a5fa' },
{ token: 'attribute.name', foreground: '86efac' },
{ token: 'attribute.value', foreground: 'fcd34d' },
{ token: 'operator', foreground: '94a3b8' },
],
colors: {
'editor.background': '#000000',
'editor.foreground': '#d4d4d4',
'editor.lineHighlightBackground': '#0a0a0a',
'editor.selectionBackground': '#1d4ed840',
'editorLineNumber.foreground': '#27272a',
'editorLineNumber.activeForeground': '#52525b',
'editorCursor.foreground': '#3b82f6',
'editorGutter.background': '#000000',
'diffEditor.insertedTextBackground': '#14532d40',
'diffEditor.removedTextBackground': '#450a0a40',
'diffEditor.insertedLineBackground': '#14532d30',
'diffEditor.removedLineBackground': '#450a0a30',
'diffEditor.diagonalFill': '#1f2937',
'editorWidget.background': '#0a0a0a',
'editorWidget.border': '#1f2937',
'input.background': '#0a0a0a',
'input.border': '#1f2937',
'scrollbarSlider.background': '#1f2937aa',
'minimap.background': '#000000',
}
});
// Diff editor
state.monacoDiffEditor = monaco.editor.createDiffEditor(el.monacoDiffHost, {
theme: 'crx-dark',
readOnly: true,
fontSize: 13,
fontFamily: "'Geist Mono', monospace",
fontLigatures: true,
lineNumbers: 'on',
minimap: { enabled: true },
scrollBeyondLastLine: false,
wordWrap: 'off',
automaticLayout: true,
renderSideBySide: true,
ignoreTrimWhitespace: false,
originalEditable: false,
smoothScrolling: true,
padding: { top: 8, bottom: 8 },
contextmenu: false,
});
// Single file editor (for added / removed)
state.singleEditor = monaco.editor.create(el.singleMonacoHost, {
theme: 'crx-dark',
readOnly: true,
fontSize: 13,
fontFamily: "'Geist Mono', monospace",
fontLigatures: true,
lineNumbers: 'on',
minimap: { enabled: false },
scrollBeyondLastLine: false,
wordWrap: 'off',
automaticLayout: true,
smoothScrolling: true,
padding: { top: 8, bottom: 8 },
contextmenu: false,
});
state.singleEditor.onDidChangeCursorPosition(e => {
el.cursorInfo.textContent = `Ln ${e.position.lineNumber}, Col ${e.position.column}`;
});
state.monacoLoaded = true;
resolve();
});
});
}
// ---------------------------------------------------------------------------
// EVENT LISTENERS
// ---------------------------------------------------------------------------
function initEventListeners() {
// File inputs
el.crxInputA.addEventListener('change', e => { const f = e.target.files[0]; if (f) loadPackage(f, 'A'); el.crxInputA.value = ''; });
el.crxInputB.addEventListener('change', e => { const f = e.target.files[0]; if (f) loadPackage(f, 'B'); el.crxInputB.value = ''; });
// Drop zones
[el.dropZoneA, el.dropZoneB].forEach(zone => {
zone.addEventListener('click', () => {
(zone.id === 'dropZoneA' ? el.crxInputA : el.crxInputB).click();
});
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
e.preventDefault();
zone.classList.remove('drag-over');
const f = e.dataTransfer.files[0];
if (f) loadPackage(f, zone.dataset.side);
});
});
// Also accept global drops
document.body.addEventListener('dragover', e => e.preventDefault());
document.body.addEventListener('drop', e => { e.preventDefault(); });
el.heroDiffBtn.addEventListener('click', runDiff);
// Header controls
el.modeSideBySide.addEventListener('click', () => setDiffMode('side'));
el.modeInline.addEventListener('click', () => setDiffMode('inline'));
el.showChangesOnly.addEventListener('click', toggleChangesOnly);
el.statsBtn.addEventListener('click', showStatsPanel);
el.resetBtn.addEventListener('click', resetAll);
// Toolbar
el.wrapBtn.addEventListener('click', toggleWrap);
el.formatBtn.addEventListener('click', formatCurrentFile);
el.copyDiffBtn.addEventListener('click', copyPatch);
el.prevChangeBtn.addEventListener('click', () => navigateChange(-1));
el.nextChangeBtn.addEventListener('click', () => navigateChange(1));
// Search
let searchTimer;
el.searchBox.addEventListener('input', e => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => filterDiffTree(e.target.value), 200);
});
el.searchBox.addEventListener('keydown', e => {
if (e.key === 'Escape') { el.searchBox.value = ''; filterDiffTree(''); }
});
// Filter tabs
document.querySelectorAll('.filter-tab').forEach(btn => {
btn.addEventListener('click', () => {
state.currentFilter = btn.dataset.filter;
document.querySelectorAll('.filter-tab').forEach(b => b.classList.toggle('active', b === btn));
applyFilter();
});
});
el.collapseAllBtn.addEventListener('click', collapseAll);
// Media zoom
el.mediaZoomIn.addEventListener('click', () => adjustMediaZoom(0.15));
el.mediaZoomOut.addEventListener('click', () => adjustMediaZoom(-0.15));
el.mediaZoomReset.addEventListener('click', () => { state.mediaZoom = 1; applyMediaZoom(); });
// Context menu
document.addEventListener('click', () => el.contextMenu.classList.add('hidden'));
el.contextMenu.addEventListener('click', e => e.stopPropagation());
el.ctxDiffFile.addEventListener('click', () => {
if (state._ctxPath) openFileDiff(state._ctxPath);
el.contextMenu.classList.add('hidden');
});
el.ctxViewLeft.addEventListener('click', () => {
if (state._ctxPath) openFileDiff(state._ctxPath, 'A');
el.contextMenu.classList.add('hidden');
});
el.ctxViewRight.addEventListener('click', () => {
if (state._ctxPath) openFileDiff(state._ctxPath, 'B');
el.contextMenu.classList.add('hidden');
});
el.ctxCopyPath.addEventListener('click', () => {
if (state._ctxPath) navigator.clipboard.writeText(state._ctxPath);
el.contextMenu.classList.add('hidden');
showToast('Path copied', 'green');
});
}
// ---------------------------------------------------------------------------
// SIDEBAR RESIZE
// ---------------------------------------------------------------------------
function initResizeHandle() {
let dragging = false, startX = 0, startW = 0;
el.resizeHandle.addEventListener('mousedown', e => {
dragging = true;
startX = e.clientX;
startW = el.sidebar.offsetWidth;
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
});
document.addEventListener('mousemove', e => {
if (!dragging) return;
const newW = Math.max(200, Math.min(600, startW + e.clientX - startX));
el.sidebar.style.width = newW + 'px';
});
document.addEventListener('mouseup', () => {
if (!dragging) return;
dragging = false;
document.body.style.cursor = '';
document.body.style.userSelect = '';
});
}
// ---------------------------------------------------------------------------
// CRX LOADING
// ---------------------------------------------------------------------------
async function loadPackage(file, side) {
if (!file.name.toLowerCase().endsWith('.crx')) {
showToast('Only .crx files are supported', 'red');
return;
}
setLoading(true, `Parsing Package ${side}…`);
await tick();
try {
const buffer = await file.arrayBuffer();
const zipBuf = parseCrxBuffer(buffer);
const zip = await JSZip.loadAsync(zipBuf);
const fileMap = {};
for (const path of Object.keys(zip.files)) {
if (!zip.files[path].dir) fileMap[path] = zip.files[path];
}
let manifest = null;
if (fileMap['manifest.json']) {
try { manifest = JSON.parse(await fileMap['manifest.json'].async('string')); } catch (_) {}
}
const pkg = { zip, fileMap, manifest, name: file.name };
state[`pkg${side}`] = pkg;
// Update drop zone appearance
const zone = side === 'A' ? el.dropZoneA : el.dropZoneB;
zone.classList.add('loaded');
zone.innerHTML = `
<div class="w-8 h-8 bg-green-950 rounded-lg flex items-center justify-center">
<i class="fa-solid fa-check text-sm text-green-500"></i>
</div>
<div class="text-center">
<p class="text-[11px] text-white font-semibold">${file.name}</p>
<p class="text-[10px] text-zinc-500 font-mono">${Object.keys(fileMap).length} files ${manifest ? `· v${manifest.version || '?'}` : ''}</p>
</div>
`;
// Show Diff button if both loaded
if (state.pkgA && state.pkgB) {
el.heroDiffBtn.classList.remove('hidden');
el.heroDiffBtn.classList.add('flex');
}
setStatus(`Package ${side} loaded - ${Object.keys(fileMap).length} files`, 'green');
showToast(`Package ${side} loaded`, 'green');
} catch (err) {
console.error(err);
showToast(`Failed to load Package ${side}`, 'red');
} finally {
setLoading(false);
}
}
function parseCrxBuffer(buffer) {
const view = new DataView(buffer);
const bytes = new Uint8Array(buffer);
if (view.byteLength < 4) return buffer;
const magic = String.fromCharCode(bytes[0], bytes[1], bytes[2], bytes[3]);
if (magic !== 'Cr24') return buffer;
const version = view.getUint32(4, true);
if (version === 2) {
const pubLen = view.getUint32(8, true);
const sigLen = view.getUint32(12, true);
return buffer.slice(16 + pubLen + sigLen);
} else if (version === 3) {
const hLen = view.getUint32(8, true);
return buffer.slice(12 + hLen);
}
return buffer;
}
// ---------------------------------------------------------------------------
// DIFF ENGINE
// ---------------------------------------------------------------------------
async function runDiff() {
if (!state.pkgA || !state.pkgB) {
showToast('Load both packages first', 'red');
return;
}
setLoading(true, 'Computing diff…');
await tick();
try {
const pathsA = new Set(Object.keys(state.pkgA.fileMap));
const pathsB = new Set(Object.keys(state.pkgB.fileMap));
const allPaths = [...new Set([...pathsA, ...pathsB])].sort();
state.diffMap = {};
state.allPaths = allPaths;
for (const path of allPaths) {
const inA = pathsA.has(path);
const inB = pathsB.has(path);
if (inA && !inB) {
state.diffMap[path] = { status: STATUS.REMOVED, fileA: state.pkgA.fileMap[path], fileB: null };
} else if (!inA && inB) {
state.diffMap[path] = { status: STATUS.ADDED, fileA: null, fileB: state.pkgB.fileMap[path] };
} else {
// Both exist - compare hashes
const bufA = await state.pkgA.fileMap[path].async('uint8array');
const bufB = await state.pkgB.fileMap[path].async('uint8array');
const same = arraysEqual(bufA, bufB);
state.diffMap[path] = {
status: same ? STATUS.SAME : STATUS.MODIFIED,
fileA: state.pkgA.fileMap[path],
fileB: state.pkgB.fileMap[path],
};
}
}
buildDiffTree();
showDiffUI();
const addedC = allPaths.filter(p => state.diffMap[p].status === STATUS.ADDED).length;
const removedC = allPaths.filter(p => state.diffMap[p].status === STATUS.REMOVED).length;
const modC = allPaths.filter(p => state.diffMap[p].status === STATUS.MODIFIED).length;
const sameC = allPaths.filter(p => state.diffMap[p].status === STATUS.SAME).length;
setStatus(`Diff complete - ${modC} changed, ${addedC} added, ${removedC} removed, ${sameC} same`, 'green');
showToast('Diff complete', 'green');
// Status bar summary
el.diffSummaryBar.classList.remove('hidden');
el.diffSummaryBar.classList.add('flex');
el.diffAddedCount.textContent = `+${addedC}`;
el.diffRemovedCount.textContent = `-${removedC}`;
el.diffModifiedCount.textContent = `~${modC}`;
// Header version badges
const mA = state.pkgA.manifest, mB = state.pkgB.manifest;
el.headerVerA.textContent = (mA && mA.version) ? `A v${mA.version}` : 'A';
el.headerVerB.textContent = (mB && mB.version) ? `B v${mB.version}` : 'B';
el.headerVersions.classList.remove('hidden');
el.headerVersions.classList.add('flex');
// Auto-open first changed file
const firstChanged = allPaths.find(p =>
state.diffMap[p].status === STATUS.MODIFIED ||
state.diffMap[p].status === STATUS.ADDED ||
state.diffMap[p].status === STATUS.REMOVED
);
if (firstChanged) openFileDiff(firstChanged);
else {
hideAllViewers();
el.noFileSelected.classList.remove('hidden');
}
} catch (err) {
console.error(err);
showToast('Diff failed', 'red');
setStatus('Error', 'red');
} finally {
setLoading(false);
}
}
function arraysEqual(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
// ---------------------------------------------------------------------------
// DIFF UI SETUP
// ---------------------------------------------------------------------------
function showDiffUI() {
el.treePlaceholder.classList.add('hidden');
el.diffTree.classList.remove('hidden');
el.filterRow.classList.remove('hidden');
el.filterRow.classList.add('flex');
el.sidebarMeta.classList.remove('hidden');
el.fileCountLabel.textContent = `${state.allPaths.length} files`;
el.diffModeToggle.classList.remove('hidden');
el.diffModeToggle.classList.add('flex');
el.filterToggle.classList.remove('hidden');
el.filterToggle.classList.add('flex');
el.statsBtn.classList.remove('hidden');
el.statsBtn.classList.add('flex');
el.resetBtn.classList.remove('hidden');
el.resetBtn.classList.add('flex');
el.welcomeScreen.classList.add('hidden');
el.noFileSelected.classList.remove('hidden');
updateDiffModeButtons();
applyFilter();
}
// ---------------------------------------------------------------------------
// DIFF TREE
// ---------------------------------------------------------------------------
function buildDiffTree() {
el.diffTree.innerHTML = '';
// Build a virtual folder tree
const root = { isDir: true, children: {}, name: '', path: '' };
for (const path of state.allPaths) {
const parts = path.split('/');
let node = root;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (!node.children[part]) {
const isDir = i < parts.length - 1;
node.children[part] = {
isDir,
name: part,
path: parts.slice(0, i + 1).join('/'),
children: {},
filePath: isDir ? null : path,
};
}
node = node.children[part];
}
}
renderDiffNodes(root.children, el.diffTree, 0);
}
function getStatusForDir(dirPath) {
// Returns compound status for a folder
const relevant = state.allPaths.filter(p => p.startsWith(dirPath + '/') || p === dirPath);
const statuses = relevant.map(p => state.diffMap[p]?.status);
if (statuses.includes(STATUS.ADDED)) return STATUS.ADDED;
if (statuses.includes(STATUS.REMOVED)) return STATUS.REMOVED;
if (statuses.includes(STATUS.MODIFIED)) return STATUS.MODIFIED;
return STATUS.SAME;
}
function renderDiffNodes(children, parentEl, depth) {
const ul = document.createElement('ul');
ul.className = depth === 0 ? 'space-y-px' : 'pl-3 border-l border-zinc-900 ml-2 space-y-px';
const sorted = Object.keys(children).sort((a, b) => {
const ad = children[a].isDir, bd = children[b].isDir;
if (ad !== bd) return ad ? -1 : 1;
return a.localeCompare(b, undefined, { sensitivity: 'base' });
});
sorted.forEach(key => {
const item = children[key];
const li = document.createElement('li');
li.dataset.treePath = item.path;
const status = item.isDir
? getStatusForDir(item.path)
: (state.diffMap[item.filePath]?.status || STATUS.SAME);
const statusColor = {
[STATUS.ADDED]: 'diff-added',
[STATUS.REMOVED]: 'diff-removed',
[STATUS.MODIFIED]: 'diff-modified',
[STATUS.SAME]: 'diff-same',
}[status] || 'diff-same';
const row = document.createElement('div');
row.className = `flex items-center gap-1.5 px-2 py-1 rounded cursor-pointer text-xs hover:bg-zinc-950 transition-colors group`;
row.dataset.path = item.path;
if (item.filePath) row.dataset.filePath = item.filePath;
row.setAttribute('tabindex', '0');
// Status dot
if (!item.isDir) {
const dot = document.createElement('span');
dot.className = `w-1.5 h-1.5 rounded-full flex-shrink-0 ${
status === STATUS.ADDED ? 'bg-green-500' :
status === STATUS.REMOVED ? 'bg-red-500' :
status === STATUS.MODIFIED ? 'bg-yellow-500' :
'bg-zinc-800'
}`;
row.appendChild(dot);
} else {
const icon = document.createElement('i');
icon.className = `fa-solid fa-folder text-blue-500 text-[11px] flex-shrink-0 w-3.5 text-center`;
icon.dataset.icon = 'folder';
row.appendChild(icon);
}
// Name
const nameSpan = document.createElement('span');
nameSpan.className = `truncate ${statusColor}`;
nameSpan.textContent = item.name;
row.appendChild(nameSpan);
// Size delta badge for modified files
if (!item.isDir && status === STATUS.MODIFIED) {
const diff = state.diffMap[item.filePath];
if (diff.fileA && diff.fileB) {
const sA = diff.fileA._data?.uncompressedSize || 0;
const sB = diff.fileB._data?.uncompressedSize || 0;
const delta = sB - sA;
if (delta !== 0) {
const badge = document.createElement('span');
badge.className = `ml-auto text-[9px] font-mono flex-shrink-0 ${delta > 0 ? 'text-green-800' : 'text-red-800'}`;
badge.textContent = (delta > 0 ? '+' : '') + formatBytes(delta);
row.appendChild(badge);
}
}
}
// Status label for added/removed
if (!item.isDir && (status === STATUS.ADDED || status === STATUS.REMOVED)) {
const lbl = document.createElement('span');
lbl.className = `ml-auto text-[9px] font-mono flex-shrink-0 ${status === STATUS.ADDED ? 'text-green-800' : 'text-red-800'}`;
lbl.textContent = status === STATUS.ADDED ? 'new' : 'del';
row.appendChild(lbl);
}
// Context menu
row.addEventListener('contextmenu', e => {
e.preventDefault();
if (item.isDir) return;
state._ctxPath = item.filePath;
const status = state.diffMap[item.filePath]?.status;
el.ctxViewLeft.style.display = status === STATUS.ADDED ? 'none' : '';
el.ctxViewRight.style.display = status === STATUS.REMOVED ? 'none' : '';
el.contextMenu.style.top = `${Math.min(e.clientY, window.innerHeight - 160)}px`;
el.contextMenu.style.left = `${Math.min(e.clientX, window.innerWidth - 200)}px`;
el.contextMenu.classList.remove('hidden');
});
if (item.isDir) {
const childContainer = document.createElement('div');
childContainer.className = 'hidden';
renderDiffNodes(item.children, childContainer, depth + 1);
li.appendChild(row);
li.appendChild(childContainer);
const toggle = () => {
const collapsed = childContainer.classList.contains('hidden');
childContainer.classList.toggle('hidden');
const icon = row.querySelector('[data-icon="folder"]');
if (icon) icon.className = `fa-solid ${collapsed ? 'fa-folder-open text-blue-400' : 'fa-folder text-blue-500'} text-[11px] flex-shrink-0 w-3.5 text-center`;
};
row.addEventListener('click', toggle);
row.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); }
});
} else {
li.appendChild(row);
row.addEventListener('click', () => openFileDiff(item.filePath));
row.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openFileDiff(item.filePath); }
});
}
ul.appendChild(li);
});
parentEl.appendChild(ul);
}
// ---------------------------------------------------------------------------
// FILTER & SEARCH
// ---------------------------------------------------------------------------
function applyFilter() {
const allLIs = Array.from(el.diffTree.querySelectorAll('li[data-tree-path]'));
const filter = state.currentFilter;
const query = el.searchBox.value.toLowerCase().trim();
let visible = 0;
allLIs.forEach(li => {
const filePath = li.querySelector('[data-file-path]')?.dataset?.filePath ||
li.querySelector('[data-path]')?.dataset?.path;
const isDir = !li.querySelector('[data-file-path]') && li.querySelector('[data-path]');
if (isDir) return; // Folders handled by their children
const fp = li.querySelector('[data-file-path]')?.dataset?.filePath;
if (!fp) return;
const status = state.diffMap[fp]?.status;
const nameMatch = !query || fp.toLowerCase().includes(query);
const filterMatch = filter === 'all' || status === filter;
const show = nameMatch && filterMatch;
li.style.display = show ? '' : 'none';
if (show) visible++;
});
// Show/hide parent folders
el.diffTree.querySelectorAll('li[data-tree-path]').forEach(li => {
const child = li.querySelector(':scope > div:not([data-path])');
if (!child) return;
const hasVisible = Array.from(child.querySelectorAll('li[data-tree-path]')).some(c => c.style.display !== 'none');
li.style.display = hasVisible ? '' : 'none';
});
el.filterCount.textContent = filter !== 'all' ? `${visible}` : '';
}
function filterDiffTree(query) {
applyFilter();
}
function collapseAll() {
el.diffTree.querySelectorAll('li > div:not([data-path])').forEach(c => c.classList.add('hidden'));
el.diffTree.querySelectorAll('[data-icon="folder"]').forEach(i => {
i.className = 'fa-solid fa-folder text-blue-500 text-[11px] flex-shrink-0 w-3.5 text-center';
});
}
// ---------------------------------------------------------------------------
// OPEN FILE DIFF
// ---------------------------------------------------------------------------
async function openFileDiff(path, forceView) {
if (!path || !state.diffMap[path]) return;
state.activePath = path;
const diff = state.diffMap[path];
// Highlight in tree
el.diffTree.querySelectorAll('[data-path]').forEach(n => n.classList.remove('bg-zinc-900'));
const treeRow = el.diffTree.querySelector(`[data-file-path="${CSS.escape(path)}"]`);
if (treeRow) {
treeRow.classList.add('bg-zinc-900');
treeRow.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
// Update file status panel
const sA = diff.fileA?._data?.uncompressedSize || 0;
const sB = diff.fileB?._data?.uncompressedSize || 0;
el.infoSizeA.textContent = diff.fileA ? formatBytes(sA) : '-';
el.infoSizeB.textContent = diff.fileB ? formatBytes(sB) : '-';
el.infoStatus.textContent = diff.status.toUpperCase();
el.infoStatus.className = `font-semibold ${
diff.status === STATUS.ADDED ? 'text-green-400' :
diff.status === STATUS.REMOVED ? 'text-red-400' :
diff.status === STATUS.MODIFIED ? 'text-yellow-400' :
'text-zinc-500'
}`;
el.fileStatusPanel.classList.remove('hidden');
// Show toolbar
el.editorToolbar.classList.remove('hidden');
el.filePathDisplay.textContent = path;
// Status badge
const badgeCfg = {
[STATUS.ADDED]: { text: 'ADDED', cls: 'badge-added' },
[STATUS.REMOVED]: { text: 'REMOVED', cls: 'badge-removed' },
[STATUS.MODIFIED]: { text: 'MODIFIED', cls: 'badge-modified' },
[STATUS.SAME]: { text: 'SAME', cls: 'badge-same' },
}[diff.status];
el.activeStatusBadge.textContent = badgeCfg.text;
el.activeStatusBadge.className = `px-2 py-0.5 rounded text-[10px] font-mono font-semibold flex-shrink-0 ${badgeCfg.cls}`;
const ext = path.split('.').pop().toLowerCase();
const lang = LANG_MAP[ext] || 'plaintext';
el.langDisplay.textContent = lang === 'plaintext' ? ext.toUpperCase() || 'TEXT' : lang;
// Reset change navigation
state.currentChanges = [];
state.currentChangeIdx = -1;
el.prevChangeBtn.classList.add('hidden');
el.nextChangeBtn.classList.add('hidden');
el.changeCounter.classList.add('hidden');
el.changeSep.classList.add('hidden');
el.formatBtn.classList.add('hidden');
el.copyDiffBtn.classList.add('hidden');
el.infoLines.textContent = '-';
// ── SAME file
if (diff.status === STATUS.SAME && !forceView) {
hideAllViewers();
// Show a single read-only view
el.singleFileViewer.classList.remove('hidden');
el.singleFileHeader.textContent = `Unchanged - ${path}`;
el.singleFileHeader.className = 'px-4 py-2 border-b border-zinc-900 flex-shrink-0 text-[10px] font-mono text-zinc-600';
await loadSingleEditor(diff.fileA || diff.fileB, lang);
setStatus('Unchanged', 'zinc');
return;
}
// ── MEDIA files
if (IMAGE_EXTS.has(ext) || AUDIO_EXTS.has(ext) || VIDEO_EXTS.has(ext) || FONT_EXTS.has(ext)) {
await showMediaDiff(path, diff, ext);
return;
}
// ── BINARY
if (BINARY_EXTS.has(ext) || lang === '__binary__') {
showBinaryDiff(path, diff, ext);
return;
}
// ── TEXT / CODE - use Monaco diff editor
hideAllViewers();
el.monacoDiffHost.classList.remove('hidden');
const contentA = diff.fileA ? await readFileText(diff.fileA) : '';
const contentB = diff.fileB ? await readFileText(diff.fileB) : '';
const monacoLang = lang === '__binary__' ? 'plaintext' : lang;
const origModel = monaco.editor.createModel(contentA, monacoLang);
const modModel = monaco.editor.createModel(contentB, monacoLang);
state.monacoDiffEditor.setModel({ original: origModel, modified: modModel });
state.monacoDiffEditor.updateOptions({
renderSideBySide: state.diffMode === 'side',
wordWrap: state.wrapEnabled ? 'on' : 'off',
});
// Wait for diff to compute
await tick();
await tick();
// Change navigation
const changes = state.monacoDiffEditor.getLineChanges() || [];
state.currentChanges = changes;
if (changes.length > 0) {
el.prevChangeBtn.classList.remove('hidden');
el.prevChangeBtn.classList.add('flex');
el.nextChangeBtn.classList.remove('hidden');
el.nextChangeBtn.classList.add('flex');
el.changeCounter.classList.remove('hidden');
el.changeSep.classList.remove('hidden');
updateChangeCounter();
el.infoLines.textContent = `${changes.length} hunks`;
el.copyDiffBtn.classList.remove('hidden');
el.copyDiffBtn.classList.add('flex');
}
// Format button for code files
if (['js','javascript','json','css','html','typescript'].includes(lang)) {
el.formatBtn.classList.remove('hidden');
el.formatBtn.classList.add('flex');
}
setStatus(diff.status === STATUS.MODIFIED ? `${changes.length} change${changes.length !== 1 ? 's' : ''}` : diff.status, 'green');
}
async function readFileText(file) {
const sizeData = file._data;
const size = sizeData ? (sizeData.uncompressedSize || 0) : 0;
if (size > BINARY_LIMIT) return `// File too large to preview (${formatBytes(size)})`;
try { return await file.async('string'); } catch (_) { return '// Binary or unreadable content.'; }
}
async function loadSingleEditor(file, lang) {
if (!file) return;
const content = await readFileText(file);
const monacoLang = lang === '__binary__' ? 'plaintext' : lang;
const model = monaco.editor.createModel(content, monacoLang);
state.singleEditor.setModel(model);
}
// ---------------------------------------------------------------------------
// MEDIA DIFF
// ---------------------------------------------------------------------------
async function showMediaDiff(path, diff, ext) {
hideAllViewers();
el.mediaDiffViewer.classList.remove('hidden');
state.mediaZoom = 1;
applyMediaZoom();
const name = path.split('/').pop();
el.mediaLabelA.textContent = diff.fileA ? name : '(not present)';
el.mediaLabelB.textContent = diff.fileB ? name : '(not present)';
revokeBlobs();
el.mediaContainerLeft.innerHTML = '';
el.mediaContainerRight.innerHTML = '';
el.mediaSizeLeft.textContent = '';
el.mediaSizeRight.textContent = '';
async function renderMedia(file, container, sizeEl) {
if (!file) {
container.innerHTML = '<p class="text-xs text-zinc-700 font-mono">Not present</p>';
return;
}
const sizeData = file._data;
sizeEl.textContent = sizeData ? formatBytes(sizeData.uncompressedSize || 0) : '';
if (IMAGE_EXTS.has(ext)) {
const blob = await file.async('blob');
const mime = IMAGE_MIME[ext] || 'image/png';
const url = URL.createObjectURL(new Blob([blob], { type: mime }));
trackBlob(url);
const img = document.createElement('img');
img.src = url;
img.alt = name;
img.className = 'max-w-none shadow-2xl rounded';
img.style.imageRendering = (ext === 'ico' || ext === 'cur') ? 'pixelated' : 'auto';
img.onload = () => { sizeEl.textContent += ` · ${img.naturalWidth}×${img.naturalHeight}`; };
container.appendChild(img);
} else if (AUDIO_EXTS.has(ext)) {
const blob = await file.async('blob');
const mime = AUDIO_MIME[ext] || 'audio/mpeg';
const url = URL.createObjectURL(new Blob([blob], { type: mime }));
trackBlob(url);
const wrap = document.createElement('div');
wrap.className = 'flex flex-col items-center gap-3';
wrap.innerHTML = `<div class="w-12 h-12 bg-zinc-900 rounded-xl flex items-center justify-center"><i class="fa-solid fa-music text-2xl text-blue-400"></i></div>`;
const audio = document.createElement('audio');
audio.controls = true;
audio.src = url;
audio.style = 'filter:invert(1)hue-rotate(180deg);width:200px;';
wrap.appendChild(audio);
container.appendChild(wrap);
} else if (FONT_EXTS.has(ext)) {
const wrap = document.createElement('div');
wrap.className = 'flex flex-col items-center gap-3 p-6';
wrap.innerHTML = `<i class="fa-solid fa-font text-4xl text-purple-500"></i><p class="text-xs font-mono text-zinc-500">${name}</p>`;
container.appendChild(wrap);
} else {
container.innerHTML = `<p class="text-xs text-zinc-600 font-mono">${name}</p>`;
}
}
await renderMedia(diff.fileA, el.mediaContainerLeft, el.mediaSizeLeft);
await renderMedia(diff.fileB, el.mediaContainerRight, el.mediaSizeRight);
setStatus('Media diff', 'green');
}
// ---------------------------------------------------------------------------
// BINARY DIFF
// ---------------------------------------------------------------------------
function showBinaryDiff(path, diff, ext) {
hideAllViewers();
el.binaryDiffViewer.classList.remove('hidden');
const name = path.split('/').pop();
const iconCls = FONT_EXTS.has(ext) ? 'fa-font text-purple-500' :
BINARY_EXTS.has(ext) ? 'fa-microchip text-green-500' : 'fa-file text-zinc-500';
el.binaryIconLeft.className = `fa-solid ${iconCls} text-2xl mb-2`;
el.binaryIconRight.className = `fa-solid ${iconCls} text-2xl mb-2`;
el.binaryNameLeft.textContent = diff.fileA ? name : '(not present)';
el.binaryNameRight.textContent = diff.fileB ? name : '(not present)';
const sA = diff.fileA?._data?.uncompressedSize || 0;
const sB = diff.fileB?._data?.uncompressedSize || 0;
el.binarySizeLeft.textContent = diff.fileA ? formatBytes(sA) : '';
el.binarySizeRight.textContent = diff.fileB ? formatBytes(sB) : '';
const delta = sB - sA;
if (diff.status === STATUS.SAME) {
el.binaryDiffMsg.textContent = 'Binary files are identical';
el.binaryDiffMsg.className = 'text-[11px] font-mono text-zinc-600';
} else if (diff.status === STATUS.ADDED) {
el.binaryDiffMsg.textContent = `New binary file - ${formatBytes(sB)}`;
el.binaryDiffMsg.className = 'text-[11px] font-mono text-green-700';
} else if (diff.status === STATUS.REMOVED) {
el.binaryDiffMsg.textContent = `Binary file removed - was ${formatBytes(sA)}`;
el.binaryDiffMsg.className = 'text-[11px] font-mono text-red-700';
} else {
el.binaryDiffMsg.textContent = `Binary content changed - size delta: ${delta >= 0 ? '+' : ''}${formatBytes(delta)}`;
el.binaryDiffMsg.className = `text-[11px] font-mono ${delta > 0 ? 'text-green-700' : 'text-red-700'}`;
}
setStatus('Binary diff', 'zinc');
}
// ---------------------------------------------------------------------------