-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
83 lines (67 loc) · 2.16 KB
/
main.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Ankibookmarklet {
constructor() {
this.point = {
x: 0,
y: 0,
};
this.note = {};
this.options = loadOptions();
this.popup = new Popup();
this.translator = new Translator();
this.target = new Ankimobile();
this.timeout = null;
window.addEventListener('mousemove', e => this.onMouseMove(e));
window.addEventListener('mousedown', e => this.onMouseDown(e));
window.addEventListener('touchstart', e => this.onTouchStart(e));
window.addEventListener('message', e => this.onFrameMessage(e));
document.addEventListener('selectionchange', e => this.userSelectionChanged(e));
window.addEventListener('selectionend', e => this.onSelectionEnd(e));
showIndicator(this.options);
}
onMouseMove(e) {
this.point = {
x: e.clientX,
y: e.clientY,
};
}
userSelectionChanged(e) {
// wait 500 ms after the last selection change event
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = setTimeout(() => {
var selEndEvent = new CustomEvent("selectionend");
window.dispatchEvent(selEndEvent);
}, 500);
}
onSelectionEnd(e) {
// reset selection timeout
this.timeout = null;
const selection = window.getSelection();
const word = (selection.toString() || '').trim();
this.translator.getTranslation(word).then((note) => {
if (!note) return;
note.sentence = getSentence(word);
this.note = note;
const content = renderPopup(note, this.options);
this.popup.showNextTo({
x: this.point.x,
y: this.point.y,
}, content);
}).catch(err => console.log(err));
}
onMouseDown(e) {
this.popup.hide();
}
onTouchStart(e) {
this.popup.hide();
const touch = e.touches[0];
this.point = {
x: touch.clientX,
y: touch.clientY,
};
}
onFrameMessage(e) {
this.target.addNote(this.note, this.options);
}
}