-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathAceDiff.ts
More file actions
1073 lines (942 loc) · 30.8 KB
/
Copy pathAceDiff.ts
File metadata and controls
1073 lines (942 loc) · 30.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
/* eslint-disable no-console, @typescript-eslint/no-non-null-assertion */
import type { Ace } from 'ace-builds'
import { makeDiff, cleanupSemantic } from '@sanity/diff-match-patch'
import throttle from './helpers/throttle.js'
import debounce from './helpers/debounce.js'
import normalizeContent from './helpers/normalizeContent.js'
import getCurve from './visuals/getCurve.js'
import getMode from './visuals/getMode.js'
import getTheme from './visuals/getTheme.js'
import getLine from './visuals/getLine.js'
import getEditorHeight from './visuals/getEditorHeight.js'
import createArrow from './visuals/createArrow.js'
import ensureElement from './dom/ensureElement.js'
import query from './dom/query.js'
import C, {
DIFF_EQUAL,
DIFF_DELETE,
DIFF_INSERT,
EDITOR_LEFT,
EDITOR_RIGHT,
LTR,
RTL,
DIFF_GRANULARITY_BROAD,
DIFF_GRANULARITY_SPECIFIC,
type EditorSide,
type CopyDirection,
} from './constants.js'
import type { AceDiffOptions, AceStatic } from './types/options.js'
import type { DiffInfo, CharRange } from './types/diff.js'
import type { EditorInstance, EditorState, AceRange } from './types/ace.js'
// Range module placeholder
let Range: AceRange | null = null
function getRangeModule(ace: AceStatic): AceRange | false {
if (ace.Range) {
return ace.Range
}
const requireFunc = ace.acequire || ace.require
if (requireFunc) {
return requireFunc('ace/range') as AceRange
}
return false
}
// Default options
const defaultOptions = {
ace: undefined as AceStatic | undefined,
mode: null as string | null,
theme: null as string | null,
element: null as HTMLElement | string | null,
diffGranularity: DIFF_GRANULARITY_BROAD as 'specific' | 'broad',
lockScrolling: true,
showDiffs: true,
showConnectors: true,
charDiffs: true,
maxDiffs: 5000,
left: {
id: null as string | null,
content: null as string | null,
mode: null as string | null,
theme: null as string | null,
editable: true,
copyLinkEnabled: true,
},
right: {
id: null as string | null,
content: null as string | null,
mode: null as string | null,
theme: null as string | null,
editable: true,
copyLinkEnabled: true,
},
classes: {
gutterID: 'acediff__gutter',
diff: 'acediff__diffLine',
diffChar: 'acediff__diffChar',
diffGutter: 'acediff__diffGutter',
connector: 'acediff__connector',
newCodeConnectorLink: 'acediff__newCodeConnector',
newCodeConnectorLinkContent: '→',
deletedCodeConnectorLink: 'acediff__deletedCodeConnector',
deletedCodeConnectorLinkContent: '←',
copyRightContainer: 'acediff__copy--right',
copyLeftContainer: 'acediff__copy--left',
},
connectorYOffset: 0,
onDiffReady: null as ((diffs: DiffInfo[]) => void) | null,
}
export default class AceDiff {
options: AceDiffOptions
el!: HTMLElement
editors!: EditorState
diffs: DiffInfo[] = []
lineHeight = 0
gutterSVG: SVGSVGElement | null = null
gutterWidth = 0
gutterHeight = 0
copyLeftContainer: HTMLDivElement | null = null
copyRightContainer: HTMLDivElement | null = null
connectorYOffset = 0
private removeEventHandlers: (() => void) | null = null
constructor(options: Partial<AceDiffOptions> = {}) {
// Deep clone default options and merge with provided options
const clonedDefaults = JSON.parse(
JSON.stringify(defaultOptions),
) as typeof defaultOptions
// Merge options
this.options = {
...clonedDefaults,
...options,
left: { ...clonedDefaults.left, ...options.left },
right: { ...clonedDefaults.right, ...options.right },
classes: { ...clonedDefaults.classes, ...options.classes },
}
const getDefaultAce = (): AceStatic | undefined =>
typeof window !== 'undefined'
? (window as unknown as { ace?: AceStatic }).ace
: undefined
if (!this.options.ace) {
this.options.ace = getDefaultAce()
}
const { ace } = this.options
if (!ace) {
const errMessage =
'No ace editor found nor supplied - `options.ace` or `window.ace` is missing'
console.error(errMessage)
throw new Error(errMessage)
}
const rangeModule = getRangeModule(ace)
if (!rangeModule) {
const errMessage =
'Could not require Range module for Ace. Depends on your bundling strategy, but it usually comes with Ace itself. See https://ace.c9.io/api/range.html, open an issue on GitHub ace-diff/ace-diff'
console.error(errMessage)
throw new Error(errMessage)
}
Range = rangeModule
if (this.options.element === null) {
const errMessage =
'You need to specify an element for Ace-diff - `options.element` is missing'
console.error(errMessage)
throw new Error(errMessage)
}
if (this.options.element instanceof HTMLElement) {
this.el = this.options.element
} else {
const foundEl = document.body.querySelector<HTMLElement>(
this.options.element,
)
if (!foundEl) {
const errMessage = `Can't find the specified element ${this.options.element}`
console.error(errMessage)
throw new Error(errMessage)
}
this.el = foundEl
}
this.options.left.id = ensureElement(this.el, 'acediff__left')
this.options.classes.gutterID = ensureElement(this.el, 'acediff__gutter')
this.options.right.id = ensureElement(this.el, 'acediff__right')
this.el.innerHTML = `<div class="acediff acediff__wrap">${this.el.innerHTML}</div>`
// instantiate the editors
this.editors = {
left: {
ace: ace.edit(this.options.left.id!),
markers: [],
lineLengths: [],
diffGutters: [],
},
right: {
ace: ace.edit(this.options.right.id!),
markers: [],
lineLengths: [],
diffGutters: [],
},
editorHeight: null,
}
// set up the editors
this.editors.left.ace.getSession().setMode(getMode(this, EDITOR_LEFT) ?? '')
this.editors.right.ace
.getSession()
.setMode(getMode(this, EDITOR_RIGHT) ?? '')
this.editors.left.ace.setReadOnly(!this.options.left.editable)
this.editors.right.ace.setReadOnly(!this.options.right.editable)
this.editors.left.ace.setShowFoldWidgets(false)
this.editors.right.ace.setShowFoldWidgets(false)
this.editors.left.ace.setTheme(getTheme(this, EDITOR_LEFT) ?? '')
this.editors.right.ace.setTheme(getTheme(this, EDITOR_RIGHT) ?? '')
this.editors.left.ace.setValue(
normalizeContent(this.options.left.content ?? null),
-1,
)
this.editors.right.ace.setValue(
normalizeContent(this.options.right.content ?? null),
-1,
)
// store the visible height of the editors
this.editors.editorHeight = getEditorHeight(this)
// The lineHeight is set to 0 initially and we need to wait for another tick
setTimeout(() => {
this.lineHeight = this.editors.left.ace.renderer.lineHeight
this.addEventHandlers()
this.createCopyContainers()
this.createGutter()
this.diff()
}, 1)
}
// Public methods
setOptions(options: Partial<AceDiffOptions>): void {
this.options = {
...this.options,
...options,
left: { ...this.options.left, ...options.left },
right: { ...this.options.right, ...options.right },
classes: { ...this.options.classes, ...options.classes },
}
this.diff()
}
getNumDiffs(): number {
return this.diffs.length
}
getEditors(): { left: Ace.Editor; right: Ace.Editor } {
return {
left: this.editors.left.ace,
right: this.editors.right.ace,
}
}
diff(): void {
const val1 = this.editors.left.ace.getSession().getValue()
const val2 = this.editors.right.ace.getSession().getValue()
const diff = cleanupSemantic(makeDiff(val2, val1))
this.editors.left.lineLengths = this.getLineLengths(this.editors.left)
this.editors.right.lineLengths = this.getLineLengths(this.editors.right)
const diffs: DiffInfo[] = []
const offset = { left: 0, right: 0 }
diff.forEach((chunk) => {
const chunkType = chunk[0]
const text = chunk[1]
if (text.length === 0) return
if (chunkType === DIFF_EQUAL) {
offset.left += text.length
offset.right += text.length
} else if (chunkType === DIFF_DELETE) {
diffs.push(
this.computeDiff(DIFF_DELETE, offset.left, offset.right, text),
)
offset.right += text.length
} else if (chunkType === DIFF_INSERT) {
diffs.push(
this.computeDiff(DIFF_INSERT, offset.left, offset.right, text),
)
offset.left += text.length
}
})
this.diffs = this.simplifyDiffs(diffs)
if (this.diffs.length > this.options.maxDiffs) {
return
}
this.clearDiffs()
this.decorate()
if (typeof this.options.onDiffReady === 'function') {
this.options.onDiffReady(this.diffs)
}
}
clear(): void {
this.clearDiffs()
this.clearGutter()
this.clearArrows()
}
destroy(): void {
const leftValue = this.editors.left.ace.getValue()
this.editors.left.ace.destroy()
let oldDiv = this.editors.left.ace.container
let newDiv = oldDiv.cloneNode(false) as HTMLElement
newDiv.textContent = leftValue
oldDiv.parentNode?.replaceChild(newDiv, oldDiv)
const rightValue = this.editors.right.ace.getValue()
this.editors.right.ace.destroy()
oldDiv = this.editors.right.ace.container
newDiv = oldDiv.cloneNode(false) as HTMLElement
newDiv.textContent = rightValue
oldDiv.parentNode?.replaceChild(newDiv, oldDiv)
const elementById = document.getElementById(this.options.classes.gutterID!)
if (elementById) {
elementById.innerHTML = ''
}
this.removeEventHandlers?.()
}
// Private methods
private addEventHandlers(): void {
let isSyncingScroll = false
const syncScroll = (
sourceEditor: EditorInstance,
targetEditor: EditorInstance,
): void => {
if (!this.options.lockScrolling || isSyncingScroll) return
const sourceSession = sourceEditor.ace.getSession()
const targetSession = targetEditor.ace.getSession()
const sourceScrollTop = sourceSession.getScrollTop()
const sourceLineCount = sourceSession.getLength()
const sourceContentHeight = sourceLineCount * this.lineHeight
const sourceViewportHeight = (
sourceEditor.ace.renderer as unknown as {
$size: { scrollerHeight: number }
}
).$size.scrollerHeight
const sourceMaxScroll = Math.max(
0,
sourceContentHeight - sourceViewportHeight,
)
const scrollRatio =
sourceMaxScroll > 0 ? sourceScrollTop / sourceMaxScroll : 0
const targetLineCount = targetSession.getLength()
const targetContentHeight = targetLineCount * this.lineHeight
const targetViewportHeight = (
targetEditor.ace.renderer as unknown as {
$size: { scrollerHeight: number }
}
).$size.scrollerHeight
const targetMaxScroll = Math.max(
0,
targetContentHeight - targetViewportHeight,
)
const targetScrollTop = scrollRatio * targetMaxScroll
isSyncingScroll = true
targetSession.setScrollTop(targetScrollTop)
isSyncingScroll = false
}
this.editors.left.ace.getSession().on(
'changeScrollTop',
throttle(() => {
syncScroll(this.editors.left, this.editors.right)
this.updateGap()
}, 16),
)
this.editors.right.ace.getSession().on(
'changeScrollTop',
throttle(() => {
syncScroll(this.editors.right, this.editors.left)
this.updateGap()
}, 16),
)
const diffBound = this.diff.bind(this)
this.editors.left.ace.on('change', diffBound)
this.editors.right.ace.on('change', diffBound)
if (this.options.left.copyLinkEnabled) {
query(
`#${this.options.classes.gutterID}`,
'click',
`.${this.options.classes.newCodeConnectorLink}`,
(e) => this.copy(e, LTR),
)
}
if (this.options.right.copyLinkEnabled) {
query(
`#${this.options.classes.gutterID}`,
'click',
`.${this.options.classes.deletedCodeConnectorLink}`,
(e) => this.copy(e, RTL),
)
}
const onResize = debounce(() => {
const leftEl = document.getElementById(this.options.left.id!)
if (leftEl) {
;(this.editors as { availableHeight?: number }).availableHeight =
leftEl.offsetHeight
}
this.diff()
}, 250)
window.addEventListener('resize', onResize)
this.removeEventHandlers = () => {
window.removeEventListener('resize', onResize)
}
}
private copy(e: Event, dir: CopyDirection): void {
const target = e.target as HTMLElement
const diffIndex = parseInt(
target.getAttribute('data-diff-index') ?? '0',
10,
)
const diff = this.diffs[diffIndex]
if (!diff) return
// Don't allow copying into a non-editable editor
if (dir === LTR && !this.options.right.editable) return
if (dir === RTL && !this.options.left.editable) return
let sourceEditor: EditorInstance
let targetEditor: EditorInstance
let sourceStartOffset: number
let sourceEndOffset: number
let targetStartOffset: number
let targetEndOffset: number
if (dir === LTR) {
sourceEditor = this.editors.left
targetEditor = this.editors.right
sourceStartOffset = diff.leftStartOffset
sourceEndOffset = diff.leftEndOffset
targetStartOffset = diff.rightStartOffset
targetEndOffset = diff.rightEndOffset
} else {
sourceEditor = this.editors.right
targetEditor = this.editors.left
sourceStartOffset = diff.rightStartOffset
sourceEndOffset = diff.rightEndOffset
targetStartOffset = diff.leftStartOffset
targetEndOffset = diff.leftEndOffset
}
const sourceValue = sourceEditor.ace.getValue()
const contentToInsert = sourceValue.substring(
sourceStartOffset,
sourceEndOffset,
)
const targetDoc = targetEditor.ace.getSession().doc
const startPos = targetDoc.indexToPosition(targetStartOffset, 0)
const endPos = targetDoc.indexToPosition(targetEndOffset, 0)
const h = targetEditor.ace.getSession().getScrollTop()
if (Range) {
targetEditor.ace
.getSession()
.replace(
new Range(startPos.row, startPos.column, endPos.row, endPos.column),
contentToInsert,
)
}
targetEditor.ace.getSession().setScrollTop(parseInt(String(h), 10))
this.diff()
}
private getLineLengths(editor: EditorInstance): number[] {
const lines = editor.ace.getSession().doc.getAllLines()
return lines.map((line: string) => line.length + 1)
}
private showDiff(
editor: EditorSide,
startLine: number,
endLine: number,
chars: CharRange[],
className: string,
): void {
const editorInstance = this.editors[editor]
let actualEndLine = endLine
if (actualEndLine < startLine) {
actualEndLine = startLine
}
const classNames = `${className} ${
actualEndLine > startLine ? 'lines' : 'targetOnly'
} ${editor}`
let markerEndLine = actualEndLine
if (markerEndLine > startLine) {
markerEndLine -= 1
}
if (Range) {
editorInstance.markers.push(
editorInstance.ace.session.addMarker(
new Range(startLine, 0, markerEndLine, 1),
classNames,
'fullLine',
),
)
}
if (this.options.charDiffs && chars && chars.length > 0) {
const charClassName = `${this.options.classes.diffChar} ${editor}`
chars.forEach((char) => {
if (Range) {
editorInstance.markers.push(
editorInstance.ace.session.addMarker(
new Range(char.lineStart, char.start, char.lineEnd - 1, char.end),
charClassName,
'text',
),
)
}
})
}
const gutterClassName = `${this.options.classes.diffGutter} ${editor}`
for (let line = startLine; line < actualEndLine; line += 1) {
editorInstance.ace.session.addGutterDecoration(line, gutterClassName)
editorInstance.diffGutters.push({ line, className: gutterClassName })
}
}
private updateGap(): void {
this.clearDiffs()
this.decorate()
this.positionCopyContainers()
}
private clearDiffs(): void {
this.editors.left.markers.forEach((marker) => {
this.editors.left.ace.getSession().removeMarker(marker)
})
this.editors.right.markers.forEach((marker) => {
this.editors.right.ace.getSession().removeMarker(marker)
})
this.editors.left.markers = []
this.editors.right.markers = []
this.editors.left.diffGutters.forEach((gutter) => {
this.editors.left.ace.session.removeGutterDecoration(
gutter.line,
gutter.className,
)
})
this.editors.right.diffGutters.forEach((gutter) => {
this.editors.right.ace.session.removeGutterDecoration(
gutter.line,
gutter.className,
)
})
this.editors.left.diffGutters = []
this.editors.right.diffGutters = []
}
private addConnector(
leftStartLine: number,
leftEndLine: number,
rightStartLine: number,
rightEndLine: number,
): void {
const leftScrollTop = this.editors.left.ace.getSession().getScrollTop()
const rightScrollTop = this.editors.right.ace.getSession().getScrollTop()
this.connectorYOffset = 1
const p1_x = -1
const p1_y = leftStartLine * this.lineHeight - leftScrollTop + 0.5
const p2_x = this.gutterWidth + 1
const p2_y = rightStartLine * this.lineHeight - rightScrollTop + 0.5
const p3_x = -1
const p3_y =
leftEndLine * this.lineHeight -
leftScrollTop +
this.connectorYOffset +
0.5
const p4_x = this.gutterWidth + 1
const p4_y =
rightEndLine * this.lineHeight -
rightScrollTop +
this.connectorYOffset +
0.5
const curve1 = getCurve(p1_x, p1_y, p2_x, p2_y)
const curve2 = getCurve(p4_x, p4_y, p3_x, p3_y)
const verticalLine1 = `L${p2_x},${p2_y} ${p4_x},${p4_y}`
const verticalLine2 = `L${p3_x},${p3_y} ${p1_x},${p1_y}`
const d = `${curve1} ${verticalLine1} ${curve2} ${verticalLine2}`
const el = document.createElementNS(C.SVG_NS, 'path')
el.setAttribute('d', d)
el.setAttribute('class', this.options.classes.connector ?? '')
this.gutterSVG?.appendChild(el)
}
private addCopyArrows(info: DiffInfo, diffIndex: number): void {
// "Copy to right" arrow: only show if left has content to copy,
// left.copyLinkEnabled is true, AND the right editor is editable
if (
info.leftEndLine > info.leftStartLine &&
this.options.left.copyLinkEnabled &&
this.options.right.editable
) {
const arrow = createArrow({
className: this.options.classes.newCodeConnectorLink ?? '',
topOffset: info.leftStartLine * this.lineHeight,
tooltip: 'Copy to right',
diffIndex,
arrowContent: this.options.classes.newCodeConnectorLinkContent ?? '',
})
this.copyRightContainer?.appendChild(arrow)
}
// "Copy to left" arrow: only show if right has content to copy,
// right.copyLinkEnabled is true, AND the left editor is editable
if (
info.rightEndLine > info.rightStartLine &&
this.options.right.copyLinkEnabled &&
this.options.left.editable
) {
const arrow = createArrow({
className: this.options.classes.deletedCodeConnectorLink ?? '',
topOffset: info.rightStartLine * this.lineHeight,
tooltip: 'Copy to left',
diffIndex,
arrowContent:
this.options.classes.deletedCodeConnectorLinkContent ?? '',
})
this.copyLeftContainer?.appendChild(arrow)
}
}
private positionCopyContainers(): void {
const leftTopOffset = this.editors.left.ace.getSession().getScrollTop()
const rightTopOffset = this.editors.right.ace.getSession().getScrollTop()
if (this.copyRightContainer) {
this.copyRightContainer.style.cssText = `top: ${-leftTopOffset}px`
}
if (this.copyLeftContainer) {
this.copyLeftContainer.style.cssText = `top: ${-rightTopOffset}px`
}
}
private computeDiff(
diffType: number,
offsetLeft: number,
offsetRight: number,
diffText: string,
): DiffInfo {
let lineInfo: Partial<DiffInfo> = {}
if (diffType === DIFF_INSERT) {
const info = this.getSingleDiffInfo(
this.editors.left,
offsetLeft,
diffText,
)
const currentLineOtherEditor = this.getLineForCharPosition(
this.editors.right,
offsetRight,
)
const numCharsOnLineOtherEditor = this.getCharsOnLine(
this.editors.right,
currentLineOtherEditor,
)
const numCharsOnLeftEditorStartLine = this.getCharsOnLine(
this.editors.left,
info.startLine,
)
const rightStartLine = currentLineOtherEditor
const sameLineInsert = info.startLine === info.endLine
let numRows = 0
if (
(info.startChar > 0 ||
(sameLineInsert &&
diffText.length < numCharsOnLeftEditorStartLine)) &&
numCharsOnLineOtherEditor > 0 &&
info.startChar < numCharsOnLeftEditorStartLine
) {
numRows++
}
lineInfo = {
leftStartLine: info.startLine,
leftEndLine: info.endLine + 1,
rightStartLine,
rightEndLine: rightStartLine + numRows,
leftStartOffset: offsetLeft,
leftEndOffset: offsetLeft + diffText.length,
rightStartOffset: offsetRight,
rightEndOffset: offsetRight,
leftStartChar: info.startChar,
leftEndChar: info.endChar,
}
} else {
const info = this.getSingleDiffInfo(
this.editors.right,
offsetRight,
diffText,
)
const currentLineOtherEditor = this.getLineForCharPosition(
this.editors.left,
offsetLeft,
)
const numCharsOnLineOtherEditor = this.getCharsOnLine(
this.editors.left,
currentLineOtherEditor,
)
const numCharsOnRightEditorStartLine = this.getCharsOnLine(
this.editors.right,
info.startLine,
)
const leftStartLine = currentLineOtherEditor
const sameLineInsert = info.startLine === info.endLine
let numRows = 0
if (
(info.startChar > 0 ||
(sameLineInsert &&
diffText.length < numCharsOnRightEditorStartLine)) &&
numCharsOnLineOtherEditor > 0 &&
info.startChar < numCharsOnRightEditorStartLine
) {
numRows++
}
lineInfo = {
leftStartLine,
leftEndLine: leftStartLine + numRows,
rightStartLine: info.startLine,
rightEndLine: info.endLine + 1,
leftStartOffset: offsetLeft,
leftEndOffset: offsetLeft,
rightStartOffset: offsetRight,
rightEndOffset: offsetRight + diffText.length,
rightStartChar: info.startChar,
rightEndChar: info.endChar,
}
}
return lineInfo as DiffInfo
}
private getSingleDiffInfo(
editor: EditorInstance,
offset: number,
diffString: string,
): {
startLine: number
startChar: number
endLine: number
endChar: number
} {
const info = {
startLine: 0,
startChar: 0,
endLine: 0,
endChar: 0,
}
const endCharNum = offset + diffString.length
let runningTotal = 0
let startLineSet = false
let endLineSet = false
editor.lineLengths.forEach((lineLength, lineIndex) => {
runningTotal += lineLength
if (!startLineSet && offset < runningTotal) {
info.startLine = lineIndex
info.startChar = offset - runningTotal + lineLength
startLineSet = true
}
if (!endLineSet && endCharNum <= runningTotal) {
info.endLine = lineIndex
info.endChar = endCharNum - runningTotal + lineLength
endLineSet = true
}
})
if (
info.startChar > 0 &&
this.getCharsOnLine(editor, info.startLine) === info.startChar
) {
info.startLine++
info.startChar = 0
}
if (info.endChar === 0) {
info.endLine--
}
const endsWithNewline = /\n$/.test(diffString)
if (info.startChar > 0 && endsWithNewline) {
info.endLine++
}
return info
}
private getCharsOnLine(editor: EditorInstance, line: number): number {
return getLine(editor, line).length
}
private getLineForCharPosition(
editor: EditorInstance,
offsetChars: number,
): number {
const lines: string[] = editor.ace.getSession().doc.getAllLines()
let foundLine = 0
let runningTotal = 0
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i]
if (line !== undefined) {
runningTotal += line.length + 1
}
if (offsetChars <= runningTotal) {
foundLine = i
if (offsetChars === runningTotal && i < lines.length - 1) {
foundLine += 1
}
break
}
}
if (runningTotal >= editor.ace.getSession().getValue().length) {
foundLine += 1
}
return foundLine
}
private createGutter(): void {
const gutterEl = document.getElementById(this.options.classes.gutterID!)
if (!gutterEl) return
this.gutterHeight = gutterEl.clientHeight
this.gutterWidth = gutterEl.clientWidth
const leftHeight = this.getTotalHeight(EDITOR_LEFT)
const rightHeight = this.getTotalHeight(EDITOR_RIGHT)
const height = Math.max(leftHeight, rightHeight, this.gutterHeight)
this.gutterSVG = document.createElementNS(C.SVG_NS, 'svg')
this.gutterSVG.setAttribute('width', String(this.gutterWidth))
this.gutterSVG.setAttribute('height', String(height))
gutterEl.appendChild(this.gutterSVG)
}
private getTotalHeight(editor: EditorSide): number {
const ed = editor === EDITOR_LEFT ? this.editors.left : this.editors.right
return ed.ace.getSession().getLength() * this.lineHeight
}
private createCopyContainers(): void {
this.copyRightContainer = document.createElement('div')
this.copyRightContainer.setAttribute(
'class',
this.options.classes.copyRightContainer ?? '',
)
this.copyLeftContainer = document.createElement('div')
this.copyLeftContainer.setAttribute(
'class',
this.options.classes.copyLeftContainer ?? '',
)
const gutterEl = document.getElementById(this.options.classes.gutterID!)
if (gutterEl) {
gutterEl.appendChild(this.copyRightContainer)
gutterEl.appendChild(this.copyLeftContainer)
}
}
private clearGutter(): void {
const gutterEl = document.getElementById(this.options.classes.gutterID!)
if (gutterEl && this.gutterSVG) {
gutterEl.removeChild(this.gutterSVG)
}
this.createGutter()
}
private clearArrows(): void {
if (this.copyLeftContainer) {
this.copyLeftContainer.innerHTML = ''
}
if (this.copyRightContainer) {
this.copyRightContainer.innerHTML = ''
}
}
private simplifyDiffs(diffs: DiffInfo[]): DiffInfo[] {
const groupedDiffs: DiffInfo[] = []
const compare = (val: number): boolean =>
this.options.diffGranularity === DIFF_GRANULARITY_SPECIFIC
? val < 1
: val <= 1
const createDiffWithChars = (diff: Partial<DiffInfo>): DiffInfo => {
const newDiff: DiffInfo = {
...diff,
leftChars: [],
rightChars: [],
} as DiffInfo
if (diff.leftEndChar !== undefined) {
newDiff.leftChars.push({
start: diff.leftStartChar ?? 0,
end: diff.leftEndChar,
lineStart: diff.leftStartLine ?? 0,
lineEnd: diff.leftEndLine ?? 0,
})
}
if (diff.rightEndChar !== undefined) {
newDiff.rightChars.push({
start: diff.rightStartChar ?? 0,
end: diff.rightEndChar,
lineStart: diff.rightStartLine ?? 0,
lineEnd: diff.rightEndLine ?? 0,
})
}
return newDiff
}
diffs.forEach((diff, index) => {
if (index === 0) {
groupedDiffs.push(createDiffWithChars(diff))
return
}
let isGrouped = false
for (let i = 0; i < groupedDiffs.length; i += 1) {
if (
compare(
Math.abs(diff.leftStartLine - groupedDiffs[i]!.leftEndLine),
) &&
compare(Math.abs(diff.rightStartLine - groupedDiffs[i]!.rightEndLine))
) {
groupedDiffs[i]!.leftStartLine = Math.min(
diff.leftStartLine,
groupedDiffs[i]!.leftStartLine,
)
groupedDiffs[i]!.rightStartLine = Math.min(
diff.rightStartLine,
groupedDiffs[i]!.rightStartLine,
)
groupedDiffs[i]!.leftEndLine = Math.max(
diff.leftEndLine,
groupedDiffs[i]!.leftEndLine,
)
groupedDiffs[i]!.rightEndLine = Math.max(
diff.rightEndLine,
groupedDiffs[i]!.rightEndLine,
)
groupedDiffs[i]!.leftStartOffset = Math.min(
diff.leftStartOffset,
groupedDiffs[i]!.leftStartOffset,
)
groupedDiffs[i]!.leftEndOffset = Math.max(
diff.leftEndOffset,
groupedDiffs[i]!.leftEndOffset,
)
groupedDiffs[i]!.rightStartOffset = Math.min(
diff.rightStartOffset,
groupedDiffs[i]!.rightStartOffset,
)
groupedDiffs[i]!.rightEndOffset = Math.max(