-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
typewriter-scrolling.js
66 lines (65 loc) · 2.46 KB
/
typewriter-scrolling.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
// all credit to azu: https://github.com/azu/codemirror-typewriter-scrolling/blob/b0ac076d72c9445c96182de87d974de2e8cc56e2/typewriter-scrolling.js
"use strict";
var movedByMouse = false;
CodeMirror.commands.scrollSelectionToCenter = function (cm) {
var cursor = cm.getCursor('head');
var charCoords = cm.charCoords(cursor, "local");
var top = charCoords.top;
var halfLineHeight = (charCoords.bottom - top) / 2;
var halfWindowHeight = cm.getWrapperElement().offsetHeight / 2;
var scrollTo = Math.round((top - halfWindowHeight + halfLineHeight));
cm.scrollTo(null, scrollTo);
};
CodeMirror.defineOption("typewriterScrolling", false, function (cm, val, old) {
if (old && old != CodeMirror.Init) {
const linesEl = cm.getScrollerElement().querySelector('.CodeMirror-lines');
linesEl.style.paddingTop = null;
linesEl.style.paddingBottom = null;
cm.off("cursorActivity", onCursorActivity);
cm.off("refresh", onRefresh);
cm.off("mousedown", onMouseDown);
cm.off("keydown", onKeyDown);
cm.off("beforeChange", onBeforeChange);
}
if (val) {
onRefresh(cm);
cm.on("cursorActivity", onCursorActivity);
cm.on("refresh", onRefresh);
cm.on("mousedown", onMouseDown);
cm.on("keydown", onKeyDown);
cm.on("beforeChange", onBeforeChange);
}
});
function onMouseDown() {
movedByMouse = true;
}
const modiferKeys = ["Alt", "AltGraph", "CapsLock", "Control", "Fn", "FnLock", "Hyper", "Meta", "NumLock", "ScrollLock", "Shift", "Super", "Symbol", "SymbolLock"];
function onKeyDown(cm, e) {
if (!modiferKeys.includes(e.key)) {
movedByMouse = false;
}
}
function onBeforeChange() {
movedByMouse = false;
}
function onCursorActivity(cm) {
const linesEl = cm.getScrollerElement().querySelector('.CodeMirror-lines');
if (cm.getSelection().length !== 0) {
linesEl.classList.add("selecting");
}
else {
linesEl.classList.remove("selecting");
}
if(!movedByMouse) {
cm.execCommand("scrollSelectionToCenter");
}
}
function onRefresh(cm) {
const halfWindowHeight = cm.getWrapperElement().offsetHeight / 2;
const linesEl = cm.getScrollerElement().querySelector('.CodeMirror-lines');
linesEl.style.paddingTop = `${halfWindowHeight}px`;
linesEl.style.paddingBottom = `${halfWindowHeight}px`; // Thanks @walulula!
if (cm.getSelection().length === 0) {
cm.execCommand("scrollSelectionToCenter");
}
}