-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
3704 lines (3128 loc) · 144 KB
/
renderer.js
File metadata and controls
3704 lines (3128 loc) · 144 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
// Custom tooltip system for scalable tooltips
let customTooltip = null;
let tooltipTimeout = null;
function showCustomTooltip(element, text) {
hideCustomTooltip();
customTooltip = document.createElement('div');
customTooltip.className = 'custom-tooltip';
customTooltip.textContent = text;
document.body.appendChild(customTooltip);
const rect = element.getBoundingClientRect();
customTooltip.style.left = rect.left + (rect.width / 2) + 'px';
customTooltip.style.top = (rect.top - 10) + 'px';
// Position tooltip with boundary checking
setTimeout(() => {
const tooltipRect = customTooltip.getBoundingClientRect();
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
// Calculate ideal position (centered above element)
let left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
let top = rect.top - tooltipRect.height - 8;
// Check right boundary
if (left + tooltipRect.width > windowWidth - 5) {
left = windowWidth - tooltipRect.width - 5;
}
// Check left boundary
if (left < 5) {
left = 5;
}
// Check top boundary (if tooltip would go above window, show below instead)
if (top < 5) {
top = rect.bottom + 8;
}
// Check bottom boundary (shouldn't happen often, but just in case)
if (top + tooltipRect.height > windowHeight - 5) {
top = windowHeight - tooltipRect.height - 5;
}
customTooltip.style.left = left + 'px';
customTooltip.style.top = top + 'px';
customTooltip.classList.add('visible');
}, 0);
}
function hideCustomTooltip() {
if (customTooltip) {
customTooltip.remove();
customTooltip = null;
}
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
tooltipTimeout = null;
}
}
function addCustomTooltip(element, text) {
// Store the original title as custom tooltip text
if (!text && element.hasAttribute('title')) {
text = element.getAttribute('title');
element.setAttribute('data-tooltip', text);
element.removeAttribute('title');
}
element.addEventListener('mouseenter', () => {
const tooltipText = text || element.getAttribute('data-tooltip');
if (tooltipText) {
tooltipTimeout = setTimeout(() => {
showCustomTooltip(element, tooltipText);
}, 500); // Show after 500ms hover
}
});
element.addEventListener('mouseleave', hideCustomTooltip);
element.addEventListener('mousedown', hideCustomTooltip);
}
// Function to convert all title attributes to custom tooltips
function convertAllTooltips() {
// Convert all elements with title attribute
document.querySelectorAll('[title]').forEach(element => {
addCustomTooltip(element);
});
// Monitor for new elements with title attributes
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1) { // Element node
if (node.hasAttribute && node.hasAttribute('title')) {
addCustomTooltip(node);
}
// Check children too
if (node.querySelectorAll) {
node.querySelectorAll('[title]').forEach(element => {
addCustomTooltip(element);
});
}
}
});
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});
}
// Document state management
class DocumentState {
constructor() {
this.content = '';
this.filePath = '';
this.scrollTop = 0;
this.selectedParagraphs = new Set();
this.tabId = 'tab-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
this.isModified = false;
this.pastedTimestamp = null; // Store timestamp for pasted documents
}
}
// Multi-document storage
let documents = {
left: new Map(),
right: new Map()
};
let activeTab = {
left: null,
right: null
};
// Toolbar scaling manager to prevent control overflow at high zoom levels
class ToolbarScaler {
constructor() {
this.toolbars = new Map();
this.resizeObserver = null;
this.checkTimeout = null;
this.MIN_SCALE = 0.7;
this.BUFFER_FACTOR = 0.95; // Less aggressive buffer for tighter fit
}
init() {
// Set up observers for both toolbars
this.observeToolbar('left');
this.observeToolbar('right');
// Set up global resize observer
this.setupResizeObserver();
// Initial check
this.checkAllToolbars();
}
observeToolbar(side) {
const wrapper = document.querySelector(`#${side}Pane .pane-controls-wrapper`);
if (wrapper) {
this.toolbars.set(side, wrapper);
}
}
setupResizeObserver() {
this.resizeObserver = new ResizeObserver(() => {
// Debounce resize events
clearTimeout(this.checkTimeout);
this.checkTimeout = setTimeout(() => {
this.checkAllToolbars();
}, 100);
});
// Observe the main container for size changes
const container = document.querySelector('.container');
if (container) {
this.resizeObserver.observe(container);
}
}
checkAllToolbars() {
for (const [side, toolbar] of this.toolbars) {
this.checkAndScale(side);
}
}
checkAndScale(side) {
const toolbar = this.toolbars.get(side);
if (!toolbar) return;
const scale = this.calculateScale(toolbar);
this.applyScale(toolbar, scale);
}
calculateScale(wrapper) {
// Get the parent pane-controls width
const container = wrapper.parentElement;
if (!container) return 1.0;
// Account for padding in the container
const containerPadding = 36; // 16px padding + 2px buffer on each side
const availableWidth = container.clientWidth - containerPadding;
// Get the natural width of all controls
// Remove any existing transform to measure natural size
const currentTransform = wrapper.style.transform;
wrapper.style.transform = '';
const controlsWidth = wrapper.scrollWidth;
// Restore transform
wrapper.style.transform = currentTransform;
// Calculate scale needed to fit
if (controlsWidth > availableWidth) {
// Calculate scale with buffer
const scale = (availableWidth / controlsWidth) * this.BUFFER_FACTOR;
// Enforce minimum scale
return Math.max(scale, this.MIN_SCALE);
}
return 1.0; // No scaling needed
}
applyScale(wrapper, scale) {
if (scale < 1.0) {
// Apply transform origin to keep controls left-aligned
wrapper.style.transformOrigin = 'left center';
wrapper.style.transform = `scale(${scale})`;
} else {
// Reset to normal
wrapper.style.transform = '';
wrapper.style.transformOrigin = '';
}
}
destroy() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
}
clearTimeout(this.checkTimeout);
}
}
// Create global instance
const toolbarScaler = new ToolbarScaler();
// Global settings and state
let currentZoom = 1.0;
let appConfig = null;
// Paragraph matching settings
let paragraphMatchingEnabled = true;
let paragraphAlgorithm = 'thomas'; // 'thomas' or 'patience'
let paragraphFuzziness = 0.0; // 0.0-1.0
// Sentence matching settings
let sentenceMatchingEnabled = true;
let sentenceAlgorithm = 'thomas'; // 'thomas', 'levenshtein', 'character'
let sentenceFuzziness = 0.0; // 0.0-1.0
// Strikethrough setting (left side only)
let strikethroughEnabled = true; // Default enabled
// Store resize observers to prevent memory leaks
const resizeObservers = new Map();
// Store paragraph diff results globally
let paragraphDiffResults = null;
// Store mapping of matched paragraphs between documents
let matchedParagraphs = {
leftToRight: new Map(),
rightToLeft: new Map()
};
// Store matched sentences for sentence mode
let matchedSentences = {
leftToRight: new Map(),
rightToLeft: new Map()
};
// Store all sentences for current comparison
let currentSentences = {
left: new Map(),
right: new Map()
};
// Store fuzzy matched sentence pairs
let fuzzyMatchedPairs = [];
// Store character diff pairs
let characterDiffPairs = [];
// Track if CTRL is held
let ctrlHeld = false;
// Store change bar data for paragraphs
let paragraphChangeBars = {
left: new Map(),
right: new Map()
};
// Maximum number of tabs per side
const MAX_TABS = 20;
// Tab management functions
function generateTabTitle(filePath) {
if (!filePath) return '(empty)';
if (filePath.startsWith('Pasted at ')) return filePath;
const parts = filePath.split(/[/\\]/);
return parts[parts.length - 1] || '(empty)';
}
async function createNewTab(side, content = '', filePath = '') {
if (documents[side].size >= MAX_TABS) {
await showInfo(`Maximum number of tabs (${MAX_TABS}) reached.`, 'Tab Limit');
return null;
}
const doc = new DocumentState();
doc.content = content;
doc.filePath = filePath;
documents[side].set(doc.tabId, doc);
// Create tab element
const tabsContainer = document.getElementById(`${side}TabsContainer`);
const tabElement = document.createElement('div');
tabElement.className = 'tab';
tabElement.dataset.tabId = doc.tabId;
tabElement.draggable = true;
tabElement.innerHTML = `
<span class="tab-title">${escapeHtml(generateTabTitle(filePath))}</span>
<button class="tab-close" title="Close tab">×</button>
`;
// Add event listeners
tabElement.addEventListener('click', (e) => {
if (!e.target.classList.contains('tab-close')) {
switchToTab(side, doc.tabId);
}
});
tabElement.querySelector('.tab-close').addEventListener('click', (e) => {
e.stopPropagation();
closeTab(side, doc.tabId);
});
// Add drag and drop functionality
setupTabDragAndDrop(tabElement, side);
tabsContainer.appendChild(tabElement);
// Switch to the new tab
switchToTab(side, doc.tabId);
return doc.tabId;
}
function switchToTab(side, tabId) {
if (activeTab[side] === tabId) return;
// Save current tab state
if (activeTab[side]) {
saveCurrentTabState(side);
}
// Store current document pair before switching
const previousLeftDoc = getActiveDocument('left');
const previousRightDoc = getActiveDocument('right');
const previousLeftPath = previousLeftDoc ? previousLeftDoc.filePath : null;
const previousRightPath = previousRightDoc ? previousRightDoc.filePath : null;
// Update active tab
activeTab[side] = tabId;
// Update tab UI
const tabs = document.querySelectorAll(`#${side}TabsContainer .tab`);
tabs.forEach(tab => {
if (tab.dataset.tabId === tabId) {
tab.classList.add('active');
} else {
tab.classList.remove('active');
}
});
// Load new tab content
const doc = documents[side].get(tabId);
if (doc) {
displayDocument(side, doc);
// Clear all diffs when switching tabs
clearComparison();
clearParagraphMarkers();
}
// Update button states for the opposite side as well (document pair might have changed)
updateTabButtonStates('left');
updateTabButtonStates('right');
saveState();
}
function closeTab(side, tabId) {
// Don't close if it's the only tab
if (documents[side].size <= 1) {
// Clear the content instead
const doc = documents[side].get(tabId);
if (doc) {
doc.content = '';
doc.filePath = '';
doc.scrollTop = 0;
doc.selectedParagraphs.clear();
doc.isModified = false;
doc.pastedTimestamp = null; // Clear timestamp too
displayDocument(side, doc);
updateTabTitle(side, tabId, '(empty)', false); // Update tab title
}
return;
}
// Find adjacent tab to switch to
const tabs = Array.from(document.querySelectorAll(`#${side}TabsContainer .tab`));
const currentIndex = tabs.findIndex(tab => tab.dataset.tabId === tabId);
let newActiveTab = null;
if (currentIndex > 0) {
newActiveTab = tabs[currentIndex - 1].dataset.tabId;
} else if (currentIndex < tabs.length - 1) {
newActiveTab = tabs[currentIndex + 1].dataset.tabId;
}
// Remove tab from DOM
const tabElement = tabs[currentIndex];
if (tabElement) {
tabElement.remove();
}
// Remove document from storage
documents[side].delete(tabId);
// Clean up resize observer if exists
if (resizeObservers.has(`${side}-${tabId}`)) {
resizeObservers.get(`${side}-${tabId}`).disconnect();
resizeObservers.delete(`${side}-${tabId}`);
}
// Switch to adjacent tab
if (newActiveTab) {
switchToTab(side, newActiveTab);
}
saveState();
}
async function moveTabToOtherSide(fromSide) {
// Don't move if it's the only tab
if (documents[fromSide].size <= 1) {
// Instead of moving, clear the current tab and create a new one on the other side
const doc = getActiveDocument(fromSide);
if (!doc || !doc.content) {
// No content to move
return;
}
// Save the document state
const content = doc.content;
const filePath = doc.filePath;
const scrollTop = doc.scrollTop;
const selectedParagraphs = new Set(doc.selectedParagraphs);
const isModified = doc.isModified;
// Clear the current tab
doc.content = '';
doc.filePath = '';
doc.scrollTop = 0;
doc.selectedParagraphs.clear();
doc.isModified = false;
displayDocument(fromSide, doc);
// Update tab title to reflect cleared state
updateTabTitle(fromSide, doc.tabId, '(empty)', false);
// Create new tab on the other side
const toSide = fromSide === 'left' ? 'right' : 'left';
// Check if the destination side has only a single empty tab
let singleEmptyTabId = null;
if (documents[toSide].size === 1) {
const [tabId, doc] = documents[toSide].entries().next().value;
if (!doc.content && !doc.filePath) {
singleEmptyTabId = tabId;
}
}
const newTabId = await createNewTab(toSide, content, filePath);
if (newTabId) {
const newDoc = documents[toSide].get(newTabId);
if (newDoc) {
newDoc.scrollTop = scrollTop;
newDoc.selectedParagraphs = selectedParagraphs;
newDoc.isModified = isModified;
// Update tab title to reflect modified state
updateTabTitle(toSide, newTabId, generateTabTitle(filePath), isModified);
// Restore scroll and selections after display
setTimeout(() => {
const contentElement = document.getElementById(`${toSide}Content`);
if (contentElement) {
contentElement.scrollTop = scrollTop;
}
selectedParagraphs.forEach(paragraphNum => {
const checkbox = document.querySelector(`#${toSide}-paragraph-${paragraphNum}`);
if (checkbox) {
checkbox.checked = true;
}
});
}, 0);
}
// If destination had a single empty tab, close it
if (singleEmptyTabId) {
closeTab(toSide, singleEmptyTabId);
}
}
} else {
// Multiple tabs exist, can safely move
const doc = getActiveDocument(fromSide);
if (!doc) return;
// Save the current tab state
saveCurrentTabState(fromSide);
// Save the document state
const content = doc.content;
const filePath = doc.filePath;
const scrollTop = doc.scrollTop;
const selectedParagraphs = new Set(doc.selectedParagraphs);
const isModified = doc.isModified;
const currentTabId = activeTab[fromSide];
// Create new tab on the other side
const toSide = fromSide === 'left' ? 'right' : 'left';
// Check if the destination side has only a single empty tab
let singleEmptyTabId = null;
if (documents[toSide].size === 1) {
const [tabId, doc] = documents[toSide].entries().next().value;
if (!doc.content && !doc.filePath) {
singleEmptyTabId = tabId;
}
}
const newTabId = await createNewTab(toSide, content, filePath);
if (newTabId) {
const newDoc = documents[toSide].get(newTabId);
if (newDoc) {
newDoc.scrollTop = scrollTop;
newDoc.selectedParagraphs = selectedParagraphs;
newDoc.isModified = isModified;
// Update tab title to reflect modified state
updateTabTitle(toSide, newTabId, generateTabTitle(filePath), isModified);
// Restore scroll and selections after display
setTimeout(() => {
const contentElement = document.getElementById(`${toSide}Content`);
if (contentElement) {
contentElement.scrollTop = scrollTop;
}
selectedParagraphs.forEach(paragraphNum => {
const checkbox = document.querySelector(`#${toSide}-paragraph-${paragraphNum}`);
if (checkbox) {
checkbox.checked = true;
}
});
}, 0);
}
// Close the original tab
closeTab(fromSide, currentTabId);
// If destination had a single empty tab, close it
if (singleEmptyTabId) {
closeTab(toSide, singleEmptyTabId);
}
}
}
// Clear any comparison since documents have changed sides
clearComparison();
// Re-run paragraph diff if both sides have content
const leftDoc = getActiveDocument('left');
const rightDoc = getActiveDocument('right');
if (leftDoc && leftDoc.content && rightDoc && rightDoc.content) {
// Automatic paragraph diff removed - now handled by Compare button
// runParagraphDiff();
}
saveState();
}
function getActiveDocument(side) {
if (!activeTab[side]) return null;
return documents[side].get(activeTab[side]);
}
function updateTabTitle(side, tabId, title, isModified = false) {
const tab = document.querySelector(`#${side}TabsContainer .tab[data-tab-id="${tabId}"]`);
if (tab) {
const titleElement = tab.querySelector('.tab-title');
titleElement.textContent = title;
if (isModified) {
titleElement.classList.add('modified');
} else {
titleElement.classList.remove('modified');
}
}
}
function saveCurrentTabState(side) {
const doc = getActiveDocument(side);
if (!doc) return;
// Save scroll position
const contentElement = document.getElementById(`${side}Content`);
if (contentElement) {
doc.scrollTop = contentElement.scrollTop;
}
// Save selected paragraphs
doc.selectedParagraphs.clear();
const checkboxes = document.querySelectorAll(`#${side}ParagraphNumbers input[type="checkbox"]:checked`);
checkboxes.forEach(cb => {
doc.selectedParagraphs.add(parseInt(cb.dataset.paragraph));
});
}
// Tab drag and drop functionality
let draggedTab = null;
let draggedSide = null;
function setupTabDragAndDrop(tabElement, side) {
tabElement.addEventListener('dragstart', (e) => {
draggedTab = tabElement;
draggedSide = side;
tabElement.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
});
tabElement.addEventListener('dragend', (e) => {
tabElement.classList.remove('dragging');
// Clean up any drag-over indicators
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.remove('drag-over-left', 'drag-over-right');
});
draggedTab = null;
draggedSide = null;
});
tabElement.addEventListener('dragover', (e) => {
e.preventDefault();
if (!draggedTab || draggedSide !== side || draggedTab === tabElement) return;
const rect = tabElement.getBoundingClientRect();
const midpoint = rect.left + rect.width / 2;
// Remove other indicators
document.querySelectorAll(`#${side}TabsContainer .tab`).forEach(tab => {
if (tab !== tabElement) {
tab.classList.remove('drag-over-left', 'drag-over-right');
}
});
if (e.clientX < midpoint) {
tabElement.classList.add('drag-over-left');
tabElement.classList.remove('drag-over-right');
} else {
tabElement.classList.add('drag-over-right');
tabElement.classList.remove('drag-over-left');
}
});
tabElement.addEventListener('dragleave', (e) => {
tabElement.classList.remove('drag-over-left', 'drag-over-right');
});
tabElement.addEventListener('drop', (e) => {
e.preventDefault();
if (!draggedTab || draggedSide !== side || draggedTab === tabElement) return;
const rect = tabElement.getBoundingClientRect();
const midpoint = rect.left + rect.width / 2;
const insertBefore = e.clientX < midpoint;
const container = document.getElementById(`${side}TabsContainer`);
if (insertBefore) {
container.insertBefore(draggedTab, tabElement);
} else {
container.insertBefore(draggedTab, tabElement.nextSibling);
}
tabElement.classList.remove('drag-over-left', 'drag-over-right');
// Save the new tab order
saveState();
});
}
// Initialize event listeners
document.addEventListener('DOMContentLoaded', async () => {
// Check if API is available
if (!window.api) {
console.error('Electron API not available. Make sure preload script is loaded correctly.');
return;
}
// Override console methods to log to stdout
const originalConsole = {
log: console.log,
warn: console.warn,
error: console.error
};
// Helper to serialize objects for IPC
const serializeForIPC = (obj) => {
try {
// Try to clone the object to test if it's serializable
structuredClone(obj);
return obj;
} catch (e) {
// If not serializable, convert to string representation
if (obj instanceof Element) {
return `[DOM Element: ${obj.tagName}${obj.id ? '#' + obj.id : ''}${obj.className ? '.' + obj.className : ''}]`;
} else if (obj instanceof Event) {
return `[Event: ${obj.type} on ${obj.target?.tagName || 'unknown'}]`;
} else if (typeof obj === 'object' && obj !== null) {
// For other objects, create a safe representation
try {
const safeObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
if (value instanceof Element) {
safeObj[key] = `[DOM Element: ${value.tagName}]`;
} else if (value instanceof Event) {
safeObj[key] = `[Event: ${value.type}]`;
} else if (typeof value === 'function') {
safeObj[key] = '[Function]';
} else {
try {
structuredClone(value);
safeObj[key] = value;
} catch {
safeObj[key] = String(value);
}
}
}
}
return safeObj;
} catch {
return String(obj);
}
}
return obj;
}
};
console.log = (...args) => {
originalConsole.log(...args); // Still log to DevTools
const serializedArgs = args.map(serializeForIPC);
window.api.consoleLog(...serializedArgs); // Log serialized version to stdout
};
console.warn = (...args) => {
originalConsole.warn(...args);
const serializedArgs = args.map(serializeForIPC);
window.api.consoleWarn(...serializedArgs);
};
console.error = (...args) => {
originalConsole.error(...args);
const serializedArgs = args.map(serializeForIPC);
window.api.consoleError(...serializedArgs);
};
// Convert all native tooltips to custom scalable tooltips
convertAllTooltips();
// Icons don't need tooltips - removed due to visual conflicts
// Load configuration
try {
appConfig = await window.api.getConfig();
} catch (error) {
// Failed to load config, using defaults
appConfig = {
fuzzySentenceMatching: {
minMatchPercent: 10,
maxMatchPercent: 100
},
fuzzyParagraphMatching: {
minMatchPercent: 30,
maxMatchPercent: 100
}
};
}
// Apply min/max values from config to intensity sliders
const bgIntensityMin = appConfig?.colors?.bgIntensityMin ?? 5;
const bgIntensityMax = appConfig?.colors?.bgIntensityMax ?? 40;
const hlIntensityMin = appConfig?.colors?.hlIntensityMin ?? 20;
const hlIntensityMax = appConfig?.colors?.hlIntensityMax ?? 60;
// Set min/max for background intensity sliders
document.getElementById('leftBgIntensity').min = bgIntensityMin;
document.getElementById('leftBgIntensity').max = bgIntensityMax;
document.getElementById('rightBgIntensity').min = bgIntensityMin;
document.getElementById('rightBgIntensity').max = bgIntensityMax;
// Set min/max for highlight intensity sliders
document.getElementById('leftHlIntensity').min = hlIntensityMin;
document.getElementById('leftHlIntensity').max = hlIntensityMax;
document.getElementById('rightHlIntensity').min = hlIntensityMin;
document.getElementById('rightHlIntensity').max = hlIntensityMax;
// Set up all UI components first
setupDropZones();
setupButtons();
setupFileOpenListener();
setupPasteListener();
setupZoomControls();
setupColorControls();
setupStrikethroughControl();
await populateAlgorithms();
setupDiffModeControls();
setupCopyTooltip();
setupSelectAllControls();
setupStatusBar();
setupCtrlTracking();
setupKeyboardShortcuts();
setupTabControls();
// Initialize toolbar scaling
toolbarScaler.init();
// Add copy event listener to deselect text after copy
document.addEventListener('copy', (e) => {
// Clear selection after copy
setTimeout(() => {
window.getSelection().removeAllRanges();
}, 10);
});
// Load saved state or create default tabs
window.api.onRestoreState(async () => {
const loaded = await loadSavedState();
// If no state was loaded, create default empty tabs
if (!loaded) {
await createNewTab('left');
await createNewTab('right');
}
// Update button states after loading
updateTabButtonStates('left');
updateTabButtonStates('right');
});
// Also attempt to load state immediately in case the event doesn't fire
setTimeout(async () => {
// Only load if we haven't already (no tabs exist)
if (documents.left.size === 0 && documents.right.size === 0) {
const loaded = await loadSavedState();
if (!loaded) {
await createNewTab('left');
await createNewTab('right');
}
// Update button states after loading
updateTabButtonStates('left');
updateTabButtonStates('right');
}
}, 100);
});
// Add beforeunload to save state
window.addEventListener('beforeunload', () => {
saveState();
});
function setupTabControls() {
// New tab buttons
document.getElementById('leftNewTab').addEventListener('click', async () => {
await createNewTab('left');
});
document.getElementById('rightNewTab').addEventListener('click', async () => {
await createNewTab('right');
});
// Move tab buttons
document.getElementById('leftMoveTab').addEventListener('click', async () => {
await moveTabToOtherSide('left');
});
document.getElementById('rightMoveTab').addEventListener('click', async () => {
await moveTabToOtherSide('right');
});
// Reload tab buttons
document.getElementById('leftReloadTab').addEventListener('click', async () => {
await reloadCurrentFile('left');
});
document.getElementById('rightReloadTab').addEventListener('click', async () => {
await reloadCurrentFile('right');
});
}
function setupDropZones() {
const leftDrop = document.getElementById('leftDrop');
const rightDrop = document.getElementById('rightDrop');
setupDropZone(leftDrop, 'left');
setupDropZone(rightDrop, 'right');
// Set up browse buttons
document.getElementById('leftBrowseBtn').addEventListener('click', () => openFileDialog('left'));
document.getElementById('rightBrowseBtn').addEventListener('click', () => openFileDialog('right'));
// Set up paste buttons
document.getElementById('leftPasteBtn').addEventListener('click', async () => await pasteFromClipboard('left'));
document.getElementById('rightPasteBtn').addEventListener('click', async () => await pasteFromClipboard('right'));
}
function setupDropZone(dropZone, side) {
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', async (e) => {
e.preventDefault();
dropZone.classList.remove('drag-over');
const file = e.dataTransfer.files[0];
if (file) {
loadFile(file.path, side);
}
});
}
async function loadFile(filePath, side) {
const result = await window.api.readFile(filePath);
if (result.success) {
const doc = getActiveDocument(side);
if (doc) {
doc.content = result.content;
doc.filePath = filePath;
doc.isModified = false;
updateTabTitle(side, doc.tabId, generateTabTitle(filePath), false);
displayDocument(side, doc);
// Run paragraph diff if both files are loaded
const leftDoc = getActiveDocument('left');
const rightDoc = getActiveDocument('right');
if (leftDoc && leftDoc.content && rightDoc && rightDoc.content) {
// Automatic paragraph diff removed - now handled by Compare button
// await runParagraphDiff();
}
saveState();
}
} else {
await showInfo(`Error reading file: ${result.error}`, 'File Error');
}
}
function updateTabButtonStates(side) {
const reloadButton = document.getElementById(`${side}ReloadTab`);
const doc = getActiveDocument(side);
if (reloadButton) {
if (doc && doc.filePath && !doc.pastedTimestamp) {
// Enable reload button for file documents