|
1 | 1 | import * as Diff from 'diff' |
2 | 2 | import type { Change } from 'diff' |
| 3 | +import { DIFF_DELETE, DIFF_INSERT, diff_match_patch as DiffMatchPatch } from 'diff-match-patch' |
3 | 4 | import hljs from './highlight' |
4 | 5 | import { DiffType } from './types' |
5 | 6 | import type { DiffLine, DiffStat, SplitDiffLine, SplitViewerChange, UnifiedLine, UnifiedViewerChange } from './types' |
@@ -36,6 +37,27 @@ const renderWords = (prev?: string, current?: string, diffStyle = 'word'): strin |
36 | 37 | .join('') |
37 | 38 | } |
38 | 39 |
|
| 40 | +function diffLines(prev: string, current: string) { |
| 41 | + const dmp = new DiffMatchPatch() |
| 42 | + const a = dmp.diff_linesToChars_(prev, current) |
| 43 | + const linePrev = a.chars1 |
| 44 | + const lineCurrent = a.chars2 |
| 45 | + const lineArray = a.lineArray |
| 46 | + const diffs: any[] = dmp.diff_main(linePrev, lineCurrent, false) |
| 47 | + dmp.diff_charsToLines_(diffs, lineArray) |
| 48 | + return diffs.map((x) => { |
| 49 | + const [type, text] = x |
| 50 | + const count = text.trim().split('\n').length |
| 51 | + const change: Diff.Change = { |
| 52 | + count, |
| 53 | + value: text, |
| 54 | + removed: type === DIFF_DELETE, |
| 55 | + added: type === DIFF_INSERT, |
| 56 | + } |
| 57 | + return change |
| 58 | + }) |
| 59 | +} |
| 60 | + |
39 | 61 | const getHighlightCode = (language: string, code: string) => { |
40 | 62 | const hasModifiedTags = code.match(new RegExp(`(${MODIFIED_START_TAG}|${MODIFIED_CLOSE_TAG})`, 'g')) |
41 | 63 |
|
@@ -137,8 +159,7 @@ export function createSplitDiff( |
137 | 159 | ): SplitViewerChange { |
138 | 160 | const newEmptySplitDiff = (): DiffLine => ({ type: DiffType.EMPTY }) |
139 | 161 | const newSplitDiff = (type: DiffType, num: number, code: string): DiffLine => ({ type, num, code }) |
140 | | - |
141 | | - const changes = Diff.diffLines(oldString, newString) |
| 162 | + const changes = diffLines(oldString, newString) |
142 | 163 |
|
143 | 164 | let delNum = 0 |
144 | 165 | let addNum = 0 |
@@ -301,9 +322,9 @@ export function createUnifiedDiff( |
301 | 322 | newString: string, |
302 | 323 | language = 'plaintext', |
303 | 324 | diffStyle = 'word', |
304 | | - context = 2, |
| 325 | + context = 10, |
305 | 326 | ): UnifiedViewerChange { |
306 | | - const changes = Diff.diffLines(oldString, newString) |
| 327 | + const changes = diffLines(oldString, newString) |
307 | 328 |
|
308 | 329 | let delNum = 0 |
309 | 330 | let addNum = 0 |
|
0 commit comments