UNPKG

@tanstack/hotkeys

Version:

Type-safe, framework-agnostic keyboard hotkey management for the browser

105 lines (103 loc) • 5.61 kB
import { isCodeName, isKeyNameShape, isModifierCode } from "./_chord.js"; import { altGraphTypedCharacter, codeToLogicalKey, isModifierPress, macKeycapLetter, normalizeKeyboardEvent } from "./_keyboard-event.js"; import { isAsciiLetter, isLatinLetter, isPrintableKey } from "./_keys.js"; import { US_SHIFTED, US_UNSHIFTED, matchKeyboardEvent } from "./_match.js"; import { isSingleLetterKey } from "./constants.js"; import { normalizeHotkey, parseKeyboardEvent } from "./parse.js"; // src/_recorder-chord.ts /** * Converts a keydown to a chord that fires for the same key press. * * - `'auto'` records the key by name when the press has one, and its physical * code otherwise. * - `'code'` always records the physical code. * - `'key'` always records the character or key name the press produced. * * Returns null for composition, modifier-only input, and a press the mode * can't record: a modifier position or unusable physical input by code, or an * `Unidentified` key by key. */ function hotkeyChordFromKeydown(event, platform, recordBy = "auto") { const normalized = normalizeKeyboardEvent(event, platform); if (normalized.isComposing || isModifierPress(event)) return null; const parsed = parseKeyboardEvent(event, platform); const { key: _key, code: _code, ...modifiers } = parsed; const key = recordBy === "auto" ? keyName(event, platform) : void 0; if (key !== void 0) { const { ctrl, shift, alt, meta } = parsed; const keepShift = /^Digit/.test(event.code) && (ctrl || meta || alt) || platform === "mac" && meta && !alt && key === normalized.key; for (const withShift of [keepShift && shift, shift]) { const chord = { ...modifiers, shift: withShift, key }; if (matchKeyboardEvent(event, chord, platform).matched) return normalizeHotkey({ ctrl, shift: withShift, alt, meta, key }, platform); } } if (recordBy === "code" || recordBy === "auto" && hasUsableCode(event)) return hasUsableCode(event) && !isModifierCode(event.code) && !normalized.altGraph ? normalizeHotkey({ ...modifiers, code: event.code }, platform) : null; return parsed.key && !(normalized.altGraph && !altGraphTypedCharacter(normalized)) && parsed.key !== "Unidentified" && (recordBy === "key" || parsed.key !== "Dead" && isKeyNameShape(parsed.key)) ? normalizeHotkey(parsed, platform) : null; } /** * The name `'auto'` records a press by, or undefined when its physical code * says more than anything it typed: * * - A named key such as Enter, a letter and any other character are recorded * as typed, including a character AltGr typed, such as German `@`. * - With Control, Command or Alt, a digit-row key is recorded as its digit, * as the matcher reads it: AZERTY Ctrl+& is `Mod+1`, and macOS Cmd+Shift+1, * which reports `1` where Windows reports `!`, is `Mod+Shift+1`. * - macOS reports `/` for Cmd+Shift+/ on the US `/` key, where Windows reports * `?`, so it is recorded as `?`, as the matcher reads it. * - A non-Latin letter is named by its position, as the matcher names it: * Russian `ы` is `S`. * - macOS Option types another character or starts an accent, so the keycap * letter is read from `keyCode`, as the matcher reads it. Option with any * other key keeps its position. * - On the numpad, Enter and the four operators without Shift are recorded as * typed: Numpad Enter is `Enter`. The digits and decimal key keep their * position, since what they type depends on NumLock and the layout. * - Dead keys, whitespace characters, `Unidentified` keys and modifier * positions keep their position. */ function keyName(event, platform) { const { key, code, ctrl, meta, alt, shift, altGraph } = normalizeKeyboardEvent(event, platform); if (!key || key === "Unidentified" || /^Numpad/.test(code) && code !== "NumpadEnter" && (shift || !/^Numpad(Add|Subtract|Multiply|Divide)$/.test(code)) || isModifierCode(code)) return; const typed = key !== "Dead" && isPrintableKey(key); if (altGraph) return typed && key.trim() ? key : void 0; if (key !== "Dead" && !typed) return isKeyNameShape(key) ? key : void 0; if (/^Digit\d$/.test(code) && (alt || (ctrl || meta) && (shift || !/^[-+=]$/.test(key)))) return code.slice(5); if (platform === "mac" && alt) return isAsciiLetter(key) ? key : macKeycapLetter(event); if (!typed || !key.trim()) return void 0; if (isSingleLetterKey(key)) return isLatinLetter(key) ? key : codeToLogicalKey(code); return platform === "mac" && meta && shift && !",.".includes(key) && codeToLogicalKey(code) === key ? "~_+{}|:\"<>?"["`-=[]\\;',./".indexOf(key)] ?? key : key; } /** * Explains why a key press cannot be recorded before syntax/policy checks. * Recording by key accepts produced characters instead of requiring a code, * but rejects AltGr that typed nothing new, which no hotkey matches. */ function chordRejection(event, platform, recordBy = "auto") { const normalized = normalizeKeyboardEvent(event, platform); if (recordBy === "key") return normalized.altGraph && !altGraphTypedCharacter(normalized) ? { reason: "alt-graph" } : void 0; const unrecorded = recordBy === "code" || hotkeyChordFromKeydown(event, platform, recordBy) === null; if (normalized.altGraph && unrecorded) return { reason: "alt-graph" }; if (!hasUsableCode(event) && unrecorded) return { reason: "missing-code" }; } /** * Whether the event reports a real physical key code to record. Autofill * sends a plain `Event` named keydown, without `code`. */ function hasUsableCode(event) { return isCodeName(event.code || "") && event.code !== "Unidentified"; } export { chordRejection, hotkeyChordFromKeydown };