This repository has been archived by the owner on Apr 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
caretfix.py
67 lines (55 loc) · 1.91 KB
/
caretfix.py
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
"""
Basic Caret fixer for non-English environments
"""
from aqt.editor import Editor
from anki.hooks import wrap
def onLoadNote(self):
self.web.eval("""
if (!window._caretFixed) {
window._caretFixed = true;
(function() {
var LEFT = 37, RIGHT = 39;
var tempInput = document.createElement('input');
tempInput.style.position = 'absolute';
tempInput.style.opacity = '0';
tempInput.style.left = '-99999px';
document.body.appendChild(tempInput);
var oldRange = null;
var prevElement = null;
document.addEventListener('keyup', function(event) {
if (event.target.hasAttribute('contenteditable')) {
// Left / Right arrow key -> Reset cursor.
if (event.keyCode == LEFT || event.keyCode == RIGHT) {
var sel = window.getSelection();
oldRange = sel.getRangeAt(0).cloneRange();
if(oldRange.collapsed) {
tempInput.focus();
prevElement = event.target;
py.run("refreshCaret");
}
}
}
}, false);
tempInput.addEventListener('focus', function() {
if(prevElement !== null) {
prevElement.focus();
prevElement = null;
setTimeout(function() {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(oldRange);
oldRange = null;
}, 0);
}
});
})();
}
""")
def caretResetBridge(self, str, _old=None):
if str.startswith("refreshCaret"):
self.web.clearFocus()
self.web.setFocus()
else:
_old(self, str)
Editor.bridge = wrap(Editor.bridge, caretResetBridge, 'around')
Editor.loadNote = wrap(Editor.loadNote, onLoadNote, 'after')