-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
2268 lines (1919 loc) · 97.8 KB
/
Copy pathrenderer.js
File metadata and controls
2268 lines (1919 loc) · 97.8 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
class JSONViewer {
constructor() {
this.tabs = [];
this.activeTabId = null;
this.tabCounter = 0;
this.searchResults = [];
this.currentSearchIndex = -1;
this.settings = this.getDefaultSettings();
this.init();
}
getDefaultSettings() {
return {
theme: 'dark',
fontFamily: "'Fira Code', 'Consolas', monospace",
fontSize: 14,
colors: {
key: '#9cdcfe',
string: '#ce9178',
number: '#b5cea8',
boolean: '#569cd6',
null: '#808080',
bracket: '#d4d4d4',
object: '#ffd700',
array: '#ff6b6b'
},
behavior: {
autoExpand: false,
showDataTypes: true,
highlightMatches: true,
showLineNumbers: true,
rainbowBrackets: false,
showStringLength: false, // Show character count for long strings
showArrayIndices: true, // Show [0], [1] indices for array items
stringLengthThreshold: 20, // Character threshold for showing length badges
indentSize: 2, // Number of spaces for JSON indentation
showWhitespace: false // Show whitespace characters like spaces and tabs
}
};
}
async init() {
await this.loadSettings();
this.applySettings();
this.bindEvents();
this.bindElectronEvents();
this.updateUI();
await this.loadAppVersion();
}
async loadAppVersion() {
if (window.electronAPI && window.electronAPI.getVersion) {
try {
const version = await window.electronAPI.getVersion();
const versionElement = document.getElementById('appVersion');
if (versionElement) {
versionElement.textContent = version;
}
} catch (error) {
console.error('Failed to load app version:', error);
}
}
}
bindEvents() {
// Tab management
document.getElementById('newTabBtn').addEventListener('click', () => this.createNewTab());
// File operations
document.getElementById('loadFileBtn').addEventListener('click', () => this.showFileDialog());
document.getElementById('pasteJsonBtn').addEventListener('click', () => this.showPasteModal());
document.getElementById('validateBtn').addEventListener('click', () => this.validateCurrentTab());
document.getElementById('formatBtn').addEventListener('click', () => this.formatCurrentTab());
document.getElementById('minifyBtn').addEventListener('click', () => this.minifyCurrentTab());
// View controls
document.getElementById('expandAllBtn').addEventListener('click', () => this.expandAll());
document.getElementById('collapseAllBtn').addEventListener('click', () => this.collapseAll());
document.getElementById('fullscreenBtn').addEventListener('click', () => this.toggleFullscreen());
document.getElementById('showLineNumbers').addEventListener('change', (e) => {
this.settings.behavior.showLineNumbers = e.target.checked;
// Just toggle the body class - no re-render needed!
document.body.classList.toggle('show-line-numbers', e.target.checked);
// Also update the viewer classes
const viewer = document.querySelector('.json-viewer');
if (viewer) {
viewer.classList.toggle('with-line-numbers', e.target.checked);
// Check if we have collapsible regions
const hasCollapsible = this.collapsibleRegions && Object.keys(this.collapsibleRegions).length > 0;
viewer.classList.toggle('has-collapsible-regions', hasCollapsible);
}
});
// Quick settings
document.getElementById('settingsBtn').addEventListener('click', () => this.showSettings());
document.getElementById('fontSizeRange').addEventListener('input', (e) => {
const size = parseInt(e.target.value);
this.settings.fontSize = size;
document.getElementById('fontSizeValue').textContent = size + 'px';
this.applyFontSettings();
});
// Search functionality with debouncing
let searchTimeout;
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('input', (e) => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => this.performSearch(), 300);
});
// Add Enter key support for search navigation
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault(); // Prevent form submission if in a form
if (this.searchResults && this.searchResults.length > 0) {
if (e.shiftKey) {
// Shift+Enter goes to previous result
this.previousSearchResult();
} else {
// Enter goes to next result
this.nextSearchResult();
}
}
}
});
document.getElementById('searchPrev').addEventListener('click', () => this.previousSearchResult());
document.getElementById('searchNext').addEventListener('click', () => this.nextSearchResult());
document.getElementById('closeSearch').addEventListener('click', () => this.hideSearch());
document.querySelectorAll('input[name="searchType"]').forEach(radio => {
radio.addEventListener('change', () => this.performSearch());
});
// Settings panel
document.getElementById('closeSettings').addEventListener('click', () => this.hideSettings());
document.getElementById('saveSettings').addEventListener('click', () => this.saveSettings());
document.getElementById('resetSettings').addEventListener('click', () => this.resetSettings());
// Settings controls
document.getElementById('themeSelect').addEventListener('change', (e) => {
this.settings.theme = e.target.value;
this.applyTheme();
});
document.getElementById('fontFamilySelect').addEventListener('change', (e) => {
this.settings.fontFamily = e.target.value;
this.applyFontSettings();
});
document.getElementById('settingsFontSize').addEventListener('input', (e) => {
const size = parseInt(e.target.value);
this.settings.fontSize = size;
document.getElementById('settingsFontSizeValue').textContent = size + 'px';
this.applyFontSettings();
});
// Color settings
Object.keys(this.settings.colors).forEach(colorType => {
const colorInput = document.getElementById(colorType + 'Color');
if (colorInput) {
colorInput.addEventListener('change', (e) => {
this.settings.colors[colorType] = e.target.value;
this.applyColorSettings();
this.updateActiveTabView(); // Refresh the view to show new colors
});
}
});
// Behavior settings
document.getElementById('autoExpand').addEventListener('change', (e) => {
this.settings.behavior.autoExpand = e.target.checked;
});
document.getElementById('showDataTypes').addEventListener('change', (e) => {
this.settings.behavior.showDataTypes = e.target.checked;
this.updateActiveTabView();
});
document.getElementById('highlightMatches').addEventListener('change', (e) => {
this.settings.behavior.highlightMatches = e.target.checked;
});
// Rainbow Brackets (settings panel)
const settingsRainbowBrackets = document.querySelector('.settings-panel #rainbowBrackets');
if (settingsRainbowBrackets) {
settingsRainbowBrackets.addEventListener('change', (e) => {
this.settings.behavior.rainbowBrackets = e.target.checked;
this.updateActiveTabViewPreservingState();
this.updateSettingsUI(); // Sync with sidebar
});
}
// JSON input modal
document.getElementById('closeJsonModal').addEventListener('click', () => this.hidePasteModal());
document.getElementById('cancelJsonInput').addEventListener('click', () => this.hidePasteModal());
document.getElementById('loadJsonInput').addEventListener('click', () => this.loadJsonFromInput());
// Keyboard shortcuts
document.addEventListener('keydown', (e) => this.handleKeyboardShortcuts(e));
// Rainbow Brackets (sidebar)
document.getElementById('rainbowBrackets').addEventListener('change', (e) => {
this.settings.behavior.rainbowBrackets = e.target.checked;
this.updateActiveTabViewPreservingState();
this.updateSettingsUI(); // Sync with settings panel
});
// Show Whitespace (sidebar)
document.getElementById('showWhitespace').addEventListener('change', (e) => {
this.settings.behavior.showWhitespace = e.target.checked;
// Toggle the body class AND re-render to add/remove whitespace spans
document.body.classList.toggle('show-whitespace', e.target.checked);
this.updateActiveTabViewPreservingState(); // Re-render to show/hide whitespace
this.updateSettingsUI(); // Sync with settings panel
});
// Array Indices (settings panel)
document.getElementById('showArrayIndices').addEventListener('change', (e) => {
this.settings.behavior.showArrayIndices = e.target.checked;
this.updateActiveTabViewPreservingState();
this.updateSettingsUI(); // Sync with sidebar
});
// String Length (settings panel)
document.getElementById('showStringLength').addEventListener('change', (e) => {
this.settings.behavior.showStringLength = e.target.checked;
this.updateActiveTabViewPreservingState();
this.updateSettingsUI(); // Sync with sidebar
});
// String Length Threshold (settings panel)
document.getElementById('stringLengthThreshold').addEventListener('input', (e) => {
const threshold = parseInt(e.target.value);
this.settings.behavior.stringLengthThreshold = threshold;
document.getElementById('stringLengthThresholdValue').textContent = threshold + ' chars';
if (this.settings.behavior.showStringLength) {
this.updateActiveTabViewPreservingState();
}
});
}
bindElectronEvents() {
if (window.electronAPI) {
window.electronAPI.onFileOpened((event, data) => {
// Create new tab and get its ID
const newTabId = this.createNewTab();
// Find the newly created tab
const activeTab = this.tabs.find(tab => tab.id === newTabId);
if (activeTab) {
// Store file metadata BEFORE loading content
activeTab.filePath = data.filePath;
activeTab.encoding = data.encoding || 'utf-8';
activeTab.hasEncodingIssues = data.hasEncodingIssues || false;
activeTab.wasAutoDetected = data.wasAutoDetected || false;
}
// Load the content - this will trigger updateContentUI which will show the warning if needed
this.loadJsonFromFile(data.content, data.fileName);
});
window.electronAPI.onNewTab(() => this.createNewTab());
window.electronAPI.onCloseTab(() => this.closeCurrentTab());
window.electronAPI.onToggleSettings(() => this.toggleSettings());
window.electronAPI.onToggleSearch(() => this.toggleSearch());
window.electronAPI.onExpandAll(() => this.expandAll());
window.electronAPI.onCollapseAll(() => this.collapseAll());
}
}
handleKeyboardShortcuts(e) {
// F11 for fullscreen (without ctrl/cmd)
if (e.key === 'F11') {
e.preventDefault();
this.toggleFullscreen();
return;
}
if (e.ctrlKey || e.metaKey) {
switch (e.key) {
case 't':
e.preventDefault();
this.createNewTab();
break;
case 'w':
e.preventDefault();
this.closeCurrentTab();
break;
case 'f':
e.preventDefault();
this.toggleSearch();
break;
case ',':
e.preventDefault();
this.toggleSettings();
break;
case 'e':
e.preventDefault();
if (e.shiftKey) {
this.collapseAll();
} else {
this.expandAll();
}
break;
}
}
if (e.key === 'Escape') {
this.hideSearch();
this.hideSettings();
this.hidePasteModal();
}
}
createNewTab() {
const tabId = `tab-${++this.tabCounter}`;
const tab = {
id: tabId,
title: 'Untitled',
content: null,
jsonData: null,
isValid: null,
filePath: null,
encoding: 'utf-8',
hasEncodingIssues: false
};
this.tabs.push(tab);
this.activeTabId = tabId;
this.updateTabsUI();
this.updateContentUI();
this.hideWelcome();
return tabId; // Return the tab ID
}
closeTab(tabId) {
const index = this.tabs.findIndex(tab => tab.id === tabId);
if (index === -1) return;
this.tabs.splice(index, 1);
if (this.activeTabId === tabId) {
if (this.tabs.length > 0) {
const newActiveIndex = Math.min(index, this.tabs.length - 1);
this.activeTabId = this.tabs[newActiveIndex].id;
} else {
this.activeTabId = null;
this.showWelcome();
}
}
this.updateTabsUI();
this.updateContentUI();
}
closeCurrentTab() {
if (this.activeTabId) {
this.closeTab(this.activeTabId);
}
}
switchToTab(tabId) {
this.activeTabId = tabId;
this.updateTabsUI();
this.updateContentUI();
}
updateTabsUI() {
const tabsContainer = document.getElementById('tabs');
tabsContainer.innerHTML = '';
this.tabs.forEach(tab => {
const tabElement = document.createElement('div');
tabElement.className = `tab ${tab.id === this.activeTabId ? 'active' : ''}`;
tabElement.innerHTML = `
<span class="tab-title" title="${tab.title}">${tab.title}</span>
<button class="tab-close" onclick="app.closeTab('${tab.id}')">×</button>
`;
tabElement.addEventListener('click', (e) => {
if (!e.target.classList.contains('tab-close')) {
this.switchToTab(tab.id);
}
});
tabsContainer.appendChild(tabElement);
});
}
// Update the updateContentUI method to include word wrap class
updateContentUI() {
const tabContent = document.getElementById('tabContent');
tabContent.innerHTML = '';
if (!this.activeTabId) return;
const activeTab = this.tabs.find(tab => tab.id === this.activeTabId);
if (!activeTab) return;
const contentDiv = document.createElement('div');
contentDiv.className = 'tab-content active';
// Show encoding warning if needed (before JSON content)
// Show warning for encoding issues OR auto-detected encoding
if ((activeTab.hasEncodingIssues || activeTab.wasAutoDetected) && activeTab.filePath && activeTab.encoding) {
const warningDiv = activeTab.wasAutoDetected ?
this.createEncodingSuccess(activeTab.encoding) :
this.createEncodingWarning(activeTab.encoding);
if (warningDiv) {
contentDiv.appendChild(warningDiv);
}
}
if (activeTab.jsonData) {
// Check file size and use appropriate rendering method
const jsonText = JSON.stringify(activeTab.jsonData, null, this.settings.behavior.indentSize || 2);
const lineCount = jsonText.split('\n').length;
const isLargeFile = lineCount > 5000; // Threshold for progressive rendering
const isVeryLargeFile = lineCount > 50000; // Threshold for virtual scrolling
if (isVeryLargeFile) {
this.renderVirtualJSON(activeTab, contentDiv, jsonText);
} else if (isLargeFile) {
this.renderLargeJSON(activeTab, contentDiv, jsonText);
} else {
this.renderNormalJSON(activeTab, contentDiv);
}
} else if (activeTab.content) {
// Show error for invalid JSON
const errorDiv = document.createElement('div');
errorDiv.className = 'error-display';
errorDiv.textContent = 'Invalid JSON: ' + (activeTab.error || 'Unknown error');
contentDiv.appendChild(errorDiv);
}
tabContent.appendChild(contentDiv);
}
renderNormalJSON(activeTab, contentDiv) {
const viewer = document.createElement('div');
viewer.className = `json-viewer ${this.settings.behavior.showLineNumbers ? 'with-line-numbers' : ''}`;
const jsonContent = document.createElement('div');
jsonContent.className = 'json-content';
jsonContent.innerHTML = this.renderJSON(activeTab.jsonData, 0, true, '');
viewer.appendChild(jsonContent);
// Always render line numbers, CSS will control visibility
const hasCollapsibleRegions = this.collapsibleRegions && Object.keys(this.collapsibleRegions).length > 0;
const lineNumbers = this.generateLineNumbers(activeTab.jsonData, false);
const lineNumbersDiv = document.createElement('div');
lineNumbersDiv.className = 'line-numbers';
lineNumbersDiv.innerHTML = lineNumbers;
viewer.appendChild(lineNumbersDiv);
// Set initial viewer classes
viewer.classList.toggle('with-line-numbers', this.settings.behavior.showLineNumbers);
viewer.classList.toggle('has-collapsible-regions', hasCollapsibleRegions);
// Status indicator
const statusDiv = document.createElement('div');
statusDiv.className = `status-indicator ${activeTab.isValid ? 'status-valid' : 'status-invalid'}`;
statusDiv.textContent = activeTab.isValid ? 'Valid JSON' : 'Invalid JSON';
viewer.appendChild(statusDiv);
contentDiv.appendChild(viewer);
}
renderLargeJSON(activeTab, contentDiv, jsonText) {
// Show loading indicator
const loadingDiv = document.createElement('div');
loadingDiv.className = 'loading-indicator';
loadingDiv.innerHTML = '<div class="spinner"></div><p>Processing large file...</p>';
contentDiv.appendChild(loadingDiv);
// Use requestIdleCallback for progressive rendering
const renderCallback = () => {
const viewer = document.createElement('div');
viewer.className = `json-viewer ${this.settings.behavior.showLineNumbers ? 'with-line-numbers' : ''}`;
// Create containers
const jsonContent = document.createElement('div');
jsonContent.className = 'json-content';
const lineNumbersDiv = document.createElement('div');
lineNumbersDiv.className = 'line-numbers';
// Process in chunks
const lines = jsonText.split('\n');
const CHUNK_SIZE = 1000;
let currentIndex = 0;
// Build collapsible regions and bracket levels once
if (lines.length > 0) {
this.collapsibleRegions = this.buildCollapsibleMap(lines);
if (this.settings.behavior.rainbowBrackets) {
this.bracketLevels = this.calculateBracketLevels(lines);
}
}
const processChunk = () => {
const fragment = document.createDocumentFragment();
const lineNumberFragment = document.createDocumentFragment();
const endIndex = Math.min(currentIndex + CHUNK_SIZE, lines.length);
// Process lines in this chunk
for (let i = currentIndex; i < endIndex; i++) {
const lineNumber = i + 1;
const line = lines[i];
// Create line element
const lineDiv = document.createElement('div');
lineDiv.className = 'json-line';
lineDiv.setAttribute('data-line', lineNumber);
lineDiv.innerHTML = this.highlightJsonLine(line, lineNumber);
fragment.appendChild(lineDiv);
// Create line number element with toggle if needed
const isCollapsible = this.collapsibleRegions && this.collapsibleRegions[lineNumber];
if (isCollapsible) {
const lineNumDiv = document.createElement('div');
lineNumDiv.className = 'line-number-with-toggle';
lineNumDiv.setAttribute('data-line', lineNumber);
lineNumDiv.innerHTML = `
<button class="gutter-toggle" data-line="${lineNumber}" onclick="app.toggleRegion(${lineNumber})">▼</button>
<span class="line-num">${lineNumber}</span>
`;
lineNumberFragment.appendChild(lineNumDiv);
} else {
const lineNumDiv = document.createElement('div');
lineNumDiv.className = 'line-number';
lineNumDiv.setAttribute('data-line', lineNumber);
lineNumDiv.innerHTML = `<span class="line-num">${lineNumber}</span>`;
lineNumberFragment.appendChild(lineNumDiv);
}
}
// Append chunks to DOM
jsonContent.appendChild(fragment);
lineNumbersDiv.appendChild(lineNumberFragment);
currentIndex = endIndex;
// Update progress
const progress = Math.round((currentIndex / lines.length) * 100);
loadingDiv.querySelector('p').textContent = `Processing large file... ${progress}%`;
// Continue processing or finish
if (currentIndex < lines.length) {
requestIdleCallback(processChunk);
} else {
// Remove loading indicator and add viewer
contentDiv.removeChild(loadingDiv);
viewer.appendChild(jsonContent);
viewer.appendChild(lineNumbersDiv);
// Set viewer classes
const hasCollapsibleRegions = this.collapsibleRegions && Object.keys(this.collapsibleRegions).length > 0;
viewer.classList.toggle('with-line-numbers', this.settings.behavior.showLineNumbers);
viewer.classList.toggle('has-collapsible-regions', hasCollapsibleRegions);
// Status indicator
const statusDiv = document.createElement('div');
statusDiv.className = `status-indicator ${activeTab.isValid ? 'status-valid' : 'status-invalid'}`;
statusDiv.textContent = activeTab.isValid ? 'Valid JSON' : 'Invalid JSON';
viewer.appendChild(statusDiv);
contentDiv.appendChild(viewer);
}
};
// Start processing
processChunk();
};
// Use requestIdleCallback with fallback
if (window.requestIdleCallback) {
requestIdleCallback(renderCallback);
} else {
setTimeout(renderCallback, 0);
}
}
renderVirtualJSON(activeTab, contentDiv, jsonText) {
// Show loading indicator
const loadingDiv = document.createElement('div');
loadingDiv.className = 'loading-indicator';
loadingDiv.innerHTML = '<div class="spinner"></div><p>Preparing virtual scrolling for very large file...</p>';
contentDiv.appendChild(loadingDiv);
setTimeout(() => {
const lines = jsonText.split('\n');
// Count and remove empty lines at the end
let emptyLinesRemoved = 0;
while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
lines.pop();
emptyLinesRemoved++;
}
const totalLines = lines.length;
const VISIBLE_LINES = 100; // Number of lines to render at once
// Find last non-empty line
let lastNonEmptyLine = totalLines;
for (let i = totalLines - 1; i >= 0; i--) {
if (lines[i].trim() !== '') {
lastNonEmptyLine = i + 1;
break;
}
}
console.log(`Virtual scrolling: ${lastNonEmptyLine} actual content lines out of ${totalLines} total (removed ${emptyLinesRemoved} trailing empty lines)`);
// Get actual computed line height from CSS
const computedStyle = getComputedStyle(document.documentElement);
const fontSize = parseFloat(computedStyle.getPropertyValue('--font-size')) || 14;
const lineHeightRatio = parseFloat(computedStyle.getPropertyValue('--line-height')) || 1.4;
const LINE_HEIGHT = Math.ceil(fontSize * lineHeightRatio);
console.log(`Line height calculated: ${LINE_HEIGHT}px (font: ${fontSize}px, ratio: ${lineHeightRatio})`);
// Build collapsible regions and bracket levels once
this.collapsibleRegions = this.buildCollapsibleMap(lines);
if (this.settings.behavior.rainbowBrackets) {
this.bracketLevels = this.calculateBracketLevels(lines);
}
// Create viewer with virtual scrolling
const viewer = document.createElement('div');
viewer.className = `json-viewer ${this.settings.behavior.showLineNumbers ? 'with-line-numbers' : ''} virtual-scroll`;
viewer.style.position = 'relative';
viewer.style.height = '100%';
viewer.style.maxHeight = '100%'; // Don't exceed container
viewer.style.overflow = 'auto';
// Create viewport container with correct height
const viewport = document.createElement('div');
// Use the last non-empty line to calculate height
const actualContentLines = lastNonEmptyLine;
const totalHeight = actualContentLines * LINE_HEIGHT;
viewport.style.height = `${totalHeight}px`;
viewport.style.position = 'relative';
console.log(`Viewport height: ${totalHeight}px for ${actualContentLines} content lines`);
// Create content container that will hold visible lines
const jsonContent = document.createElement('div');
jsonContent.className = 'json-content';
jsonContent.style.position = 'absolute';
jsonContent.style.width = '100%';
// Create line numbers container with overflow hidden
const lineNumbersContainer = document.createElement('div');
lineNumbersContainer.style.position = 'absolute';
lineNumbersContainer.style.left = '0';
lineNumbersContainer.style.top = '0';
lineNumbersContainer.style.width = '85px';
lineNumbersContainer.style.height = '100%';
lineNumbersContainer.style.overflow = 'hidden';
const lineNumbersDiv = document.createElement('div');
lineNumbersDiv.className = 'line-numbers';
lineNumbersDiv.style.position = 'absolute';
lineNumbersDiv.style.width = '100%';
let currentStartLine = 0;
let renderTimeout;
const renderVisibleLines = () => {
clearTimeout(renderTimeout);
renderTimeout = setTimeout(() => {
const scrollTop = viewer.scrollTop;
const viewportHeight = viewer.clientHeight;
// Calculate visible range with some buffer
const startLine = Math.max(0, Math.floor(scrollTop / LINE_HEIGHT) - 10);
const visibleLines = Math.ceil(viewportHeight / LINE_HEIGHT) + 20; // Add buffer
const endLine = Math.min(startLine + visibleLines, lastNonEmptyLine);
// Don't render beyond actual content
if (startLine >= lastNonEmptyLine) {
return;
}
// Clear current content
jsonContent.innerHTML = '';
lineNumbersDiv.innerHTML = '';
// Set position based on scroll
jsonContent.style.top = `${startLine * LINE_HEIGHT}px`;
lineNumbersDiv.style.top = `${startLine * LINE_HEIGHT}px`;
// Render visible lines
const fragment = document.createDocumentFragment();
const lineNumberFragment = document.createDocumentFragment();
for (let i = startLine; i < endLine; i++) {
const lineNumber = i + 1;
const line = lines[i];
// Create line element
const lineDiv = document.createElement('div');
lineDiv.className = 'json-line';
lineDiv.setAttribute('data-line', lineNumber);
lineDiv.style.height = `${LINE_HEIGHT}px`;
lineDiv.style.lineHeight = `${LINE_HEIGHT}px`;
lineDiv.style.margin = '0';
lineDiv.style.padding = '0';
lineDiv.innerHTML = this.highlightJsonLine(line, lineNumber);
fragment.appendChild(lineDiv);
// Create line number element
const isCollapsible = this.collapsibleRegions && this.collapsibleRegions[lineNumber];
if (isCollapsible) {
const lineNumDiv = document.createElement('div');
lineNumDiv.className = 'line-number-with-toggle';
lineNumDiv.setAttribute('data-line', lineNumber);
lineNumDiv.style.height = `${LINE_HEIGHT}px`;
lineNumDiv.innerHTML = `
<button class="gutter-toggle" data-line="${lineNumber}" onclick="app.toggleRegion(${lineNumber})">▼</button>
<span class="line-num">${lineNumber}</span>
`;
lineNumberFragment.appendChild(lineNumDiv);
} else {
const lineNumDiv = document.createElement('div');
lineNumDiv.className = 'line-number';
lineNumDiv.setAttribute('data-line', lineNumber);
lineNumDiv.style.height = `${LINE_HEIGHT}px`;
lineNumDiv.innerHTML = `<span class="line-num">${lineNumber}</span>`;
lineNumberFragment.appendChild(lineNumDiv);
}
}
jsonContent.appendChild(fragment);
lineNumbersDiv.appendChild(lineNumberFragment);
}, 10); // Small debounce
};
// Set up scroll listener
viewer.addEventListener('scroll', renderVisibleLines);
// Assemble the viewer
lineNumbersContainer.appendChild(lineNumbersDiv);
viewport.appendChild(jsonContent);
viewport.appendChild(lineNumbersContainer);
viewer.appendChild(viewport);
// Remove loading and add viewer
contentDiv.removeChild(loadingDiv);
// Set viewer classes
const hasCollapsibleRegions = this.collapsibleRegions && Object.keys(this.collapsibleRegions).length > 0;
viewer.classList.toggle('with-line-numbers', this.settings.behavior.showLineNumbers);
viewer.classList.toggle('has-collapsible-regions', hasCollapsibleRegions);
// Status indicator
const statusDiv = document.createElement('div');
statusDiv.className = `status-indicator ${activeTab.isValid ? 'status-valid' : 'status-invalid'}`;
statusDiv.textContent = `${activeTab.isValid ? 'Valid' : 'Invalid'} JSON (${lastNonEmptyLine.toLocaleString()} lines)`;
viewer.appendChild(statusDiv);
contentDiv.appendChild(viewer);
// Initial render
renderVisibleLines();
}, 0);
}
renderJSON(data, level = 0, isRoot = true, path = '') {
// Generate clean JSON text with proper indentation
const indentSize = this.settings.behavior.indentSize || 2;
const jsonText = JSON.stringify(data, null, indentSize);
const lines = jsonText.split('\n');
// Build map of collapsible regions (preserve existing state)
const newRegions = this.buildCollapsibleMap(lines);
if (this.collapsibleRegions) {
// Preserve collapsed state from existing regions
Object.keys(newRegions).forEach(lineNumber => {
if (this.collapsibleRegions[lineNumber]) {
newRegions[lineNumber].collapsed = this.collapsibleRegions[lineNumber].collapsed;
}
});
}
this.collapsibleRegions = newRegions;
// Calculate bracket levels for rainbow brackets
if (this.settings.behavior.rainbowBrackets) {
this.bracketLevels = this.calculateBracketLevels(lines);
}
// Convert each line to HTML with syntax highlighting
const htmlLines = lines.map((line, index) => {
const lineNumber = index + 1;
const highlighted = this.highlightJsonLine(line, lineNumber);
// Check if this line should be hidden due to collapsed region
let isHidden = false;
for (const startLine in this.collapsibleRegions) {
const region = this.collapsibleRegions[startLine];
if (region.collapsed && lineNumber > parseInt(startLine) && lineNumber <= region.endLine) {
isHidden = true;
break;
}
}
const hiddenClass = isHidden ? ' json-line-hidden' : '';
// Check if this is a collapsed region start line
let collapsedIndicator = '';
if (this.collapsibleRegions && this.collapsibleRegions[lineNumber] && this.collapsibleRegions[lineNumber].collapsed) {
collapsedIndicator = ' collapsed-region';
}
const result = `<div class="json-line${hiddenClass}${collapsedIndicator}" data-line="${lineNumber}">${highlighted}</div>`;
if (lineNumber === 6) {
}
return result;
});
return htmlLines.join('');
}
calculateBracketLevels(lines) {
const bracketLevels = {};
let currentLevel = 0;
const bracketStack = []; // Stack to track opening brackets and their colors
let arrayElementIndices = []; // Track element index at each array level
lines.forEach((line, index) => {
const lineNumber = index + 1;
const trimmedLine = line.trim();
// Store bracket info for this line
const brackets = [];
// Check if this line starts a new array element (excluding the array opening line itself)
if (arrayElementIndices.length > 0 &&
(trimmedLine.startsWith('{') || trimmedLine.startsWith('[') ||
/^"/.test(trimmedLine) || /^\d+/.test(trimmedLine) ||
trimmedLine.startsWith('true') || trimmedLine.startsWith('false') ||
trimmedLine.startsWith('null'))) {
// Look at previous line to see if it ended with a comma (new element) or was the array opening
if (index > 0) {
const prevLine = lines[index - 1].trim();
if (prevLine.endsWith(',')) {
// Increment the element index for the current array
arrayElementIndices[arrayElementIndices.length - 1]++;
}
}
}
// Process each character in the line
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '{' || char === '[') {
// Calculate color level
let colorLevel = currentLevel;
// If we're inside an array, add the current element index
if (arrayElementIndices.length > 0) {
const currentElementIndex = arrayElementIndices[arrayElementIndices.length - 1];
colorLevel = currentLevel + currentElementIndex;
}
brackets.push({ char, level: colorLevel, position: i });
// Push bracket info to stack for matching closing bracket
bracketStack.push({
char: char,
level: colorLevel,
depth: currentLevel,
isArray: char === '['
});
// If opening an array, add a new element index counter
if (char === '[') {
arrayElementIndices.push(0);
}
currentLevel++;
} else if (char === '}' || char === ']') {
currentLevel = Math.max(0, currentLevel - 1);
// Pop the matching opening bracket to get the same color
if (bracketStack.length > 0) {
const matchingBracket = bracketStack.pop();
brackets.push({ char, level: matchingBracket.level, position: i });
// If closing an array, remove its element index counter
if (char === ']' && arrayElementIndices.length > 0) {
arrayElementIndices.pop();
}
} else {
// Fallback if stack is empty (shouldn't happen with valid JSON)
brackets.push({ char, level: currentLevel, position: i });
}
}
}
if (brackets.length > 0) {
bracketLevels[lineNumber] = brackets;
}
});
return bracketLevels;
}
buildCollapsibleMap(lines) {
const collapsibleRegions = {};
const bracketStack = [];
lines.forEach((line, index) => {
const lineNumber = index + 1;
const trimmedLine = line.trim();
// More robust bracket detection
// Check for opening brackets that start a new object/array
const hasOpeningObject = trimmedLine.includes('{') && !this.isInlineObject(trimmedLine);
const hasOpeningArray = trimmedLine.includes('[') && !this.isInlineArray(trimmedLine);
if (hasOpeningObject) {
bracketStack.push({
lineNumber: lineNumber,
char: '{',
indentLevel: line.length - line.trimStart().length
});
}
if (hasOpeningArray) {
bracketStack.push({
lineNumber: lineNumber,
char: '[',
indentLevel: line.length - line.trimStart().length
});
}
// Check for closing brackets
const hasClosingObject = (trimmedLine === '}' || trimmedLine === '},');
const hasClosingArray = (trimmedLine === ']' || trimmedLine === '],');
if (hasClosingObject || hasClosingArray) {
const closingChar = hasClosingObject ? '}' : ']';
// Find the most recent matching opening bracket
for (let i = bracketStack.length - 1; i >= 0; i--) {
const opening = bracketStack[i];
if ((opening.char === '{' && closingChar === '}') ||
(opening.char === '[' && closingChar === ']')) {
// Only create collapsible region if there's content between brackets
if (lineNumber > opening.lineNumber + 1) {
// Count items between start and end
let itemCount = 0;
const isArray = opening.char === '[';
if (isArray) {
// For arrays, count direct child items
let depth = 0;
for (let i = opening.lineNumber; i < lineNumber - 1; i++) {
const line = lines[i].trim();
// Track depth to only count direct children
if (line.includes('{') || line.includes('[')) depth++;
if (line.includes('}') || line.includes(']')) depth--;
// Count items at depth 1 (direct children of this array)
if (depth === 1) {
// Count opening brackets of direct child objects/arrays
if (line === '{' || line === '[' || line.startsWith('{') || line.startsWith('[')) {
itemCount++;
}
// Count primitive values (strings, numbers, etc) that are direct children
else if (depth === 0 && line.match(/^["'\d\-true\false\null]/)) {
itemCount++;
}
}
}
} else {
// For objects, count properties (lines with colons at the right depth)
let depth = 0;
for (let i = opening.lineNumber; i < lineNumber - 1; i++) {
const line = lines[i].trim();
// Count lines with colons at depth 0 (direct properties)
if (depth === 0 && line.includes('":')) {
itemCount++;
}
// Track depth
if (line.includes('{') || line.includes('[')) depth++;
if (line.includes('}') || line.includes(']')) depth--;
}