-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathremoteCursor.js
56 lines (44 loc) · 1.68 KB
/
remoteCursor.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
import CSS_COLORS from './cssColors';
import { generateItemFromHash } from './hashAlgo';
import { ANIMALS } from './cursorNames';
export default class RemoteCursor {
constructor(mde, siteId, position) {
this.mde = mde;
const color = generateItemFromHash(siteId, CSS_COLORS);
const name = generateItemFromHash(siteId, ANIMALS);
this.createCursor(color);
this.createFlag(color, name);
this.cursor.appendChild(this.flag);
this.set(position);
}
createCursor(color) {
const textHeight = this.mde.codemirror.defaultTextHeight();
this.cursor = document.createElement('div');
this.cursor.classList.add('remote-cursor');
this.cursor.style.backgroundColor = color;
this.cursor.style.height = textHeight + 'px';
}
createFlag(color, name) {
const cursorName = document.createTextNode(name);
this.flag = document.createElement('span');
this.flag.classList.add('flag');
this.flag.style.backgroundColor = color;
this.flag.appendChild(cursorName)
}
set(position) {
this.detach();
const coords = this.mde.codemirror.cursorCoords(position, 'local');
this.cursor.style.left = (coords.left >= 0 ? coords.left : 0) + 'px';
this.mde.codemirror.getDoc().setBookmark(position, { widget: this.cursor });
this.lastPosition = position;
// Add a zero width-space so line wrapping works (on firefox?)
this.cursor.parentElement.appendChild(document.createTextNode("\u200b"));
}
detach() {
// Used when updating cursor position.
// If cursor exists on the DOM, remove it.
// DO NOT remove cursor's parent. It contains the zero width-space.
if (this.cursor.parentElement)
this.cursor.remove();
}
}