@tanstack/hotkeys
Version:
Type-safe, framework-agnostic keyboard hotkey management for the browser
112 lines (110 loc) • 6.33 kB
JavaScript
import { altGraphTypedCharacter, codeToLogicalKey, isTypedText, macKeycapLetter, normalizeKeyboardEvent } from "./_keyboard-event.js";
import { isAsciiLetter, isLatinLetter, isPrintableKey, keysEqual } from "./_keys.js";
import { isSingleLetterKey } from "./constants.js";
import { detectPlatform } from "./platform.js";
// src/_match.ts
/** What US Shift types on each punctuation key, and the key itself. */
const US_SHIFTED = "~_+{}|:\"<>?";
const US_UNSHIFTED = "`-=[]\\;',./";
/** Matches an event and reports the winning candidate and release identity. */
function matchKeyboardEvent(event, parsed, platform = detectPlatform()) {
const normalized = normalizeKeyboardEvent(event, platform);
const noMatch = {
matched: false,
score: 0
};
if (normalized.isComposing) return noMatch;
const { altGraph } = normalized;
if ((altGraph ? false : normalized.ctrl) !== parsed.ctrl || (altGraph ? false : normalized.alt) !== parsed.alt || normalized.meta !== parsed.meta) return noMatch;
const shiftMatches = normalized.shift === parsed.shift;
if (altGraph && !altGraphTypedCharacter(normalized)) return noMatch;
if (parsed.code !== void 0) return !altGraph && shiftMatches && normalized.code === parsed.code ? matched(3) : noMatch;
const shiftTypedNothing = platform === "mac" && normalized.meta && normalized.shift && !normalized.alt && !/^(Digit|Numpad)/.test(normalized.code) && codeToLogicalKey(normalized.code) === normalized.key;
if (shiftTypedNothing && !parsed.shift && !"<>".includes(parsed.key) && "~_+{}|:\"<>?"["`-=[]\\;',./".indexOf(normalized.key)] === parsed.key) return matched(2);
if (keysEqual(normalized.key, parsed.key)) {
const implicitShift = isPrintableKey(normalized.key) && !isSingleLetterKey(normalized.key) && !parsed.shift && !shiftTypedNothing;
if (shiftMatches || implicitShift && normalized.shift) return matched(implicitShift ? 2 : 3);
}
if (altGraph || !shiftMatches) return noMatch;
if (normalized.key === "ı" && parsed.key === "I" && !normalized.alt) return matched(2);
const optionLetter = platform === "mac" && normalized.alt && (normalized.key === "Dead" || isTypedText(normalized.key) && !isAsciiLetter(normalized.key)) ? macKeycapLetter(event) : void 0;
const shiftedIndex = normalized.shift && !normalized.alt && normalized.key.length === 1 && !/^(Digit|Numpad)/.test(normalized.code) ? US_SHIFTED.indexOf(normalized.key) : -1;
const usKey = shiftedIndex < 0 || namesLetter(normalized, event.keyCode) ? void 0 : US_UNSHIFTED[shiftedIndex];
if (optionLetter === void 0 && usKey === void 0 && !positionStandsIn(normalized, platform, event.keyCode)) return noMatch;
const fallbackKey = optionLetter ?? usKey ?? codeToLogicalKey(normalized.code) ?? (normalized.key === "Unidentified" ? normalized.code : void 0);
return fallbackKey !== void 0 && keysEqual(fallbackKey, parsed.key) ? matched(1) : noMatch;
function matched(score) {
return {
matched: true,
score,
identity: {
key: normalized.key,
code: normalized.code
}
};
}
}
/**
* Whether a key's conventional position may stand in for what it typed. Only
* output that can't name a shortcut falls back:
* - non-Latin letters and symbols, such as Russian `ы` or macOS Option's `–`,
* including text of several code points, such as macOS Hebrew `שׁ`
* - dead keys on a letter key, on Quote or Backquote (US International's
* ' and `), or with Control, Alt or Command
* - `Unidentified` keys, except on letter positions, which layouts such as
* AZERTY rearrange, and numpad positions, whose output depends on NumLock.
* Chrome on Linux Wayland reports Ctrl+` this way, and Firefox reports
* numpad 5 with NumLock off this way.
* - anything on the digit row, where AZERTY types `&` and `é` for 1 and 2
* and macOS Spanish Option+Shift+6 types a space,
* except `-`, `+` or `=` typed with only the platform's zoom modifier,
* Control or macOS Command: AZERTY Ctrl+- on the 6 key is zoom out
* - ASCII symbols typed with Shift on a punctuation key, such as UK `@` on
* the US ' key. One that US Shift types, such as `?`, names its US key
* instead (`/`), in matchKeyboardEvent
* - ASCII symbols on a letter key whose legacy keyCode names that letter:
* Greek `;` on the Q key reports VK_Q on Windows
* - ASCII symbols typed with macOS Option on a letter position, such as `~`
* for US Cmd+Option+N, where Command cancels the dead key
* - Latin letters typed with Alt, such as macOS Option+A typing `å`
* - Latin letters on punctuation keys with Control or Command, so German
* Cmd+ü still fires `Mod+[` (German types `[` with Option)
*
* A named key (`End` from a NumLock-off numpad), any other ASCII character,
* or a Latin letter typed on its own is the key the user meant, wherever it
* sits. AZERTY's `+` on the US `/` position is `+`, not `/`. So is a Latin
* letter typed with Control+Alt on a Windows letter key: Windows treats
* Control+Alt as AltGr, so Polish Control+Alt+A types `ą`.
*/
function positionStandsIn({ key, code, ctrl, meta, shift, alt }, platform, keyCode) {
if (key === "Unidentified") return !/^(Key|Numpad)/.test(code);
if (code.startsWith("Digit")) {
if (/\p{Cf}/u.test(key)) return false;
return !(!shift && !alt && (platform === "mac" ? meta && !ctrl : ctrl && !meta)) || !/^[-+=]$/.test(key);
}
if (key === "Dead") return ctrl || meta || alt || /^(Quote|Backquote|Key)/.test(code);
if (!isTypedText(key)) return false;
if (isAsciiLetter(key)) return false;
const letterKey = code.startsWith("Key");
if (/^[!-~]$/.test(key)) {
if (letterKey) return namesLetter({
code,
shift,
alt
}, keyCode) || alt && platform === "mac";
return shift;
}
if (!isLatinLetter(Array.from(key)[0])) return true;
if (alt && !(letterKey && ctrl && platform === "windows")) return true;
return (ctrl || meta) && !letterKey;
}
/**
* Whether a key's legacy keyCode names the letter of its position. Alt
* without Shift types a character of its own, so then it doesn't; Greek
* Alt+Shift+Q typing `:` is still Q. AltGr presses, such as German `@` on
* VK_Q, never get here: matchKeyboardEvent returns before any fallback.
*/
function namesLetter({ code, shift, alt }, keyCode) {
return (!alt || shift) && /^Key[A-Z]$/.test(code) && keyCode === code.charCodeAt(3);
}
export { US_SHIFTED, US_UNSHIFTED, matchKeyboardEvent };