@tanstack/hotkeys
Version:
Type-safe, framework-agnostic keyboard hotkey management for the browser
211 lines (209 loc) • 7.72 kB
JavaScript
import { chordHasKey, hotkeySteps, parsedChordsEqual } from "./_chord.js";
import { isSequenceStep, keepsSequenceProgress } from "./_keyboard-event.js";
import { matchKeyboardEvent } from "./_match.js";
import { formatHotkey } from "./format.js";
import { parseHotkey } from "./parse.js";
import { detectPlatform } from "./platform.js";
// src/match.ts
/**
* Checks if a KeyboardEvent matches a hotkey.
*
* Physical bindings such as `Mod+[KeyS]` match `event.code` exactly.
* Logical bindings match `event.key`, the character the key types on the
* user's keyboard layout. Letters match without regard to case, and Shift
* that typed a symbol, such as `?`, does not need to be written.
*
* When `event.key` cannot name the shortcut, the key's conventional position
* (`event.code`) stands in. That covers non-Latin letters, dead keys, the
* digit row, symbols typed with Shift, and what macOS Option types. A symbol
* that US Shift types names its US key, so `Shift+/` fires on whatever key
* types `?`. On the
* digit row, `-`, `+`, and `=` typed with Control alone, or Command alone on
* macOS, don't stand in, because those presses zoom the page: AZERTY Ctrl+-
* doesn't fire `Mod+6`.
* With
* Option held on macOS, the letter comes from the keycap (`event.keyCode`)
* when the browser reports one. A named key such as `End` and a character
* typed with AltGr match only as themselves, and so does an ASCII letter
* outside the digit row. An `'Unidentified'` key falls back to its position,
* except on letter and numpad keys.
*
* Turkish `ı` is its own letter: an `ı` binding never fires on the `i` key,
* but `I` fires on the `ı` key. Keys pressed while an input method editor is
* composing match nothing.
*
* @param event - The KeyboardEvent to check
* @param chord - The chord string or parsed chord to match against
* @param platform - The target platform for resolving 'Mod' (defaults to auto-detection)
* @returns True if the event matches the chord
*
* @example
* ```ts
* document.addEventListener('keydown', (event) => {
* if (matchesKeyboardEvent(event, 'Mod+S')) {
* event.preventDefault()
* handleSave()
* }
* })
* ```
*/
function matchesKeyboardEvent(event, chord, platform = detectPlatform()) {
const parsed = typeof chord === "string" ? parseHotkey(chord, platform) : chord;
if (!chordHasKey(parsed)) return false;
return matchKeyboardEvent(event, parsed, platform).matched;
}
/**
* Creates a keyboard event handler that calls the callback when the chord
* matches. For sequences, use `createSequenceMatcher`.
*
* @param chord - The chord string or parsed chord to match
* @param callback - The function to call when the hotkey matches
* @param options - Options for matching and handling
* @returns A function that can be used as an event handler
*
* @example
* ```ts
* const handler = createHotkeyChordHandler('Mod+S', (event, { hotkey, parsedChord }) => {
* console.log(`${hotkey} was pressed`)
* handleSave()
* })
*
* document.addEventListener('keydown', handler)
* ```
*/
function createHotkeyChordHandler(chord, callback, options = {}) {
const { preventDefault = true, stopPropagation = true, platform } = options;
const resolvedPlatform = platform ?? detectPlatform();
const hotkeyString = typeof chord === "string" ? chord : formatHotkey(chord);
const parsed = typeof chord === "string" ? parseHotkey(chord, resolvedPlatform) : chord;
const context = {
kind: "chord",
hotkey: hotkeyString,
parsedChord: parsed
};
return (event) => {
if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {
if (preventDefault) event.preventDefault();
if (stopPropagation) event.stopPropagation();
callback(event, context);
}
};
}
/**
* Creates a handler that matches several chords.
*
* @param handlers - A map of chord strings to their handlers
* @param options - Options for matching and handling
* @returns A function that can be used as an event handler
*
* @example
* ```ts
* const handler = createMultiHotkeyChordHandler({
* 'Mod+S': (event, { hotkey }) => handleSave(),
* 'Mod+Z': (event, { hotkey }) => handleUndo(),
* 'Mod+Shift+Z': (event, { hotkey }) => handleRedo(),
* })
*
* document.addEventListener('keydown', handler)
* ```
*/
function createMultiHotkeyChordHandler(handlers, options = {}) {
const { preventDefault = true, stopPropagation = true, platform } = options;
const resolvedPlatform = platform ?? detectPlatform();
const parsedHandlers = Object.entries(handlers).filter((entry) => Boolean(entry[1])).map(([hotkey, handler]) => {
const parsed = parseHotkey(hotkey, resolvedPlatform);
return {
parsed,
handler,
context: {
kind: "chord",
hotkey,
parsedChord: parsed
}
};
});
return (event) => {
for (const { parsed, handler, context } of parsedHandlers) if (matchesKeyboardEvent(event, parsed, resolvedPlatform)) {
if (preventDefault) event.preventDefault();
if (stopPropagation) event.stopPropagation();
handler(event, context);
return;
}
};
}
/**
* Compares normalized hotkey identity, including all four modifiers.
* Sequences are equal when every step is equal; a one-step sequence equals its chord.
* Aliases resolve on the supplied platform. A physical code and a logical key
* remain distinct even when one keyboard event could match both.
*/
function areHotkeysEqual(left, right, platform = detectPlatform()) {
const a = hotkeySteps(left);
const b = hotkeySteps(right);
return a.length === b.length && a.every((step, index) => parsedChordsEqual(parseHotkey(step, platform), parseHotkey(b[index], platform)));
}
/** Default timeout between sequence steps (in milliseconds). */
const DEFAULT_SEQUENCE_TIMEOUT = 1e3;
/**
* Creates a simple sequence matcher for one-off use.
*
* This is a low-level helper that does not support ignoreInputs, target,
* or other HotkeyOptions. Callers must handle input filtering themselves
* if attaching to document.
*
* Modifier presses, auto-repeats, and keys an input method editor reads are
* not steps. Lock keys such as CapsLock and NumLock, Fn, and dead keys advance
* the sequence when they match the next step and otherwise keep its progress.
*
* @param sequence - The sequence of hotkeys to match
* @param options - Options including timeout
* @returns An object with match() and reset() methods
*
* @example
* ```ts
* const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })
*
* document.addEventListener('keydown', (event) => {
* if (matcher.match(event)) {
* console.log('Sequence matched!')
* }
* })
* ```
*/
function createSequenceMatcher(sequence, options = {}) {
const platform = options.platform ?? detectPlatform();
const timeout = options.timeout ?? 1e3;
const parsedSequence = parseHotkey(sequence, platform);
let currentIndex = 0;
let lastKeyTime = 0;
return {
match(event) {
if (!isSequenceStep(event)) return false;
const now = Date.now();
if (currentIndex > 0 && now - lastKeyTime > timeout) currentIndex = 0;
const expected = parsedSequence[currentIndex];
if (!expected) return false;
if (matchesKeyboardEvent(event, expected, platform)) {
lastKeyTime = now;
currentIndex++;
if (currentIndex >= parsedSequence.length) {
currentIndex = 0;
return true;
}
} else if (currentIndex > 0) {
if (matchesKeyboardEvent(event, parsedSequence[0], platform)) {
currentIndex = 1;
lastKeyTime = now;
} else if (!keepsSequenceProgress(event)) currentIndex = 0;
}
return false;
},
reset() {
currentIndex = 0;
},
getProgress() {
return currentIndex;
}
};
}
export { DEFAULT_SEQUENCE_TIMEOUT, areHotkeysEqual, createHotkeyChordHandler, createMultiHotkeyChordHandler, createSequenceMatcher, matchesKeyboardEvent };