Skip to content

Commit c95179c

Browse files
committed
Extract code for computing byte offsets in the source text
1 parent da0174a commit c95179c

File tree

1 file changed

+32
-13
lines changed

1 file changed

+32
-13
lines changed

ui/frontend/Editor.tsx

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,35 @@ import AdvancedEditor from './AdvancedEditor';
66
import { CommonEditorProps, Editor as EditorType, Position } from './types';
77
import { State } from './reducers';
88

9+
class CodeByteOffsets {
10+
readonly code: string;
11+
readonly lines: string[];
12+
13+
constructor(code: string) {
14+
this.code = code;
15+
this.lines = code.split('\n');
16+
}
17+
18+
public lineToOffsets(line: number) {
19+
const precedingBytes = this.bytesBeforeLine(line);
20+
21+
const highlightedLine = this.lines[line];
22+
const highlightedBytes = highlightedLine.length;
23+
24+
return [precedingBytes, precedingBytes + highlightedBytes];
25+
}
26+
27+
private bytesBeforeLine(line: number) {
28+
// Subtract one as this logic is zero-based and the lines are one-based
29+
line -= 1;
30+
31+
const precedingLines = this.lines.slice(0, line);
32+
33+
// Add one to account for the newline we split on and removed
34+
return precedingLines.map(l => l.length + 1).reduce((a, b) => a + b);
35+
}
36+
}
37+
938
class SimpleEditor extends React.PureComponent<CommonEditorProps> {
1039
private _editor: HTMLTextAreaElement;
1140

@@ -43,20 +72,10 @@ class SimpleEditor extends React.PureComponent<CommonEditorProps> {
4372
if (!newPosition || !editor) { return; }
4473
if (newPosition === oldPosition) { return; }
4574

46-
// Subtract one as this logix is zero-based and the lines are one-based
47-
const line = newPosition.line - 1;
48-
const { code } = this.props;
49-
50-
const lines = code.split('\n');
51-
52-
const precedingLines = lines.slice(0, line);
53-
const highlightedLine = lines[line];
54-
55-
// Add one to account for the newline we split on and removed
56-
const precedingBytes = precedingLines.map(l => l.length + 1).reduce((a, b) => a + b);
57-
const highlightedBytes = highlightedLine.length;
75+
const offsets = new CodeByteOffsets(this.props.code);
76+
const [startBytes, endBytes] = offsets.lineToOffsets(newPosition.line);
5877

59-
editor.setSelectionRange(precedingBytes, precedingBytes + highlightedBytes);
78+
editor.setSelectionRange(startBytes, endBytes);
6079
}
6180
}
6281

0 commit comments

Comments
 (0)