forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
56 lines (43 loc) · 1.29 KB
/
index.ts
File metadata and controls
56 lines (43 loc) · 1.29 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
import { TextOperation } from 'ot';
import { stringDiff } from './lcs';
const MAX_DIFF_SIZE = 10000;
export function findDiff(
originalText: string,
modifiedText: string,
pretty: boolean
) {
return stringDiff(originalText, modifiedText, pretty);
}
export function getTextOperation(originalText: string, modifiedText: string) {
const ot = new TextOperation();
if (Math.max(originalText.length, modifiedText.length) > MAX_DIFF_SIZE) {
ot.delete(originalText.length);
ot.insert(modifiedText);
// eslint-disable-next-line
console.warn(
'Not optimizing edits, file is larger than ' + MAX_DIFF_SIZE + 'b'
);
return ot;
}
const diffs = findDiff(originalText, modifiedText, false);
let lastPos = 0;
diffs.forEach(change => {
const start = change.originalStart;
const end = change.originalStart + change.originalLength;
if (start - lastPos !== 0) {
ot.retain(start - lastPos);
}
lastPos = end;
const oldText = originalText.substr(start, change.originalLength);
const newText = modifiedText.substr(
change.modifiedStart,
change.modifiedLength
);
if (oldText !== newText) {
ot.insert(newText);
ot.delete(change.originalLength);
}
});
ot.retain(originalText.length - ot.baseLength);
return ot;
}