-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2316 lines (2006 loc) · 71.7 KB
/
main.js
File metadata and controls
2316 lines (2006 loc) · 71.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
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
const { app, BrowserWindow, Menu, ipcMain, dialog, clipboard, screen } = require('electron');
const path = require('path');
const fs = require('fs').promises;
const packageInfo = require('./package.json');
const Diff = require('diff');
// Import modular diff system
const AlgorithmRegistry = require('./diff/core/Registry');
const algorithmRegistry = new AlgorithmRegistry();
let mainWindow;
let currentZoom = 1.0;
let config = {};
let windowState = null;
async function loadConfig() {
try {
const configPath = path.join(__dirname, 'config.json');
const configData = await fs.readFile(configPath, 'utf-8');
config = JSON.parse(configData);
} catch (error) {
console.warn('Config file not found or invalid, using defaults');
config = {
window: {
defaultWidth: 1400,
defaultHeight: 800,
minWidth: 800,
minHeight: 600
},
zoom: {
default: 1.0,
min: 0.5,
max: 3.0,
increment: 0.25
},
colors: {
left: {
defaultBgHue: 0,
defaultBgIntensity: 20,
defaultHlHue: 0,
defaultHlIntensity: 40
},
right: {
defaultBgHue: 120,
defaultBgIntensity: 20,
defaultHlHue: 120,
defaultHlIntensity: 40
},
bgIntensityMin: 5,
bgIntensityMax: 40,
hlIntensityMin: 20,
hlIntensityMax: 60
},
fuzzySentenceMatching: {
minMatchPercent: 10,
maxMatchPercent: 100,
defaultFuzzLevel: 0.00,
wordLookAheadLimit: 5
},
fuzzyParagraphMatching: {
minMatchPercent: 30,
maxMatchPercent: 100,
defaultFuzzLevel: 0.00
},
ui: {
statusBarUpdateIntervalMs: 60000,
paragraphSyncHighlightDurationMs: 600,
paragraphSyncHighlightColor: "rgba(100, 100, 255, 0.3)",
sentenceSyncHighlightColor: "rgba(100, 100, 255, 0.5)",
tooltipDisplayDurationMs: 1500
},
toolbar: {
defaultParagraphAlgorithm: "thomas",
defaultSentenceAlgorithm: "thomas",
defaultParagraphMatchingEnabled: true,
defaultSentenceMatchingEnabled: true
}
};
}
}
async function loadWindowState() {
try {
const userDataPath = app.getPath('userData');
const windowStatePath = path.join(userDataPath, 'differon-window-state.json');
const data = await fs.readFile(windowStatePath, 'utf-8');
windowState = JSON.parse(data);
// Validate that the window position is still valid (e.g., not off-screen)
const displays = screen.getAllDisplays();
const displayBounds = displays.map(d => d.bounds);
// Check if the saved position is within any display
let isValidPosition = false;
for (const display of displayBounds) {
if (windowState.x >= display.x - 100 &&
windowState.x <= display.x + display.width - 100 &&
windowState.y >= display.y - 100 &&
windowState.y <= display.y + display.height - 100) {
isValidPosition = true;
break;
}
}
if (!isValidPosition) {
// Reset to default if position is invalid
windowState = null;
}
} catch (error) {
// No saved state or error reading it
windowState = null;
}
}
async function saveWindowState() {
if (!mainWindow) return;
const bounds = mainWindow.getBounds();
const isMaximized = mainWindow.isMaximized();
const isFullScreen = mainWindow.isFullScreen();
const state = {
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
isMaximized: isMaximized,
isFullScreen: isFullScreen
};
try {
const userDataPath = app.getPath('userData');
const windowStatePath = path.join(userDataPath, 'differon-window-state.json');
await fs.writeFile(windowStatePath, JSON.stringify(state, null, 2));
} catch (error) {
// Error saving window state
}
}
function createWindow() {
// Use saved window state or defaults
const windowOptions = {
width: windowState?.width || config.window.defaultWidth,
height: windowState?.height || config.window.defaultHeight,
minWidth: config.window.minWidth,
minHeight: config.window.minHeight,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.join(__dirname, 'preload.js')
},
icon: path.join(__dirname, 'build/icon.ico')
};
// Set position if we have saved state
if (windowState && windowState.x !== undefined && windowState.y !== undefined) {
windowOptions.x = windowState.x;
windowOptions.y = windowState.y;
}
mainWindow = new BrowserWindow(windowOptions);
// Restore maximized or fullscreen state after window is shown
if (windowState) {
if (windowState.isFullScreen) {
mainWindow.setFullScreen(true);
} else if (windowState.isMaximized) {
mainWindow.maximize();
}
}
mainWindow.loadFile('index.html');
// Remove the application menu to reclaim vertical space
mainWindow.removeMenu();
// Enable F12 for DevTools and Ctrl+Shift+I
mainWindow.webContents.on('before-input-event', (event, input) => {
if (input.key === 'F12' || (input.control && input.shift && input.key === 'I')) {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
});
// Save window state on various events
let saveTimeout;
const debouncedSaveWindowState = () => {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(saveWindowState, 500);
};
mainWindow.on('resize', debouncedSaveWindowState);
mainWindow.on('move', debouncedSaveWindowState);
mainWindow.on('maximize', saveWindowState);
mainWindow.on('unmaximize', saveWindowState);
mainWindow.on('enter-full-screen', saveWindowState);
mainWindow.on('leave-full-screen', saveWindowState);
// Create application menu
const menuTemplate = [
{
label: 'File',
submenu: [
{
label: 'Open Original...',
accelerator: 'CmdOrCtrl+O',
click: async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{ name: 'Text Files', extensions: ['txt', 'md', 'js', 'html', 'css', 'json', 'xml'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (!result.canceled) {
mainWindow.webContents.send('file-opened', { side: 'left', path: result.filePaths[0] });
}
}
},
{
label: 'Open Revised...',
accelerator: 'CmdOrCtrl+Shift+O',
click: async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{ name: 'Text Files', extensions: ['txt', 'md', 'js', 'html', 'css', 'json', 'xml'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (!result.canceled) {
mainWindow.webContents.send('file-opened', { side: 'right', path: result.filePaths[0] });
}
}
},
{ type: 'separator' },
{
label: 'Open Original in New Tab...',
accelerator: 'CmdOrCtrl+Shift+T',
click: async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{ name: 'Text Files', extensions: ['txt', 'md', 'js', 'html', 'css', 'json', 'xml'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (!result.canceled) {
mainWindow.webContents.send('file-opened-new-tab', { side: 'left', path: result.filePaths[0] });
}
}
},
{
label: 'Open Revised in New Tab...',
click: async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [
{ name: 'Text Files', extensions: ['txt', 'md', 'js', 'html', 'css', 'json', 'xml'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (!result.canceled) {
mainWindow.webContents.send('file-opened-new-tab', { side: 'right', path: result.filePaths[0] });
}
}
},
{ type: 'separator' },
{
label: 'New Tab',
accelerator: 'CmdOrCtrl+T',
click: () => {
mainWindow.webContents.send('new-tab');
}
},
{
label: 'Close Tab',
accelerator: 'CmdOrCtrl+W',
click: () => {
mainWindow.webContents.send('close-tab');
}
},
{ type: 'separator' },
{
label: 'Paste Original',
accelerator: 'CmdOrCtrl+V',
click: () => {
mainWindow.webContents.send('paste-content', { side: 'left' });
}
},
{
label: 'Paste Revised',
accelerator: 'CmdOrCtrl+Shift+V',
click: () => {
mainWindow.webContents.send('paste-content', { side: 'right' });
}
},
{ type: 'separator' },
{
label: 'Exit',
accelerator: 'CmdOrCtrl+Q',
click: () => app.quit()
}
]
},
{
label: 'Edit',
submenu: [
{ label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' },
{ label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectAll' },
{ type: 'separator' },
{
label: 'Next Tab',
accelerator: 'CmdOrCtrl+Tab',
click: () => {
mainWindow.webContents.send('next-tab');
}
},
{
label: 'Previous Tab',
accelerator: 'CmdOrCtrl+Shift+Tab',
click: () => {
mainWindow.webContents.send('previous-tab');
}
}
]
},
{
label: 'View',
submenu: [
{
label: 'Zoom In',
accelerator: 'CmdOrCtrl+Plus',
click: () => {
currentZoom = Math.min(currentZoom + config.zoom.increment, config.zoom.max);
mainWindow.webContents.setZoomFactor(currentZoom);
}
},
{
label: 'Zoom Out',
accelerator: 'CmdOrCtrl+-',
click: () => {
currentZoom = Math.max(currentZoom - config.zoom.increment, config.zoom.min);
mainWindow.webContents.setZoomFactor(currentZoom);
}
},
{
label: 'Reset Zoom',
accelerator: 'CmdOrCtrl+0',
click: () => {
currentZoom = config.zoom.default;
mainWindow.webContents.setZoomFactor(currentZoom);
}
},
{ type: 'separator' },
{ label: 'Reload', accelerator: 'CmdOrCtrl+R', role: 'reload' },
{ label: 'Toggle DevTools', accelerator: 'F12', role: 'toggleDevTools' }
]
}
];
// Menu removed - keyboard shortcuts are still handled by the renderer process
// Restore state when window is ready
mainWindow.webContents.once('dom-ready', () => {
mainWindow.webContents.send('restore-state');
});
mainWindow.on('closed', () => {
mainWindow = null;
});
// Save state before closing
mainWindow.on('close', () => {
saveWindowState();
});
}
// IPC handlers for console logging to stdout
ipcMain.on('console-log', (event, ...args) => {
console.log('[Renderer]', ...args);
});
ipcMain.on('console-warn', (event, ...args) => {
console.warn('[Renderer]', ...args);
});
ipcMain.on('console-error', (event, ...args) => {
console.error('[Renderer]', ...args);
});
// IPC handlers for file operations
ipcMain.handle('read-file', async (event, filePath) => {
try {
const content = await fs.readFile(filePath, 'utf-8');
return { success: true, content, path: filePath };
} catch (error) {
return { success: false, error: error.message };
}
});
// Natural Language Diff Handlers
const nlp = require('compromise');
// Paragraph mode diff handler (exact matching only - legacy)
ipcMain.handle('diff-paragraph', async (event, leftText, rightText) => {
// Split into paragraphs - each paragraph is text between line endings
function splitParagraphs(text) {
return text
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.split('\n');
}
const leftParagraphs = splitParagraphs(leftText);
const rightParagraphs = splitParagraphs(rightText);
const diff = [];
// Implementation of the user's algorithm
let oU = 0; // First unprocessed paragraph in original (0-indexed)
let rU = 0; // First unprocessed paragraph in revised (0-indexed)
while (oU < leftParagraphs.length) {
let found = false;
// Look for exact match in remaining revised paragraphs
for (let i = rU; i < rightParagraphs.length; i++) {
if (rightParagraphs[i] === leftParagraphs[oU]) {
// Found exact match
// First, mark all revised paragraphs before the match as added
for (let j = rU; j < i; j++) {
if (rightParagraphs[j].trim()) { // Only include non-empty paragraphs
diff.push({
value: rightParagraphs[j],
added: true,
removed: false,
count: rightParagraphs[j].split(/\s+/).filter(w => w.length > 0).length
});
}
}
// Add the matching paragraph as unchanged
if (leftParagraphs[oU].trim()) { // Only include non-empty paragraphs
diff.push({
value: leftParagraphs[oU],
added: false,
removed: false
});
}
oU += 1;
rU = i + 1;
found = true;
break;
}
}
if (!found) {
// No match found - mark original paragraph as deleted
if (leftParagraphs[oU].trim()) { // Only include non-empty paragraphs
diff.push({
value: leftParagraphs[oU],
removed: true,
added: false,
count: leftParagraphs[oU].split(/\s+/).filter(w => w.length > 0).length
});
}
oU += 1;
}
}
// Mark any remaining revised paragraphs as added
while (rU < rightParagraphs.length) {
if (rightParagraphs[rU].trim()) { // Only include non-empty paragraphs
diff.push({
value: rightParagraphs[rU],
added: true,
removed: false,
count: rightParagraphs[rU].split(/\s+/).filter(w => w.length > 0).length
});
}
rU += 1;
}
return diff;
});
// Enhanced sentence mode diff handler - process paragraphs individually
ipcMain.handle('diff-sentence', async (event, leftSelectedText, rightSelectedText, leftSelectedParagraphs, rightSelectedParagraphs, leftFullText, rightFullText) => {
// Use full text if provided, otherwise parse from selected text
const leftText = leftFullText || leftSelectedText;
const rightText = rightFullText || rightSelectedText;
// Split the full text into paragraphs
const leftFullParagraphs = leftText.split(/\r\n|\r|\n/);
const rightFullParagraphs = rightText.split(/\r\n|\r|\n/);
// Get the selected paragraphs
const leftSelectedTexts = leftSelectedParagraphs.map(i => leftFullParagraphs[i] || '');
const rightSelectedTexts = rightSelectedParagraphs.map(i => rightFullParagraphs[i] || '');
// Improved sentence splitter that preserves exact text
function splitIntoSentences(text) {
if (!text.trim()) return [];
const sentences = [];
// Try multiple approaches to ensure we catch all sentences
// Approach 1: Use compromise but verify results
const doc = nlp(text);
const nlpSentences = doc.sentences().out('array');
// Approach 2: Also use regex-based splitting for better coverage
// This catches sentences that end with . ! ? followed by space and capital letter
const regexSentences = [];
const sentenceRegex = /[^.!?]*[.!?]+(?:\s+|$)/g;
let match;
let lastEnd = 0;
while ((match = sentenceRegex.exec(text)) !== null) {
const sentence = match[0].trim();
if (sentence) {
regexSentences.push(sentence);
}
lastEnd = match.index + match[0].length;
}
// Catch any remaining text that doesn't end with punctuation
if (lastEnd < text.length) {
const remaining = text.substring(lastEnd).trim();
if (remaining) {
regexSentences.push(remaining);
}
}
// Combine both approaches - use whichever found more sentences
const sourceSentences = nlpSentences.length >= regexSentences.length ? nlpSentences : regexSentences;
// Clean up and deduplicate
const seen = new Set();
for (const sentence of sourceSentences) {
const trimmed = sentence.trim();
if (trimmed && !seen.has(trimmed)) {
sentences.push(trimmed);
seen.add(trimmed);
}
}
// If we still have no sentences, just return the whole text as one sentence
if (sentences.length === 0 && text.trim()) {
sentences.push(text.trim());
}
return sentences;
}
// Process each paragraph separately to maintain boundaries
const leftSentencesByParagraph = leftSelectedTexts.map((text, idx) => ({
paragraphIndex: leftSelectedParagraphs[idx],
sentences: splitIntoSentences(text),
text: text
}));
const rightSentencesByParagraph = rightSelectedTexts.map((text, idx) => ({
paragraphIndex: rightSelectedParagraphs[idx],
sentences: splitIntoSentences(text),
text: text
}));
// Flatten all sentences but keep track of their paragraph origins
const allLeftSentences = [];
const allRightSentences = [];
leftSentencesByParagraph.forEach(para => {
para.sentences.forEach(sentence => {
allLeftSentences.push({
sentence: sentence,
paragraphIndex: para.paragraphIndex,
paragraphText: para.text
});
});
});
rightSentencesByParagraph.forEach(para => {
para.sentences.forEach(sentence => {
allRightSentences.push({
sentence: sentence,
paragraphIndex: para.paragraphIndex,
paragraphText: para.text
});
});
});
// Apply the same n² algorithm used for paragraphs
const diff = [];
const matchedSentences = {
leftToRight: new Map(),
rightToLeft: new Map()
};
// Store sentence information for renderer
const sentenceInfo = {
left: new Map(), // paragraphIndex -> array of {text, start, end}
right: new Map() // paragraphIndex -> array of {text, start, end}
};
// Initialize sentence info maps
leftSelectedParagraphs.forEach(idx => sentenceInfo.left.set(idx, []));
rightSelectedParagraphs.forEach(idx => sentenceInfo.right.set(idx, []));
// Populate sentence info
allLeftSentences.forEach(item => {
const para = item.paragraphText;
const start = para.indexOf(item.sentence);
if (start !== -1 && sentenceInfo.left.has(item.paragraphIndex)) {
sentenceInfo.left.get(item.paragraphIndex).push({
text: item.sentence,
start: start,
end: start + item.sentence.length
});
}
});
allRightSentences.forEach(item => {
const para = item.paragraphText;
const start = para.indexOf(item.sentence);
if (start !== -1 && sentenceInfo.right.has(item.paragraphIndex)) {
sentenceInfo.right.get(item.paragraphIndex).push({
text: item.sentence,
start: start,
end: start + item.sentence.length
});
}
});
let oU = 0; // First unprocessed sentence in original (0-indexed)
let rU = 0; // First unprocessed sentence in revised (0-indexed)
while (oU < allLeftSentences.length) {
let found = false;
// Look for exact match in remaining revised sentences
for (let i = rU; i < allRightSentences.length; i++) {
if (allRightSentences[i].sentence === allLeftSentences[oU].sentence) {
// Found exact match
// Store the matching relationship
matchedSentences.leftToRight.set(
`${allLeftSentences[oU].paragraphIndex}:${allLeftSentences[oU].sentence}`,
`${allRightSentences[i].paragraphIndex}:${allRightSentences[i].sentence}`
);
matchedSentences.rightToLeft.set(
`${allRightSentences[i].paragraphIndex}:${allRightSentences[i].sentence}`,
`${allLeftSentences[oU].paragraphIndex}:${allLeftSentences[oU].sentence}`
);
// First, mark all revised sentences before the match as added
for (let j = rU; j < i; j++) {
diff.push({
value: allRightSentences[j].sentence,
added: true,
removed: false,
paragraphIndex: allRightSentences[j].paragraphIndex,
paragraphText: allRightSentences[j].paragraphText
});
}
// Add the matching sentence as unchanged
diff.push({
value: allLeftSentences[oU].sentence,
added: false,
removed: false,
leftParagraphIndex: allLeftSentences[oU].paragraphIndex,
rightParagraphIndex: allRightSentences[i].paragraphIndex
});
oU += 1;
rU = i + 1;
found = true;
break;
}
}
if (!found) {
// No match found - mark original sentence as deleted
diff.push({
value: allLeftSentences[oU].sentence,
removed: true,
added: false,
paragraphIndex: allLeftSentences[oU].paragraphIndex,
paragraphText: allLeftSentences[oU].paragraphText
});
oU += 1;
}
}
// Mark any remaining revised sentences as added
while (rU < allRightSentences.length) {
diff.push({
value: allRightSentences[rU].sentence,
added: true,
removed: false,
paragraphIndex: allRightSentences[rU].paragraphIndex,
paragraphText: allRightSentences[rU].paragraphText
});
rU += 1;
}
// Now convert to positioned diff - find positions within each paragraph
const positionedDiff = [];
// Process each diff part
for (const part of diff) {
if (part.removed) {
// Find position within the paragraph
const paragraphText = part.paragraphText;
const sentenceStart = paragraphText.indexOf(part.value);
if (sentenceStart !== -1) {
// Calculate position relative to the concatenated selected text
let globalStart = 0;
for (let i = 0; i < leftSelectedParagraphs.length; i++) {
if (leftSelectedParagraphs[i] === part.paragraphIndex) {
globalStart += sentenceStart;
break;
}
globalStart += (leftFullParagraphs[leftSelectedParagraphs[i]] || '').length + 1; // +1 for newline
}
positionedDiff.push({
value: part.value,
removed: true,
added: false,
start: globalStart,
end: globalStart + part.value.length,
side: 'left'
});
}
} else if (part.added) {
// Find position within the paragraph
const paragraphText = part.paragraphText;
const sentenceStart = paragraphText.indexOf(part.value);
if (sentenceStart !== -1) {
// Calculate position relative to the concatenated selected text
let globalStart = 0;
for (let i = 0; i < rightSelectedParagraphs.length; i++) {
if (rightSelectedParagraphs[i] === part.paragraphIndex) {
globalStart += sentenceStart;
break;
}
globalStart += (rightFullParagraphs[rightSelectedParagraphs[i]] || '').length + 1; // +1 for newline
}
positionedDiff.push({
value: part.value,
added: true,
removed: false,
start: globalStart,
end: globalStart + part.value.length,
side: 'right'
});
}
}
// Unchanged sentences don't need position info for highlighting
}
return {
diff: positionedDiff,
matchedSentences: matchedSentences,
sentenceInfo: sentenceInfo
};
});
// Enhanced fuzzy sentence mode diff handler
ipcMain.handle('diff-fuzzy-sentence', async (event, leftSelectedText, rightSelectedText, leftSelectedParagraphs, rightSelectedParagraphs, leftFullText, rightFullText, matchThreshold) => {
// Use full text if provided, otherwise parse from selected text
const leftText = leftFullText || leftSelectedText;
const rightText = rightFullText || rightSelectedText;
// Split the full text into paragraphs
const leftFullParagraphs = leftText.split(/\r\n|\r|\n/);
const rightFullParagraphs = rightText.split(/\r\n|\r|\n/);
// Get the selected paragraphs
const leftSelectedTexts = leftSelectedParagraphs.map(i => leftFullParagraphs[i] || '');
const rightSelectedTexts = rightSelectedParagraphs.map(i => rightFullParagraphs[i] || '');
// Improved sentence splitter that preserves exact text
function splitIntoSentences(text) {
if (!text.trim()) return [];
const sentences = [];
// Try multiple approaches to ensure we catch all sentences
// Approach 1: Use compromise but verify results
const doc = nlp(text);
const nlpSentences = doc.sentences().out('array');
// Approach 2: Also use regex-based splitting for better coverage
// This catches sentences that end with . ! ? followed by space and capital letter
const regexSentences = [];
const sentenceRegex = /[^.!?]*[.!?]+(?:\s+|$)/g;
let match;
let lastEnd = 0;
while ((match = sentenceRegex.exec(text)) !== null) {
const sentence = match[0].trim();
if (sentence) {
regexSentences.push(sentence);
}
lastEnd = match.index + match[0].length;
}
// Catch any remaining text that doesn't end with punctuation
if (lastEnd < text.length) {
const remaining = text.substring(lastEnd).trim();
if (remaining) {
regexSentences.push(remaining);
}
}
// Combine both approaches - use whichever found more sentences
const sourceSentences = nlpSentences.length >= regexSentences.length ? nlpSentences : regexSentences;
// Clean up and deduplicate
const seen = new Set();
for (const sentence of sourceSentences) {
const trimmed = sentence.trim();
if (trimmed && !seen.has(trimmed)) {
sentences.push(trimmed);
seen.add(trimmed);
}
}
// If we still have no sentences, just return the whole text as one sentence
if (sentences.length === 0 && text.trim()) {
sentences.push(text.trim());
}
return sentences;
}
// Calculate similarity between two sentences
function calculateSimilarity(s1, s2) {
const words1 = s1.toLowerCase().split(/\s+/);
const words2 = s2.toLowerCase().split(/\s+/);
const set1 = new Set(words1);
const set2 = new Set(words2);
const intersection = new Set([...set1].filter(x => set2.has(x)));
const union = new Set([...set1, ...set2]);
return intersection.size / union.size;
}
// Get word-level diff between two similar sentences
function getWordDiff(s1, s2) {
const words1 = s1.split(/\s+/);
const words2 = s2.split(/\s+/);
const diff = [];
let i = 0, j = 0;
while (i < words1.length || j < words2.length) {
if (i >= words1.length) {
// Remaining words in s2 are additions
diff.push({ type: 'added', value: words2.slice(j).join(' ') });
break;
} else if (j >= words2.length) {
// Remaining words in s1 are deletions
diff.push({ type: 'deleted', value: words1.slice(i).join(' ') });
break;
} else if (words1[i] === words2[j]) {
// Matching word
diff.push({ type: 'unchanged', value: words1[i] });
i++;
j++;
} else {
// Find next match
let nextMatchI = -1;
let nextMatchJ = -1;
// Look ahead for matches
for (let li = i + 1; li < Math.min(i + 5, words1.length); li++) {
for (let lj = j + 1; lj < Math.min(j + 5, words2.length); lj++) {
if (words1[li] === words2[lj]) {
nextMatchI = li;
nextMatchJ = lj;
break;
}
}
if (nextMatchI !== -1) break;
}
if (nextMatchI !== -1) {
// Output deletions and additions up to next match
if (nextMatchI > i) {
diff.push({ type: 'deleted', value: words1.slice(i, nextMatchI).join(' ') });
}
if (nextMatchJ > j) {
diff.push({ type: 'added', value: words2.slice(j, nextMatchJ).join(' ') });
}
i = nextMatchI;
j = nextMatchJ;
} else {
// No more matches
diff.push({ type: 'deleted', value: words1.slice(i).join(' ') });
diff.push({ type: 'added', value: words2.slice(j).join(' ') });
break;
}
}
}
return diff;
}
// Process each paragraph separately to maintain boundaries
const leftSentencesByParagraph = leftSelectedTexts.map((text, idx) => ({
paragraphIndex: leftSelectedParagraphs[idx],
sentences: splitIntoSentences(text),
text: text
}));
const rightSentencesByParagraph = rightSelectedTexts.map((text, idx) => ({
paragraphIndex: rightSelectedParagraphs[idx],
sentences: splitIntoSentences(text),
text: text
}));
// Flatten all sentences but keep track of their paragraph origins
const allLeftSentences = [];
const allRightSentences = [];
leftSentencesByParagraph.forEach(para => {
para.sentences.forEach(sentence => {
allLeftSentences.push({
sentence: sentence,
paragraphIndex: para.paragraphIndex,
paragraphText: para.text
});
});
});
rightSentencesByParagraph.forEach(para => {
para.sentences.forEach(sentence => {
allRightSentences.push({
sentence: sentence,
paragraphIndex: para.paragraphIndex,
paragraphText: para.text
});
});
});
// Apply fuzzy matching algorithm
const diff = [];
const matchedSentences = {
leftToRight: new Map(),
rightToLeft: new Map()
};
const fuzzyMatchedPairs = []; // Store fuzzy matched pairs for inline diff
// Store sentence information for renderer
const sentenceInfo = {
left: new Map(),
right: new Map()
};
// Initialize sentence info maps
leftSelectedParagraphs.forEach(idx => sentenceInfo.left.set(idx, []));
rightSelectedParagraphs.forEach(idx => sentenceInfo.right.set(idx, []));
// Populate sentence info
allLeftSentences.forEach(item => {
const para = item.paragraphText;
const start = para.indexOf(item.sentence);
if (start !== -1 && sentenceInfo.left.has(item.paragraphIndex)) {
sentenceInfo.left.get(item.paragraphIndex).push({
text: item.sentence,
start: start,
end: start + item.sentence.length
});
}
});
allRightSentences.forEach(item => {
const para = item.paragraphText;
const start = para.indexOf(item.sentence);
if (start !== -1 && sentenceInfo.right.has(item.paragraphIndex)) {