UNPKG

@tanstack/hotkeys

Version:

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

155 lines (153 loc) • 8.03 kB
import { isCodeName, isKeyNameShape, isModifierCode } from "./_chord.js"; import { US_SHIFTED, US_UNSHIFTED } from "./_constants.js"; import { altGraphTypedCharacter, codeToLogicalKey, isModifierPress, macKeycapLetter, normalizeKeyboardEvent } from "./_keyboard-event.js"; import { isAsciiLetter, isLatinLetter, isPrintableKey } from "./_keys.js"; import { matchKeyboardEvent } from "./_match.js"; import { isSingleLetterKey } from "./constants.js"; import { normalizeHotkey, parseHotkey, 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'` records the character or key name the press produced. * * `'auto'` and `'key'` write a symbol without Shift, as the types require: * Shift+/ records `?`. Where the symbol alone wouldn't fire on the press, or * might also fire without Shift, the key is recorded by its position instead, * such as `Mod+Shift+[BracketLeft]` for Dvorak Cmd+Shift+/. * * 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 chord = chordFromKeydown(event, platform, recordBy); return chord && withoutShiftedSymbol(chord, event, platform); } /** * Symbols that macOS reports with Command only when Shift typed them, on every * macOS layout in tests/fixtures/layout-table.json. Command ignores Shift on * some keys and reports their unshifted character, as Swedish Cmd+Shift+< * reports `<`, so other symbols such as `<` and `+` aren't listed. */ const MAC_COMMAND_SHIFTED_SYMBOLS = /* @__PURE__ */ new Set("?:>_%&()!|^~{}"); /** * Rewrites a chord with Shift and a symbol, which the types reject. The symbol * alone is kept when it fires on the press. The key's position is recorded * instead when the symbol alone doesn't fire, or when it might also fire * without Shift: with Command on macOS, which may report the unshifted * character, unless the symbol is one macOS reports only with Shift, and on * the numpad, where Shift doesn't change what an operator types. AltGr * presses, which a position can't match, keep the symbol alone. */ function withoutShiftedSymbol(chord, event, platform) { const parsed = parseHotkey(chord, platform); if (!parsed.shift || parsed.key === void 0 || !isSymbol(parsed.key)) return chord; const symbol = { ...parsed, shift: false }; const symbolFires = matchKeyboardEvent(event, symbol, platform).matched; const shiftUnknown = platform === "mac" && parsed.meta && !MAC_COMMAND_SHIFTED_SYMBOLS.has(parsed.key) || /^Numpad/.test(event.code); if (symbolFires && !shiftUnknown) return normalizeHotkey(symbol, platform); const { ctrl, shift, alt, meta } = parsed; if (hasUsableCode(event) && !isModifierCode(event.code) && !normalizeKeyboardEvent(event, platform).altGraph) return normalizeHotkey({ ctrl, shift, alt, meta, code: event.code }, platform); return symbolFires ? normalizeHotkey(symbol, platform) : null; } /** A one-character key other than a letter or digit, such as `?` or `§`. */ function isSymbol(key) { return [...key].length === 1 && !/^(\p{Letter}|[0-9])$/u.test(key); } function chordFromKeydown(event, platform, recordBy) { 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 };