-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRenderer.ts
More file actions
1137 lines (965 loc) · 41.9 KB
/
Copy pathRenderer.ts
File metadata and controls
1137 lines (965 loc) · 41.9 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
import { Code, HighlighedNode } from "../code";
import { AnycodeLine, RowElements } from "../types";
import { isGhostElement, objectHash, minimize } from "../utils";
import { moveCursor, removeCursor } from "../cursor";
import { EditorState, EditorSettings } from "../editor";
import { DiffInfo } from "../diff";
import { Selection, renderSelection } from "../selection";
import { Completion } from "../lsp";
import { Search } from "../search";
import { LineRenderer } from "./LineRenderer";
import { SearchRenderer } from "./SearchRenderer";
import { DiffRenderer } from "./DiffRenderer";
import { CompletionRenderer } from "./CompletionRenderer";
import { HoverRenderer } from "./HoverRenderer";
import { DiagnosticRenderer } from "./DiagnosticRenderer";
import { ScrollbarMarkersRenderer } from "./ScrollbarMarkersRenderer";
import { WordHighlightRenderer } from "./WordHighlightRenderer";
import { BracketMatchRenderer } from "./BracketMatchRenderer";
const MAX_SCROLLBAR_MARKER_LINES = 5000;
/**
* A real line from the code
*/
export interface RealRow {
kind: 'real';
lineIndex: number; // 0-indexed line in code
}
/**
* A ghost line representing deleted content
*/
export interface GhostRow {
kind: 'ghost';
hunkId: number;
anchorLine: number; // 1-indexed, the line before which this ghost appears
originalLineIndex: number; // 0-indexed line in original code
}
export interface SeparatorRow {
kind: 'separator';
hiddenStart: number; // inclusive, 0-indexed real line
hiddenEnd: number; // inclusive, 0-indexed real line
hiddenCount: number;
}
export type VisualRow = RealRow | GhostRow | SeparatorRow;
export class Renderer {
private container: HTMLDivElement;
private buttonsColumn: HTMLDivElement;
private gutter: HTMLDivElement;
private foldsColumn: HTMLDivElement;
private codeContent: HTMLDivElement;
private diffEnabled: boolean = false;
private lineRenderer: LineRenderer;
private searchRenderer: SearchRenderer;
private diffRenderer: DiffRenderer;
private completionRenderer: CompletionRenderer;
private hoverRenderer: HoverRenderer;
private wordHighlightRenderer: WordHighlightRenderer;
private bracketMatchRenderer: BracketMatchRenderer;
private scrollbarMarkersRenderer: ScrollbarMarkersRenderer;
private visualRows: VisualRow[] = [];
private visualIndexByElement = new WeakMap<HTMLElement, number>();
private lastCollapsedMap: Map<number, number> = new Map();
private lastFoldableStarts: Map<number, number> = new Map();
private lastHiddenLines: Set<number> = new Set();
private codeFoldingEnabled: boolean = true;
private charWidth = 0;
private lastContentMinWidth = -1;
constructor(
container: HTMLDivElement,
buttonsColumn: HTMLDivElement,
gutter: HTMLDivElement,
foldsColumn: HTMLDivElement,
codeContent: HTMLDivElement,
scrollbarMarkersEnabled: boolean = true,
onImmediateScroll?: () => void,
wrapper?: HTMLDivElement
) {
this.container = container;
this.buttonsColumn = buttonsColumn;
this.gutter = gutter;
this.foldsColumn = foldsColumn;
this.codeContent = codeContent;
// Initialize renderers
const diagnosticRenderer = new DiagnosticRenderer();
this.lineRenderer = new LineRenderer(diagnosticRenderer);
this.searchRenderer = new SearchRenderer(
container,
(lineNumber) => this.getLine(lineNumber),
(state, focusLine) => this.revealCursor(state, focusLine)
);
this.diffRenderer = new DiffRenderer(
codeContent,
gutter,
buttonsColumn,
foldsColumn
);
this.completionRenderer = new CompletionRenderer(
container,
(lineNumber) => this.getLine(lineNumber)
);
this.hoverRenderer = new HoverRenderer(
container,
(lineNumber) => this.getLine(lineNumber)
);
this.wordHighlightRenderer = new WordHighlightRenderer(codeContent);
this.bracketMatchRenderer = new BracketMatchRenderer(
codeContent,
(lineNumber) => this.getLine(lineNumber)
);
this.scrollbarMarkersRenderer = new ScrollbarMarkersRenderer(
container,
(state, line) => this.revealLineCenter(state, line),
(state, index) => {
this.searchRenderer.removeSelectedHighlight(state.search);
state.search.setSelected(index);
this.searchRenderer.updateSearchHighlights(state.search);
},
onImmediateScroll,
scrollbarMarkersEnabled,
wrapper
);
}
public setDiffEnabled(enabled: boolean) {
this.diffEnabled = enabled;
}
public clean() {
this.scrollbarMarkersRenderer.clean();
}
public getVisualRowCount(): number {
return this.visualRows.length;
}
public setFocusedDiffMode(enabled: boolean, contextLines: number = 3) {
this.diffRenderer.setFocusedDiffMode(enabled, contextLines);
}
public render(state: EditorState) {
const { code, diffs } = state;
this.codeFoldingEnabled = state.codeFoldingEnabled ?? true;
this.updateFoldableStarts(state);
this.updateCollapsedMap(state);
// Build unified visual rows model (real lines + ghost lines)
const totalRealLines = code.linesLength();
this.visualRows = this.diffEnabled
? this.buildVisualRows(totalRealLines, diffs, code)
: this.buildRealOnlyRows(totalRealLines);
this.renderViewport(state);
const wordLines = this.wordHighlightRenderer.render(state, state.scrollbarMarkersEnabled);
this.renderScrollbarMarkers(state, true, wordLines);
this.updateContentMinWidth(state);
}
private renderViewport(state: EditorState) {
const { settings, readOnly, search } = state;
const totalVisualRows = this.visualRows.length;
const { startIndex, endIndex } = this.getVisibleRange(totalVisualRows, settings);
const itemHeight = settings.lineHeight;
const paddingTop = startIndex * itemHeight;
const paddingBottom = (totalVisualRows - endIndex) * itemHeight;
// Build fragments for better performance
const btnFrag = document.createDocumentFragment();
const gutterFrag = document.createDocumentFragment();
const foldsFrag = document.createDocumentFragment();
const codeFrag = document.createDocumentFragment();
// Top spacers
btnFrag.appendChild(this.lineRenderer.createSpacer(paddingTop));
gutterFrag.appendChild(this.lineRenderer.createSpacer(paddingTop));
foldsFrag.appendChild(this.lineRenderer.createSpacer(paddingTop));
codeFrag.appendChild(this.lineRenderer.createSpacer(paddingTop));
// Render visible slice of visual rows
for (let i = startIndex; i < endIndex; i++) {
const row = this.visualRows[i];
const elements = this.createRow(row, i, state);
codeFrag.appendChild(elements.code);
gutterFrag.appendChild(elements.gutter);
btnFrag.appendChild(elements.btn);
foldsFrag.appendChild(elements.fold);
}
// Bottom spacers
btnFrag.appendChild(this.lineRenderer.createSpacer(paddingBottom));
gutterFrag.appendChild(this.lineRenderer.createSpacer(paddingBottom));
foldsFrag.appendChild(this.lineRenderer.createSpacer(paddingBottom));
codeFrag.appendChild(this.lineRenderer.createSpacer(paddingBottom));
// Replace old children atomically
this.buttonsColumn.replaceChildren(btnFrag);
this.gutter.replaceChildren(gutterFrag);
this.foldsColumn.replaceChildren(foldsFrag);
this.codeContent.replaceChildren(codeFrag);
// Render cursor or selection
if (!readOnly && (!search.isActive() || !search.isFocused())) {
this.renderCursorOrSelection(state);
}
// Render search highlights
if (!readOnly && search.isActive()) {
this.searchRenderer.updateSearchHighlights(search);
}
}
private renderScrollbarMarkers(
state: EditorState | null,
includeSearch: boolean = true,
wordLines?: number[]
) {
const enabled = (state?.scrollbarMarkersEnabled ?? true) && state !== null;
this.scrollbarMarkersRenderer.setEnabled(enabled);
if (!enabled || !state) return;
const limitMarkers = state.code.linesLength() > MAX_SCROLLBAR_MARKER_LINES;
const effectiveWordLines = limitMarkers ? [] : wordLines;
const effectiveIncludeSearch = limitMarkers ? false : includeSearch;
this.scrollbarMarkersRenderer.updateGeometry(
this.container.clientHeight,
this.visualRows.length * state.settings.lineHeight
);
this.scrollbarMarkersRenderer.render(state, effectiveIncludeSearch, effectiveWordLines, this.visualRows);
}
/**
* Build visual rows with only real lines (no ghost lines)
*/
private buildRealOnlyRows(totalLines: number): VisualRow[] {
const rows: VisualRow[] = [];
for (let i = 0; i < totalLines; i++) {
if (this.isHiddenByFold(i)) continue;
rows.push({ kind: 'real', lineIndex: i });
}
return rows;
}
/**
* Build a unified list of visual rows.
* This provides a stable model for virtualized scrolling.
*/
private buildVisualRows(
totalLines: number,
diffs: Map<number, DiffInfo> | undefined,
code: Code,
): VisualRow[] {
const rows: VisualRow[] = [];
const processedHunks = new Set<number>();
const visibleRealLines = this.diffRenderer.computeVisibleLines(totalLines, diffs, code);
const alwaysVisibleLines = code.getAlwaysVisibleLines(totalLines);
if (visibleRealLines && alwaysVisibleLines) {
for (const line of alwaysVisibleLines) visibleRealLines.add(line);
}
// Collect ghost info by anchor line for efficient lookup
const ghostsByAnchor = new Map<number, { hunkId: number; oldLineNumbers: number[] }[]>();
if (diffs) {
for (const [lineNumber, diffInfo] of diffs) {
if (!diffInfo.oldLineNumbers || diffInfo.oldLineNumbers.length === 0) continue;
if (diffInfo.changeType !== 'modified' && diffInfo.changeType !== 'deleted') continue;
const anchorLine = diffInfo.ghostAnchorLine ?? lineNumber;
if (!ghostsByAnchor.has(anchorLine)) {
ghostsByAnchor.set(anchorLine, []);
}
ghostsByAnchor.get(anchorLine)!.push({
hunkId: diffInfo.hunkId,
oldLineNumbers: diffInfo.oldLineNumbers,
});
}
}
// Build visual rows: iterate through lines and insert ghosts before their anchors
for (let i = 0; i < totalLines; i++) {
const lineNumber = i + 1; // 1-indexed for diffs
// Check for ghost lines anchored before this line
const ghostsHere = ghostsByAnchor.get(lineNumber);
if (ghostsHere && !this.isHiddenByFold(i)) {
for (const ghostGroup of ghostsHere) {
if (processedHunks.has(ghostGroup.hunkId)) continue;
processedHunks.add(ghostGroup.hunkId);
for (let ghostIndex = 0; ghostIndex < ghostGroup.oldLineNumbers.length; ghostIndex++) {
const originalLineNumber = ghostGroup.oldLineNumbers[ghostIndex];
if (originalLineNumber < 1) continue;
rows.push({
kind: 'ghost',
hunkId: ghostGroup.hunkId,
anchorLine: lineNumber,
originalLineIndex: originalLineNumber - 1,
});
}
}
}
// Add real lines based on focused mode visibility
if (!visibleRealLines || visibleRealLines.has(i)) {
if (this.isHiddenByFold(i)) continue;
rows.push({ kind: 'real', lineIndex: i });
}
}
// Handle EOF ghosts (deletions anchored after the last line)
const eofAnchor = totalLines + 1;
const eofGhosts = ghostsByAnchor.get(eofAnchor);
const isLastLineFolded = totalLines > 0 && this.isHiddenByFold(totalLines - 1);
if (eofGhosts && !isLastLineFolded) {
for (const ghostGroup of eofGhosts) {
if (processedHunks.has(ghostGroup.hunkId)) continue;
processedHunks.add(ghostGroup.hunkId);
for (let ghostIndex = 0; ghostIndex < ghostGroup.oldLineNumbers.length; ghostIndex++) {
const originalLineNumber = ghostGroup.oldLineNumbers[ghostIndex];
if (originalLineNumber < 1) continue;
rows.push({
kind: 'ghost',
hunkId: ghostGroup.hunkId,
anchorLine: eofAnchor,
originalLineIndex: originalLineNumber - 1,
});
}
}
}
return this.diffRenderer.insertSeparators(
rows,
totalLines,
(lineIndex) => this.isHiddenByFold(lineIndex)
);
}
public clearExpandedDiffRanges(): void {
this.diffRenderer.clearExpandedRanges();
}
public expandFocusedHiddenRange(
hiddenStart: number,
hiddenEnd: number,
amount: number = 5,
side: 'up' | 'down' | 'both' | 'all' = 'both'
): boolean {
return this.diffRenderer.expandRange(hiddenStart, hiddenEnd, amount, side);
}
/**
* Get visual index for a real line number.
* This accounts for ghost lines above the target line.
*/
private getVisualIndexForLine(lineIndex: number): number {
for (let i = 0; i < this.visualRows.length; i++) {
const row = this.visualRows[i];
if (row.kind === 'real' && row.lineIndex === lineIndex) {
return i;
}
}
// In focused diff mode, cursor can temporarily point to a hidden line.
// Snap to nearest rendered real row for scrolling purposes.
let nearestIndex = -1;
let nearestDistance = Number.POSITIVE_INFINITY;
for (let i = 0; i < this.visualRows.length; i++) {
const row = this.visualRows[i];
if (row.kind !== 'real') continue;
const distance = Math.abs(row.lineIndex - lineIndex);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestIndex = i;
}
}
return nearestIndex >= 0 ? nearestIndex : 0;
}
public getVisibleRealLineIndices(): Set<number> {
const lines = new Set<number>();
for (const row of this.visualRows) {
if (row.kind === 'real') {
lines.add(row.lineIndex);
}
}
return lines;
}
/**
* Get visible range based on visual row indices
*/
private getVisibleRange(totalVisualRows: number, settings: EditorSettings) {
const scrollTop = this.container.scrollTop;
const viewHeight = this.container.clientHeight;
const visibleBuffer = settings.buffer;
const itemHeight = settings.lineHeight;
let visibleCount: number;
if (viewHeight > 0) {
visibleCount = Math.ceil(viewHeight / itemHeight);
} else {
const parentHeight = this.container.parentElement?.clientHeight || 0;
const fallbackHeight = parentHeight > 0 ? parentHeight : window.innerHeight;
visibleCount = Math.min(Math.floor(fallbackHeight / itemHeight), totalVisualRows);
}
const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - visibleBuffer);
const endIndex = Math.min(totalVisualRows, startIndex + visibleCount + visibleBuffer * 2);
return { startIndex, endIndex };
}
public renderScroll(state: EditorState) {
const currentScrollTop = this.container.scrollTop;
const { settings, readOnly, search } = state;
const lineHeight = settings.lineHeight;
const buffer = settings.buffer;
// Structural changes rebuild this model through render()/renderChanges().
// Scrolling only consumes the cached visual rows.
if (this.visualRows.length === 0) {
this.render(state);
return;
}
const totalVisualRows = this.visualRows.length;
const { startIndex, endIndex } = this.getVisibleRange(totalVisualRows, settings);
this.ensureSpacers(this.codeContent);
this.ensureSpacers(this.gutter);
this.ensureSpacers(this.buttonsColumn);
this.ensureSpacers(this.foldsColumn);
const topSpacer = this.codeContent.firstChild as HTMLElement;
const bottomSpacer = this.codeContent.lastChild as HTMLElement;
const gutterTopSpacer = this.gutter.firstChild as HTMLElement;
const gutterBottomSpacer = this.gutter.lastChild as HTMLElement;
const btnTopSpacer = this.buttonsColumn.firstChild as HTMLElement;
const btnBottomSpacer = this.buttonsColumn.lastChild as HTMLElement;
const foldsTopSpacer = this.foldsColumn.firstChild as HTMLElement;
const foldsBottomSpacer = this.foldsColumn.lastChild as HTMLElement;
const renderedRange = this.getRenderedRange();
let currentStartIndex = renderedRange?.startIndex ?? -1;
let currentEndIndex = renderedRange?.endIndex ?? -1;
// Check if full re-render is needed
const needFullRerender =
currentStartIndex === -1 ||
startIndex >= currentEndIndex ||
endIndex <= currentStartIndex ||
Math.abs(startIndex - currentStartIndex) > buffer * 2 ||
Math.abs(endIndex - currentEndIndex) > buffer * 2;
if (needFullRerender) {
// Rebuild only the viewport DOM; the structural row model stays cached.
this.renderViewport(state);
return;
}
let changed = false;
// Remove rows from top
while (currentStartIndex < startIndex && this.codeContent.children.length > 2) {
this.codeContent.removeChild(this.codeContent.children[1]);
if (this.gutter.children[1]) {
this.gutter.removeChild(this.gutter.children[1]);
}
if (this.buttonsColumn.children[1]) {
this.buttonsColumn.removeChild(this.buttonsColumn.children[1]);
}
if (this.foldsColumn.children[1]) {
this.foldsColumn.removeChild(this.foldsColumn.children[1]);
}
currentStartIndex++;
changed = true;
}
// Remove rows from bottom
while (currentEndIndex > endIndex && this.codeContent.children.length > 2) {
const index = this.codeContent.children.length - 2;
this.codeContent.removeChild(this.codeContent.children[index]);
if (this.gutter.children[index]) {
this.gutter.removeChild(this.gutter.children[index]);
}
if (this.buttonsColumn.children[index]) {
this.buttonsColumn.removeChild(this.buttonsColumn.children[index]);
}
if (this.foldsColumn.children[index]) {
this.foldsColumn.removeChild(this.foldsColumn.children[index]);
}
currentEndIndex--;
changed = true;
}
// Add rows above
while (currentStartIndex > startIndex) {
currentStartIndex--;
const row = this.visualRows[currentStartIndex];
const elements = this.createRow(row, currentStartIndex, state);
this.codeContent.insertBefore(elements.code, this.codeContent.children[1]);
this.gutter.insertBefore(elements.gutter, this.gutter.children[1]);
this.buttonsColumn.insertBefore(elements.btn, this.buttonsColumn.children[1]);
this.foldsColumn.insertBefore(elements.fold, this.foldsColumn.children[1]);
changed = true;
}
// Add rows below
while (currentEndIndex < endIndex) {
const row = this.visualRows[currentEndIndex];
const elements = this.createRow(row, currentEndIndex, state);
this.codeContent.insertBefore(elements.code, bottomSpacer);
this.gutter.insertBefore(elements.gutter, gutterBottomSpacer);
this.buttonsColumn.insertBefore(elements.btn, btnBottomSpacer);
this.foldsColumn.insertBefore(elements.fold, foldsBottomSpacer);
currentEndIndex++;
changed = true;
}
// Render cursor or selection
if (!readOnly && (!search.isActive() || !search.isFocused())) {
this.renderCursorOrSelection(state);
}
// Render search highlights
if (search.isActive()) {
this.searchRenderer.updateSearchHighlights(search);
}
if (!changed) return;
// Update spacers based on visual indices
const topHeight = Math.round(startIndex * lineHeight);
const bottomHeight = Math.round(Math.max(0, (totalVisualRows - endIndex) * lineHeight));
topSpacer.style.height = `${topHeight}px`;
bottomSpacer.style.height = `${bottomHeight}px`;
gutterTopSpacer.style.height = `${topHeight}px`;
gutterBottomSpacer.style.height = `${bottomHeight}px`;
btnTopSpacer.style.height = `${topHeight}px`;
btnBottomSpacer.style.height = `${bottomHeight}px`;
foldsTopSpacer.style.height = `${topHeight}px`;
foldsBottomSpacer.style.height = `${bottomHeight}px`;
this.scrollbarMarkersRenderer.updateThumbPosition(currentScrollTop);
}
public updateScrollbarThumb() {
this.scrollbarMarkersRenderer.updateThumbPosition(this.container.scrollTop);
}
/**
* Create DOM elements for a visual row (real or ghost)
*/
private createRow(
row: VisualRow,
visualIndex: number,
state: EditorState,
precomputedNodes?: HighlighedNode[]
): RowElements {
const { code, settings, diffs, runLines, errorLines } = state;
let elements: RowElements;
if (row.kind === 'real') {
const multibufferCode = code as Code & {
getMultibufferHeader?: (line: number) => string | null;
getMultibufferLineNumber?: (line: number) => number | null;
};
const syntaxNodes = precomputedNodes || code.getLineNodes(row.lineIndex);
const displayLineNumber = multibufferCode.getMultibufferLineNumber?.(row.lineIndex) ?? undefined;
elements = this.lineRenderer.createLineElements(
row.lineIndex, syntaxNodes, errorLines, settings,
diffs, runLines, this.getFoldIndicator(row.lineIndex), state.wordHighlight,
displayLineNumber,
);
const header = multibufferCode.getMultibufferHeader?.(row.lineIndex);
if (header !== null && header !== undefined) {
elements.code.classList.add('multibuffer-file-header-row');
elements.code.contentEditable = 'false';
elements.gutter.classList.add('multibuffer-file-header-gutter');
elements.gutter.textContent = '';
elements.btn.classList.add('multibuffer-file-header-gutter');
elements.fold.classList.add('multibuffer-file-header-gutter');
}
} else if (row.kind === 'ghost') {
const originalNodes = state.originalCode?.getLineNodes(row.originalLineIndex);
const originalText = state.originalCode?.line(row.originalLineIndex) ?? '';
elements = this.diffRenderer.createGhostRowElements(
row, settings, originalText, originalNodes, state.wordHighlight
);
} else {
elements = this.diffRenderer.createGapRowElements(row, settings);
}
return this.applyVisualIndex(elements, visualIndex);
}
private applyVisualIndex(elements: RowElements, visualIndex: number): RowElements {
this.visualIndexByElement.set(elements.code, visualIndex);
this.visualIndexByElement.set(elements.gutter, visualIndex);
this.visualIndexByElement.set(elements.btn, visualIndex);
this.visualIndexByElement.set(elements.fold, visualIndex);
return elements;
}
private getRenderedRange(): { startIndex: number; endIndex: number } | null {
const children = this.codeContent.children;
const length = children.length;
if (length <= 2) return null;
const firstElement = children[1] as HTMLElement;
const lastElement = children[length - 2] as HTMLElement;
const startIndex = this.getVisualIndex(firstElement);
const endIndex = this.getVisualIndex(lastElement);
if (startIndex === -1 || endIndex === -1) return null;
return {
startIndex,
endIndex: endIndex + 1,
};
}
private getVisualIndex(element: HTMLElement): number {
return this.visualIndexByElement.get(element) ?? -1;
}
public renderChanges(state: EditorState) {
const { code, settings, diffs, search } = state;
this.wordHighlightRenderer.invalidateMarkerLines();
this.codeFoldingEnabled = state.codeFoldingEnabled ?? true;
this.updateFoldableStarts(state);
this.updateCollapsedMap(state);
// Keep a reference to the old visual rows model to identify changes
const oldVisualRows = this.visualRows;
// Rebuild visual rows - structure may have changed
const totalRealLines = code.linesLength();
const newVisualRows = this.diffEnabled
? this.buildVisualRows(totalRealLines, diffs, code)
: this.buildRealOnlyRows(totalRealLines);
if (newVisualRows.length !== oldVisualRows.length) {
// Fallback to full render
this.render(state);
return;
}
// Update visualRows
this.visualRows = newVisualRows;
const renderedRange = this.getRenderedRange();
if (!renderedRange) {
// Fallback to full render
this.render(state);
return;
}
const totalVisualRows = this.visualRows.length;
const visible = this.getVisibleRange(totalVisualRows, settings);
// If viewport changed, do full render
if (renderedRange.startIndex !== visible.startIndex ||
renderedRange.endIndex !== visible.endIndex) {
this.render(state);
return;
}
// Update changed rows in viewport
for (let i = visible.startIndex; i < visible.endIndex; i++) {
const oldRow = oldVisualRows[i];
const newRow = this.visualRows[i];
const childIndex = i - renderedRange.startIndex + 1;
let needsUpdate = false;
let precomputedNodes: HighlighedNode[] | undefined;
if (!oldRow || oldRow.kind !== newRow.kind) {
needsUpdate = true;
} else if (newRow.kind === 'real') {
const oldReal = oldRow as RealRow;
if (oldReal.lineIndex !== newRow.lineIndex) {
needsUpdate = true;
} else {
const nodes = code.getLineNodes(newRow.lineIndex);
const newHash = objectHash(nodes).toString();
const existingLine = this.codeContent.children[childIndex] as AnycodeLine | undefined;
if (!existingLine || existingLine.hash !== newHash) {
needsUpdate = true;
precomputedNodes = nodes;
}
}
} else if (newRow.kind === 'ghost') {
const oldGhost = oldRow as GhostRow;
if (oldGhost.originalLineIndex !== newRow.originalLineIndex ||
oldGhost.hunkId !== newRow.hunkId ||
oldGhost.anchorLine !== newRow.anchorLine) {
needsUpdate = true;
}
} else if (newRow.kind === 'separator') {
const oldSep = oldRow as SeparatorRow;
if (oldSep.hiddenStart !== newRow.hiddenStart ||
oldSep.hiddenEnd !== newRow.hiddenEnd) {
needsUpdate = true;
}
}
if (needsUpdate) {
const row = this.createRow(newRow, i, state, precomputedNodes);
const oldCode = this.codeContent.children[childIndex];
if (oldCode) {
this.codeContent.replaceChild(row.code, oldCode);
}
const oldGutter = this.gutter.children[childIndex];
if (oldGutter) {
this.gutter.replaceChild(row.gutter, oldGutter);
}
const oldBtn = this.buttonsColumn.children[childIndex];
if (oldBtn) {
this.buttonsColumn.replaceChild(row.btn, oldBtn);
}
const oldFold = this.foldsColumn.children[childIndex];
if (oldFold) {
this.foldsColumn.replaceChild(row.fold, oldFold);
}
}
}
// Render search highlights
if (search.isActive()) {
this.searchRenderer.updateSearchHighlights(search);
}
// Render cursor or selection
this.renderCursorOrSelection(state, true);
this.updateContentMinWidth(state);
}
private updateFoldableStarts(state: EditorState) {
const map = new Map<number, number>();
for (const range of state.foldRanges) {
const prevEnd = map.get(range.startLine);
if (prevEnd === undefined || range.endLine > prevEnd) {
map.set(range.startLine, range.endLine);
}
}
this.lastFoldableStarts = map;
}
private updateCollapsedMap(state: EditorState) {
const map = new Map<number, number>();
for (const start of state.collapsedFoldStarts) {
const end = this.lastFoldableStarts.get(start);
if (end !== undefined && end > start) {
map.set(start, end);
}
}
this.lastCollapsedMap = map;
// Pre-build the set of all hidden line indices for O(1) lookups
const hidden = new Set<number>();
if (this.codeFoldingEnabled) {
for (const [start, end] of map) {
for (let i = start + 1; i <= end; i++) {
hidden.add(i);
}
}
}
this.lastHiddenLines = hidden;
}
private isHiddenByFold(lineIndex: number): boolean {
return this.lastHiddenLines.has(lineIndex);
}
private getFoldIndicator(lineIndex: number): { canFold: boolean; collapsed: boolean } {
if (!this.codeFoldingEnabled) {
return { canFold: false, collapsed: false };
}
const end = this.lastFoldableStarts.get(lineIndex);
if (end === undefined || end <= lineIndex) {
return { canFold: false, collapsed: false };
}
return {
canFold: true,
collapsed: this.lastCollapsedMap.has(lineIndex),
};
}
private ensureSpacers(container: HTMLElement) {
const first = container.firstChild as HTMLElement | null;
const last = container.lastChild as HTMLElement | null;
if (!first || !first.classList?.contains('spacer')) {
container.insertBefore(this.lineRenderer.createSpacer(0), container.firstChild);
}
if (!last || !last.classList?.contains('spacer')) {
container.appendChild(this.lineRenderer.createSpacer(0));
}
}
public renderCursorOrSelection(state: EditorState, focus: boolean = false) {
if (!state.cursorActive || state.readOnly) return;
const { code, offset, selection } = state;
if (!selection || selection.isEmpty()) {
const { line, column } = code.getPosition(offset);
this.renderCursor(line, column, focus);
} else {
this.renderSelection(code, selection!);
}
this.renderBracketMatch(state);
}
public renderCursor(line: number, column: number, focus: boolean = false) {
this.codeContent.classList.remove('selecting');
const lineDiv = this.getLine(line);
if (lineDiv) {
if (lineDiv.isConnected) {
moveCursor(lineDiv, column, focus);
} else {
requestAnimationFrame(() => {
moveCursor(lineDiv, column, focus)
});
}
} else {
removeCursor();
}
}
public renderSelection(code: Code, selection: Selection) {
if (selection.isEmpty()) return;
this.codeContent.classList.add('selecting');
const lines = this.getLines();
let attached = true;
for (const l of lines) {
if (!l.isConnected) { attached = false; break; }
}
if (attached) {
renderSelection(selection, lines, code);
} else {
requestAnimationFrame(() => {
renderSelection(selection, this.getLines(), code);
});
}
}
public getLines(): AnycodeLine[] {
return Array.from(this.codeContent.children)
.filter((child) =>
!child.classList.contains('spacer')
&& !isGhostElement(child)
&& child.classList.contains('line')
&& typeof (child as AnycodeLine).lineNumber === 'number'
) as AnycodeLine[];
}
public getLine(lineNumber: number): AnycodeLine | null {
// Iterate through children, skipping spacers and ghost lines
for (let i = 0; i < this.codeContent.children.length; i++) {
const child = this.codeContent.children[i];
if (child.classList.contains('spacer') || isGhostElement(child)) {
continue;
}
const line = child as AnycodeLine;
if (line.lineNumber === lineNumber) {
return line;
}
}
return null;
}
public renderWordHighlight(state: EditorState) {
const wordLines = this.wordHighlightRenderer.render(state, state.scrollbarMarkersEnabled);
this.renderScrollbarMarkers(state, true, wordLines);
}
public renderBracketMatch(state: EditorState) {
this.bracketMatchRenderer.render(state);
}
public revealCursor(state: EditorState, focusLine: number | null = null): boolean {
const { code, offset, settings } = state;
if (!code) return false;
let { line } = code.getPosition(offset);
if (focusLine !== null) line = focusLine;
// For plain files without folds or diffs, visual and source line
// indices are identical. Avoid scanning all rendered rows.
const visualIndex = !this.diffEnabled && state.foldRanges.length === 0
? line
: this.getVisualIndexForLine(line);
const cursorTop = visualIndex * settings.lineHeight;
const cursorBottom = cursorTop + settings.lineHeight;
const renderedRange = this.getRenderedRange();
const isFarInsideRenderedRange = renderedRange !== null
&& visualIndex >= renderedRange.startIndex + settings.buffer
&& visualIndex < renderedRange.endIndex - settings.buffer;
if (isFarInsideRenderedRange) {
return false;
}
const viewportTop = this.container.scrollTop;
const viewportBottom = viewportTop + this.container.clientHeight;
const bottomPaddingLines = 0;
const padding = settings.lineHeight * bottomPaddingLines;
const isCursorVisible = cursorTop >= viewportTop
&& cursorBottom <= viewportBottom - padding;
if (isCursorVisible) {
return false;
}
let targetScrollTop = viewportTop;
if (cursorTop < viewportTop) {
targetScrollTop = cursorTop;
} else if (cursorBottom > viewportBottom - padding) {
targetScrollTop = cursorBottom - this.container.clientHeight + padding;
}
const tolerance = 2;
if (Math.abs(targetScrollTop - viewportTop) > tolerance) {
this.container.scrollTo({ top: targetScrollTop });
this.renderScroll(state);
return true;
}
return false;
}
public revealCursorCenter(state: EditorState): boolean {
const { code, offset } = state;
if (!code) return false;
const { line } = code.getPosition(offset);
return this.revealLineCenter(state, line);
}
private revealLineCenter(state: EditorState, line: number): boolean {
const { code, settings } = state;
if (!code) return false;
// Use visual index to account for ghost lines above cursor
const visualIndex = this.getVisualIndexForLine(line);
const cursorTop = visualIndex * settings.lineHeight;
const cursorCenter = cursorTop + settings.lineHeight / 2;
const viewportHeight = this.container.clientHeight;
const targetScrollTop = cursorCenter - viewportHeight / 2;
const maxScroll = this.container.scrollHeight - viewportHeight;
const clampedScrollTop = Math.max(0, Math.min(targetScrollTop, maxScroll));
this.container.scrollTo({ top: clampedScrollTop });
this.renderScroll(state);
return true;
}
public renderErrors(state: EditorState) {
const { errorLines } = state;
const lines = this.getLines();
if (lines.length) {
for (let i = 0; i < lines.length; i++) {
const lineDiv = lines[i];
const lineNumber = lineDiv.lineNumber;
const message = errorLines.get(lineNumber);