Skip to main content

Utils

Detect a Keyboard Keypress Sequence

import * as React from 'react';
import { useCallback, useEffect, useRef } from 'react';

const App = () => {
let keyPressBuffer = useRef([]);
let lastKeyPressTime = useRef(Date.now());

const handleKeyDown = useCallback((event) => {
// Tests for SHIFT + DEBUG
if (event.shiftKey) {
const targetChars = 'bdegu';
const successfulSequence = 'debug';
const key = event.key.toLowerCase();

if (targetChars.indexOf(key) === -1) return;

const currentTime = Date.now();

if (currentTime - lastKeyPressTime.current > 1000) {
keyPressBuffer.current = [];
}

keyPressBuffer.current.push(key);
lastKeyPressTime.current = currentTime;

if (keyPressBuffer.current.join('') === successfulSequence) {
console.log('Keypress sequence accepted');
}
}
}, []);

useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleKeyDown]);

return (
<div>
Example App
</div>
);
};

export default App;