Last active
January 16, 2017 14:23
-
-
Save Robert-Wett/36c850deb347da314f35f0e9fb921cc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import './App.css' | |
import { h, Component, cloneElement } from 'preact' | |
export default class App extends Component { | |
render() { | |
return ( | |
<KonamiZone> | |
<HelloWorld /> | |
</KonamiZone> | |
) | |
} | |
} | |
const HelloWorld = () => <div>Hello WOrld</div>; | |
class KonamiZone extends Component { | |
static defaultProps = { code: [38, 40, 37, 39] }; | |
state = { triggerCount: 0 }; | |
clearId = null; | |
pressedKeys = []; | |
componentWillMount() { | |
this.timeoutOn(); | |
document.addEventListener('keydown', this.keyDownListener); | |
} | |
componentWillUnmount() { | |
this.timeoutOff(); | |
document.removeEventListener('keydown', this.keyDownListener); | |
} | |
clearKeys = () => this.pressedKeys = []; | |
timeoutOn = () => this.clearId = window.setTimeout(this.clearKeys, 3000); | |
timeoutOff = () => window.clearInterval(this.clearId); | |
keyDownListener = e => { | |
let [{ keyCode }, { code, fn }] = [e, this.props]; | |
if (ARROW_KEYS[keyCode]){ | |
this.timeoutOff(); | |
this.pressedKeys.push(keyCode); | |
if (arraysEqual(this.pressedKeys, code)) { | |
this.setState({ triggerCount: this.state.triggerCount + 1 }, | |
() => { | |
this.clearKeys(); | |
fn && fn() || alert('BANG') | |
}); | |
} | |
else if (!arraysEqual(this.pressedKeys, code.slice(0, this.pressedKeys.length))) { | |
this.clearKeys(); | |
} | |
this.timeoutOn(); | |
} | |
else { | |
this.clearKeys(); | |
} | |
}; | |
render({ children, ...props }) { | |
return cloneElement(children[0], { ...props }); | |
} | |
} | |
const arraysEqual = (a, b) => { | |
if (a.length !== b.length) { | |
return false; | |
} | |
for (let i = 0; i < a.length; i++) { | |
if (a[i] !== b[i]) { | |
return false; | |
} | |
} | |
return true | |
}; | |
const ARROW_KEYS = { | |
37: 'LEFT', | |
38: 'UP', | |
39: 'RIGHT', | |
40: 'DOWN' | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment