Created
December 22, 2025 14:56
-
-
Save tkalve/cb99348fcb723dc13fa9f06b4c922dcb to your computer and use it in GitHub Desktop.
useCheatCodes react hook
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
| /** | |
| * @author Thomas Kalve <https://github.com/tkalve> | |
| */ | |
| import { useRef, useCallback, useEffect } from "react"; | |
| /** | |
| * Listens to cheat code sequences and triggers a callback when any sequence is entered | |
| * | |
| * @param callback - Function to call when any cheat code is entered | |
| */ | |
| export function useCheatCodes(callback: (name: string) => void): void { | |
| useCheatCode("RG9vbSBHb2QgbW9kZXxpfGR8ZHxxfGQ=", callback); | |
| useCheatCode("U2ltIENpdHkgMjAwMCBkZWJ1ZyBjaGVhdHxwfHJ8aXxzfGN8aXxsfGx8YQ==", callback); | |
| useCheatCode("S29uYW1pIGNvZGV8QXJyb3dVcHxBcnJvd1VwfEFycm93RG93bnxBcnJvd0Rvd258QXJyb3dMZWZ0fEFycm93UmlnaHR8QXJyb3dMZWZ0fEFycm93UmlnaHR8YnxhfEVudGVy", callback); | |
| useCheatCode("TW9ydGFsIEtvbWJhdCBCbG9vZCBjb2RlfGF8YnxhfGN8YXxifGI=", callback); | |
| useCheatCode("VGhlIFNpbXMgTW9uZXkgY2hlYXR8cnxvfHN8ZXxifHV8ZA==", callback); | |
| } | |
| /** | |
| * Listens to a single cheat code sequence and triggers a callback when the sequence is entered | |
| * | |
| * @param input - Base64 encoded cheat code in format btoa("Name|k|e|y|s") | |
| * @param callback - Function to call when the cheat code is entered | |
| */ | |
| function useCheatCode(input: string, callback: (name: string) => void): void { | |
| const parts = atob(input).split("|"); | |
| const name = parts.shift() ?? ""; | |
| const sequence = parts; | |
| const buffer = useRef<string[]>([]); | |
| const keySequence = useCallback( | |
| (event: KeyboardEvent) => { | |
| if (event.defaultPrevented) return; | |
| if (event.key === sequence[buffer.current.length]) { | |
| buffer.current = [...buffer.current, event.key]; | |
| } else { | |
| buffer.current = []; | |
| } | |
| if (buffer.current.length === sequence.length) { | |
| const bufferString = buffer.current.toString(); | |
| const sequenceString = sequence.toString(); | |
| if (sequenceString === bufferString) { | |
| //console.trace("Code entered: ", name); | |
| callback(name); | |
| } | |
| } | |
| }, | |
| [callback, name, sequence] | |
| ); | |
| useEffect(() => { | |
| document.addEventListener("keydown", keySequence); | |
| return () => document.removeEventListener("keydown", keySequence); | |
| }, [keySequence]); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cheat codes before Base64 encoding: