-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhighlightable-editor.js
63 lines (56 loc) · 1.81 KB
/
highlightable-editor.js
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
import {basicSetup} from 'codemirror';
import {EditorState, StateField, StateEffect} from '@codemirror/state';
import {python} from '@codemirror/lang-python';
import {EditorView, Decoration} from '@codemirror/view';
const addLineHighlight = StateEffect.define();
const lineHighlightField = StateField.define({
create() {
return Decoration.none;
},
update(lines, tr) {
lines = lines.map(tr.changes);
for (let e of tr.effects) {
if (e.is(addLineHighlight)) {
lines = Decoration.none;
lines = lines.update({add: [lineHighlightMark.range(e.value)]});
}
}
return lines;
},
provide: (f) => EditorView.decorations.from(f),
});
const lineHighlightMark = Decoration.line({
attributes: {style: 'background-color: #d2ffff'},
});
export default class HighlightableEditor {
constructor(parent, code, onHighlight) {
this.editorView = new EditorView({
state: EditorState.create({
doc: code,
extensions: [basicSetup, lineHighlightField, python()],
}),
parent: parent,
});
this.editorView.dom.addEventListener('mousemove', (event) => {
const lastMove = {
x: event.clientX,
y: event.clientY,
target: event.target,
time: Date.now(),
};
const pos = this.editorView.posAtCoords(lastMove);
let lineNo = this.editorView.state.doc.lineAt(pos).number;
const docPosition = this.editorView.state.doc.line(lineNo).from;
this.editorView.dispatch({effects: addLineHighlight.of(docPosition)});
onHighlight(lineNo);
});
}
getCode() {
return this.editorView.state.doc.toString();
}
highlightLine(lineNo) {
if (lineNo <= 0) return;
const docPosition = this.editorView.state.doc.line(lineNo).from;
this.editorView.dispatch({effects: addLineHighlight.of(docPosition)});
}
}