Skip to content

Instantly share code, notes, and snippets.

@razzius
Last active April 13, 2020 18:30
Show Gist options
  • Save razzius/9479251bd33b655a94f044e6c798b422 to your computer and use it in GitHub Desktop.
Save razzius/9479251bd33b655a94f044e6c798b422 to your computer and use it in GitHub Desktop.
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
const KEY_NAMES = {
enter: 'ret',
' ': 'spc',
escape: 'esc',
}
function parseKeyname(keyname) {
const parts = keyname.toLowerCase().split('-')
const modifiers = parts.slice(0, -1)
const key = parts[parts.length - 1]
return {
meta: modifiers.includes('m'),
control: modifiers.includes('c'),
super_: modifiers.includes('s'),
key: key,
}
}
const keybindings = {
'm-ret': 'c-s-s',
}
function keybindingIdentifier({ meta, control, super_, key }) {
// order: c-m-s-key
parts = [
control ? 'c' : null,
meta ? 'm' : null,
super_ ? 's' : null,
key,
].filter(Boolean)
return parts.join('-')
}
// function rebindKey(from, to) {}
document.onkeypress = (e) => {
console.log('keypress')
console.log(e)
}
document.onkeydown = (e) => {
console.log('keydown')
console.log(e)
const key = e.key.toLowerCase()
const keyName = key in KEY_NAMES ? KEY_NAMES[key] : key
const keybinding = {
meta: e.metaKey,
control: e.ctrlKey,
super_: e.altKey,
key: keyName,
}
const identifier = keybindingIdentifier(keybinding)
console.log(identifier)
const boundKey = keybindings[identifier]
console.log('binding:')
console.log(boundKey)
if (boundKey) {
const parsedKey = parseKeyname(boundKey)
console.log(parsedKey)
document.dispatchEvent(
new KeyboardEvent('keydown', {
key: parsedKey.key,
altKey: parsedKey.super_,
ctrlKey: parsedKey.control,
metaKey: parsedKey.meta,
})
)
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment