~/components/konami
Konami
A useKonami hook and an easter-egg component that fires a callback and plays matrix rain when someone types the Konami code.
type it anywhere on this page
locked
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { startMatrixRain } from "./lib/matrix-rain";
/** ↑ ↑ ↓ ↓ ← → ← → B A */
export const KONAMI_CODE = [
"ArrowUp",
"ArrowUp",
"ArrowDown",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowLeft",
"ArrowRight",
"b",
"a",
];
export type UseKonamiOptions = {
/** Keys to match, as `KeyboardEvent.key` values (letters in lower case). @default KONAMI_CODE */
sequence?: string[];
/** Listen at all. @default true */
enabled?: boolean;
/** Ignore keys typed into inputs, textareas and editable content. @default true */
ignoreInputs?: boolean;
};
const MODIFIERS = ["Shift", "Control", "Alt", "Meta", "CapsLock"];
function isTyping(target: EventTarget | null): boolean {
const el = target as HTMLElement | null;
return Boolean(el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)));
}
/**
* Calls `onMatch` each time the key sequence (the Konami code by default) is
* typed anywhere on the page. Returns how many keys of it are currently matched,
* for showing progress.
*/
export function useKonami(onMatch: () => void, { sequence = KONAMI_CODE, enabled = true, ignoreInputs = true }: UseKonamiOptions = {}): number {
const [progress, setProgress] = useState(0);
const onMatchRef = useRef(onMatch);
useEffect(() => {
onMatchRef.current = onMatch;
}, [onMatch]);
const key = sequence.join("\u0000");
useEffect(() => {
if (!enabled) return;
const seq = key.split("\u0000");
let i = 0;
const onKey = (e: KeyboardEvent) => {
if (e.repeat || MODIFIERS.includes(e.key) || (ignoreInputs && isTyping(e.target))) return;
const k = e.key.length === 1 ? e.key.toLowerCase() : e.key;
i = k === seq[i] ? i + 1 : k === seq[0] ? 1 : 0;
if (i === seq.length) {
i = 0;
setProgress(0);
onMatchRef.current();
} else setProgress(i);
};
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("keydown", onKey);
setProgress(0);
};
}, [enabled, ignoreInputs, key]);
return progress;
}
export type KonamiProps = {
/** Called each time the code is entered. */
onActivate?: () => void;
/** Keys to match, as `KeyboardEvent.key` values (letters in lower case). @default KONAMI_CODE */
sequence?: string[];
/** Listen at all. @default true */
enabled?: boolean;
/** Play matrix rain when the code is entered (skipped under reduced motion). @default true */
rain?: boolean;
/** How long the rain lasts, in milliseconds. A click or any key ends it early. @default 6000 */
duration?: number;
/** Rain over the whole viewport. Set to false to fill the nearest positioned parent instead (for previews). @default true */
fullscreen?: boolean;
/** Play the rain even when the user prefers reduced motion (e.g. behind an explicit "play" button). Use sparingly. @default false */
ignoreReducedMotion?: boolean;
/** Called with the number of keys matched so far, for showing progress. */
onProgress?: (matched: number) => void;
};
/**
* An easter egg: listens for the Konami code (↑ ↑ ↓ ↓ ← → ← → B A), calls
* `onActivate`, and plays a few seconds of matrix rain. The rain is decorative,
* hidden from assistive technology, and skipped under prefers-reduced-motion.
*/
export function Konami({
onActivate,
sequence,
enabled = true,
rain = true,
duration = 6000,
fullscreen = true,
ignoreReducedMotion = false,
onProgress,
}: KonamiProps) {
const [raining, setRaining] = useState(false);
const canvasRef = useRef<HTMLCanvasElement>(null);
const activate = useCallback(() => {
onActivate?.();
const reduced = !ignoreReducedMotion && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (rain && !reduced) setRaining(true);
}, [onActivate, rain, ignoreReducedMotion]);
const progress = useKonami(activate, { sequence, enabled });
const onProgressRef = useRef(onProgress);
useEffect(() => {
onProgressRef.current = onProgress;
}, [onProgress]);
useEffect(() => {
onProgressRef.current?.(progress);
}, [progress]);
useEffect(() => {
if (!raining || !canvasRef.current) return;
const stopRain = startMatrixRain(canvasRef.current);
const stop = () => setRaining(false);
const timer = window.setTimeout(stop, duration);
// Any key ends it early (registered next tick so the final key of the code doesn't).
const listen = window.setTimeout(() => window.addEventListener("keydown", stop), 0);
return () => {
stopRain();
window.clearTimeout(timer);
window.clearTimeout(listen);
window.removeEventListener("keydown", stop);
};
}, [raining, duration]);
if (!raining) return null;
return (
<div
aria-hidden="true"
onClick={() => setRaining(false)}
className={`${fullscreen ? "fixed z-[100]" : "absolute z-10"} inset-0 cursor-pointer bg-mpk-bg/60`}
>
<canvas ref={canvasRef} className="block h-full w-full" />
</div>
);
}Installation
npx mpkcn add konami01Add mpkcn-theme.css if you haven't yet (see Installation)
02Copy the source into your components folder
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { startMatrixRain } from "./lib/matrix-rain";
/** ↑ ↑ ↓ ↓ ← → ← → B A */
export const KONAMI_CODE = [
"ArrowUp",
"ArrowUp",
"ArrowDown",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowLeft",
"ArrowRight",
"b",
"a",
];
export type UseKonamiOptions = {
/** Keys to match, as `KeyboardEvent.key` values (letters in lower case). @default KONAMI_CODE */
sequence?: string[];
/** Listen at all. @default true */
enabled?: boolean;
/** Ignore keys typed into inputs, textareas and editable content. @default true */
ignoreInputs?: boolean;
};
const MODIFIERS = ["Shift", "Control", "Alt", "Meta", "CapsLock"];
function isTyping(target: EventTarget | null): boolean {
const el = target as HTMLElement | null;
return Boolean(el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)));
}
/**
* Calls `onMatch` each time the key sequence (the Konami code by default) is
* typed anywhere on the page. Returns how many keys of it are currently matched,
* for showing progress.
*/
export function useKonami(onMatch: () => void, { sequence = KONAMI_CODE, enabled = true, ignoreInputs = true }: UseKonamiOptions = {}): number {
const [progress, setProgress] = useState(0);
const onMatchRef = useRef(onMatch);
useEffect(() => {
onMatchRef.current = onMatch;
}, [onMatch]);
const key = sequence.join("\u0000");
useEffect(() => {
if (!enabled) return;
const seq = key.split("\u0000");
let i = 0;
const onKey = (e: KeyboardEvent) => {
if (e.repeat || MODIFIERS.includes(e.key) || (ignoreInputs && isTyping(e.target))) return;
const k = e.key.length === 1 ? e.key.toLowerCase() : e.key;
i = k === seq[i] ? i + 1 : k === seq[0] ? 1 : 0;
if (i === seq.length) {
i = 0;
setProgress(0);
onMatchRef.current();
} else setProgress(i);
};
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("keydown", onKey);
setProgress(0);
};
}, [enabled, ignoreInputs, key]);
return progress;
}
export type KonamiProps = {
/** Called each time the code is entered. */
onActivate?: () => void;
/** Keys to match, as `KeyboardEvent.key` values (letters in lower case). @default KONAMI_CODE */
sequence?: string[];
/** Listen at all. @default true */
enabled?: boolean;
/** Play matrix rain when the code is entered (skipped under reduced motion). @default true */
rain?: boolean;
/** How long the rain lasts, in milliseconds. A click or any key ends it early. @default 6000 */
duration?: number;
/** Rain over the whole viewport. Set to false to fill the nearest positioned parent instead (for previews). @default true */
fullscreen?: boolean;
/** Play the rain even when the user prefers reduced motion (e.g. behind an explicit "play" button). Use sparingly. @default false */
ignoreReducedMotion?: boolean;
/** Called with the number of keys matched so far, for showing progress. */
onProgress?: (matched: number) => void;
};
/**
* An easter egg: listens for the Konami code (↑ ↑ ↓ ↓ ← → ← → B A), calls
* `onActivate`, and plays a few seconds of matrix rain. The rain is decorative,
* hidden from assistive technology, and skipped under prefers-reduced-motion.
*/
export function Konami({
onActivate,
sequence,
enabled = true,
rain = true,
duration = 6000,
fullscreen = true,
ignoreReducedMotion = false,
onProgress,
}: KonamiProps) {
const [raining, setRaining] = useState(false);
const canvasRef = useRef<HTMLCanvasElement>(null);
const activate = useCallback(() => {
onActivate?.();
const reduced = !ignoreReducedMotion && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (rain && !reduced) setRaining(true);
}, [onActivate, rain, ignoreReducedMotion]);
const progress = useKonami(activate, { sequence, enabled });
const onProgressRef = useRef(onProgress);
useEffect(() => {
onProgressRef.current = onProgress;
}, [onProgress]);
useEffect(() => {
onProgressRef.current?.(progress);
}, [progress]);
useEffect(() => {
if (!raining || !canvasRef.current) return;
const stopRain = startMatrixRain(canvasRef.current);
const stop = () => setRaining(false);
const timer = window.setTimeout(stop, duration);
// Any key ends it early (registered next tick so the final key of the code doesn't).
const listen = window.setTimeout(() => window.addEventListener("keydown", stop), 0);
return () => {
stopRain();
window.clearTimeout(timer);
window.clearTimeout(listen);
window.removeEventListener("keydown", stop);
};
}, [raining, duration]);
if (!raining) return null;
return (
<div
aria-hidden="true"
onClick={() => setRaining(false)}
className={`${fullscreen ? "fixed z-[100]" : "absolute z-10"} inset-0 cursor-pointer bg-mpk-bg/60`}
>
<canvas ref={canvasRef} className="block h-full w-full" />
</div>
);
}const CHARS = "01アイウエオカキクケコ<>/{}$#";
const SIZE = 16;
const TICK_MS = 45;
type NavigatorWithHints = Navigator & {
deviceMemory?: number;
connection?: { saveData?: boolean };
};
/**
* Rough check for weak devices: few CPU cores, little memory, or data saver on.
* Also honours `<html data-perf="low">` if the app sets it.
*/
export function isLowPower(): boolean {
if (typeof window === "undefined") return false;
try {
if (document.documentElement.dataset.perf === "low") return true;
const n = navigator as NavigatorWithHints;
return Boolean(
(n.hardwareConcurrency && n.hardwareConcurrency <= 4) ||
(n.deviceMemory && n.deviceMemory <= 4) ||
n.connection?.saveData,
);
} catch {
return false;
}
}
function cssVar(el: Element, name: string, fallback: string): string {
return getComputedStyle(el).getPropertyValue(name).trim() || fallback;
}
/**
* Draws matrix rain on the canvas until the returned stop function is called.
* The canvas is sized to its parent element (and follows it on resize);
* glyphs use `--mpk-blue`, the trail fades into `--mpk-bg`.
*/
export function startMatrixRain(canvas: HTMLCanvasElement): () => void {
const ctx = canvas.getContext("2d");
if (!ctx) return () => {};
const host = canvas.parentElement ?? canvas;
const ink = cssVar(canvas, "--mpk-blue", "#6fb2ff");
const bg = cssVar(canvas, "--mpk-bg", "#0a0d10");
let drops: number[] = [];
const resize = () => {
const w = Math.max(1, Math.round(host.clientWidth || window.innerWidth));
const h = Math.max(1, Math.round(host.clientHeight || window.innerHeight));
canvas.width = w;
canvas.height = h;
const cols = Math.ceil(w / SIZE);
drops = Array.from({ length: cols }, (_, i) => drops[i] ?? Math.random() * -50);
};
resize();
const observer = typeof ResizeObserver !== "undefined" ? new ResizeObserver(resize) : null;
observer?.observe(host);
const timer = window.setInterval(() => {
ctx.globalAlpha = 0.08;
ctx.fillStyle = bg;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalAlpha = 1;
ctx.fillStyle = ink;
ctx.font = `${SIZE}px "JetBrains Mono", ui-monospace, monospace`;
drops.forEach((y, x) => {
ctx.fillText(CHARS[Math.floor(Math.random() * CHARS.length)], x * SIZE, y * SIZE);
drops[x] = y * SIZE > canvas.height && Math.random() > 0.975 ? 0 : y + 1;
});
}, TICK_MS);
return () => {
window.clearInterval(timer);
observer?.disconnect();
};
}03Update the import paths to match your project
Usage
Drop the component anywhere. Typing ↑ ↑ ↓ ↓ ← → ← → B A on the page plays a few seconds of matrix rain.
import { Konami } from "@/components/mpkcn/konami";
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<Konami onActivate={() => console.log("cheat unlocked")} />
</>
);
}A click or any key ends the rain early. Keys typed into fields are ignored.
Examples
Just the hook
useKonami calls your function on a match and returns how many keys are matched so far, so you can show progress or trigger anything else.
"use client";
import { useState } from "react";
import { useKonami } from "@/components/mpkcn/konami";
export function Secret() {
const [unlocked, setUnlocked] = useState(false);
const matched = useKonami(() => setUnlocked(true));
return <p>{unlocked ? "+30 lives" : `${matched}/10`}</p>;
}Your own sequence
sequence takes KeyboardEvent.key values, letters in lower case.
<Konami sequence={["m", "p", "k"]} rain={false} onActivate={() => setTheme("light")} />Props
| Prop | Type | Default | Description |
|---|---|---|---|
| onActivate | () => void | — | Called each time the code is entered. |
| sequence | string[] | KONAMI_CODE | Keys to match, as KeyboardEvent.key values. |
| enabled | boolean | true | Listen at all. |
| rain | boolean | true | Play matrix rain on a match. |
| duration | number | 6000 | How long the rain lasts, in milliseconds. |
| fullscreen | boolean | true | Rain over the viewport. false fills the nearest positioned parent. |
| ignoreReducedMotion | boolean | false | Rain even under reduced motion. Only use it behind an explicit action. |
| onProgress | (matched: number) => void | — | Number of keys matched so far. |
useKonami(onMatch, { sequence?, enabled?, ignoreInputs? }) returns the matched count. KONAMI_CODE is exported too.
Accessibility
- Under
prefers-reduced-motion: reducethere is no rain, butonActivatestill fires. - The rain is decorative:
aria-hidden, never focusable, and gone afterdurationor on the first click or key. - Keys typed into inputs, textareas, selects and editable content never count, so the code cannot fire while someone types.