Skip to content

Instantly share code, notes, and snippets.

@steveluscher
Last active January 31, 2018 21:26
Show Gist options
  • Save steveluscher/95c2f9c5d7577c417ab3f7c0dca3d15a to your computer and use it in GitHub Desktop.
Save steveluscher/95c2f9c5d7577c417ab3f7c0dca3d15a to your computer and use it in GitHub Desktop.
This demonstrates how to bind handlers to keyboard events in Draft.js
import {getDefaultKeyBinding, KeyBindingUtil} from 'draft-js';
const ViewportShaker = require('ViewportShaker');
const {hasCommandModifier} = KeyBindingUtil;
function mapKeyEventsToCommands(e) {
const keyCode = e.which;
const magnitude = hasCommandModifier(e) ? 300 : 100;
switch (keyCode) {
case 9: // Tab key
ViewportShaker.bump({angle: (2 * Math.PI) * Math.random(), magnitude});
case 27: // Escape key
ViewportShaker.stopShaking();
break;
case 37: // Left arrow key
ViewportShaker.bump({angle: Math.PI, magnitude});
break;
case 38: // Up arrow key
ViewportShaker.bump({angle: Math.PI / 2, magnitude});
break;
case 39: // Right arrow key
ViewportShaker.bump({angle: 0, magnitude});
break;
case 40: // Down arrow key
ViewportShaker.bump({angle: (3 * Math.PI) / 2, magnitude});
break;
}
return getDefaultKeyBinding(e);
}
class ShakyEditor extends React.Component {
render() {
return (
<DraftEditor
keyBindingFn={mapKeyEventsToCommands}
...
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment