Skip to content

Instantly share code, notes, and snippets.

@aslushnikov
Last active September 26, 2018 07:39
Show Gist options
  • Save aslushnikov/8583301 to your computer and use it in GitHub Desktop.
Save aslushnikov/8583301 to your computer and use it in GitHub Desktop.
definition of `fake` function to emulate keyboard events in CodeMirror instance. Useful for testing; depends on availability of `codeMirror.triggerOnKeyPress/triggerOnKeyUp` events.
var editor = new CodeMirror({ /* ... */ });
fake(editor, "("); // if you have closebrackets.js addon switched on, this will actually generate "()"
fake(editor, "enter"); // all the crazy indenting logic will be used
fake(editor, "e"); // just letter "e"
fake(editor, 48); // 0
fake(editor, "leftArrow", ["ctrlKey", "shiftKey"]);
// pretty names to use for codes, e.g. `fake("leftArrow")`
var prettyCodeNames = {
enter: 13,
home: 36,
leftArrow: 37,
upArrow: 38,
rightArrow: 39,
downArrow: 40
};
function createCodeMirrorFakeEvent(type, code, modifiers, charCode)
{
var e = {
_handled: false,
type: type,
charCode: charCode,
keyCode: code,
preventDefault: function(){ this._handled = true; },
stopPropagation: function(){},
};
if (modifiers) {
for (var i = 0; i < modifiers.length; ++i)
e[modifiers[i]] = true;
}
return e;
}
function fakeCMKeyEvent(editor, eventType, code, modifiers, charCode)
{
var e = createCodeMirrorFakeEvent(eventType, code, modifiers, charCode);
switch(eventType) {
case "keydown": editor.triggerOnKeyDown(e); break;
case "keypress": editor.triggerOnKeyPress(e); break;
case "keyup": editor.triggerOnKeyUp(e); break;
default: throw new Error("Unknown event type");
}
return e._handled;
}
function fakeCMInput(editor, char)
{
if (typeof char === "string")
editor.display.input.value += char;
}
function fake(editor, originalCode, modifiers)
{
modifiers = modifiers || [];
var code;
var charCode;
if (originalCode === "(") {
code = "9".charCodeAt(0);
modifiers.push("shiftKey");
charCode = "(".charCodeAt(0);
}
code = code || prettyCodeNames[originalCode] || originalCode;
if (typeof code === "string")
code = code.charCodeAt(0);
if (fakeCMKeyEvent(editor, "keydown", code, modifiers, charCode))
return;
if (fakeCMKeyEvent(editor, "keypress", code, modifiers, charCode))
return;
fakeCMInput(editor, originalCode);
fakeCMKeyEvent(editor, "keyup", code, modifiers, charCode);
}
@gloony
Copy link

gloony commented Sep 26, 2018

I just made a little change for make it work on my instance.
On "fake-cm-events.js" Line 43

Remove -> editor.display.input.value += char;
Add -> editor.replaceSelection(char);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment