forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent-to-transform.js
More file actions
49 lines (38 loc) · 1.13 KB
/
event-to-transform.js
File metadata and controls
49 lines (38 loc) · 1.13 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
import { lineAndColumnToIndex } from 'app/utils/monaco-index-converter';
import { TextOperation } from 'ot';
export default function convertChangeEventToOperation(
changeEvent,
liveOperationCode
) {
let otOperation;
let composedCode = liveOperationCode;
// eslint-disable-next-line no-restricted-syntax
for (const change of [...changeEvent.changes]) {
const newOt = new TextOperation();
const cursorStartOffset = lineAndColumnToIndex(
composedCode.split(/\n/),
change.range.startLineNumber,
change.range.startColumn
);
const retain = cursorStartOffset - newOt.targetLength;
if (retain !== 0) {
newOt.retain(retain);
}
if (change.rangeLength > 0) {
newOt.delete(change.rangeLength);
}
if (change.text) {
newOt.insert(change.text);
}
const remaining = composedCode.length - newOt.baseLength;
if (remaining > 0) {
newOt.retain(remaining);
}
otOperation = otOperation ? otOperation.compose(newOt) : newOt;
composedCode = otOperation.apply(liveOperationCode);
}
return {
operation: otOperation,
newCode: composedCode,
};
}