UNPKG

@tanstack/hotkeys

Version:

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

99 lines (97 loc) • 4.17 kB
import { NON_TYPING_KEY, NUMPAD_KEY_VALUES } from "./_constants.js"; import { canWarn } from "./_dev.js"; import { codeToLogicalKey, isTypedText } from "./_keyboard-event.js"; import { ownValue } from "./_keys.js"; // src/_registration.ts /** * Merges option layers left to right. A key set to `undefined` keeps the * earlier layer's value, so an unset option keeps its default. Getters are * read once. */ function definedOptions(...layers) { const result = {}; for (const layer of layers) { if (!layer) continue; for (const key of Object.keys(layer)) { const value = layer[key]; if (value !== void 0) result[key] = value; } } return result; } /** * Merges options over defaults for an API whose `setOptions` treats * `undefined` as "clear". An unset option takes its default, or stays * `undefined` to clear an earlier value when it has no default. */ function withDefaults(defaults, options) { return { ...options, ...definedOptions(defaults, options) }; } /** * Resolves `ignoreInputs: 'auto'` from the hotkey (the first step of a sequence). * Ctrl/Meta shortcuts, Escape, function keys, and media keys fire in inputs, * with any modifiers. Other single keys and Shift/Alt combos are ignored. */ function getDefaultIgnoreInputs(parsedChord) { if (parsedChord.ctrl || parsedChord.meta) return false; const key = parsedChord.key ?? parsedChord.code; if (key === "Escape") return false; if (NON_TYPING_KEY.test(key)) return false; return true; } /** Whether a key, or the key at a physical position, types a character. */ function typesCharacter(chord) { if (chord.code?.startsWith("Intl")) return true; const key = chord.code === void 0 ? chord.key : codeToLogicalKey(chord.code) ?? ownValue(NUMPAD_KEY_VALUES, chord.code); return key === "Space" || key !== void 0 && isTypedText(key); } /** * Whether a hotkey is a character key shortcut in the WCAG 2.1.4 sense: every * step is a key that types a character (a letter, digit, punctuation mark, or * symbol, or the space bar), alone or with Shift. Control, Alt, and Meta make * a chord a modifier shortcut, and keys such as Escape, Enter, arrows, and F1 * type nothing. */ function isCharacterKeyShortcut(steps) { return steps.every((chord) => !chord.ctrl && !chord.alt && !chord.meta && typesCharacter(chord)); } /** * Handles a registration that duplicates an existing one, based on conflict * behavior. Both registrations stay unless `'error'` throws. * * @param keyDisplay - Display string for the conflicting key/sequence (for error messages) * @param conflictBehavior - How to handle the conflict */ function handleConflict(keyDisplay, conflictBehavior) { if (conflictBehavior === "warn") { if (canWarn && process.env.NODE_ENV !== "production") console.warn(`[hotkeys] '${keyDisplay}' is already registered`); return; } if (conflictBehavior === "error") throw new Error(`[hotkeys] '${keyDisplay}' is already registered`); } /** * Compare updates without publishing unchanged options. A component can pass * `meta` inline: its primitive fields compare by value, and its object and * function fields, such as arrays, elements and callbacks, by kind only: * array, function, or other object. * Frameworks rebuild those on every render, and publishing them would * re-render registration lists, which render the caller again and loop. The * registration still keeps the newest ones. */ function optionsEqual(left, right) { return recordsEqual(left, right, (key, a, b) => key === "meta" && isReference(a) && isReference(b) ? recordsEqual(a, b, (_, x, y) => Object.is(x, y) || sameKind(x, y)) : Object.is(a, b)); } function recordsEqual(a, b, equal) { const keys = Object.keys(a); return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(key, a[key], b[key])); } function isReference(value) { return typeof value === "object" && value !== null || typeof value === "function"; } function sameKind(a, b) { return isReference(a) && isReference(b) && typeof a === typeof b && Array.isArray(a) === Array.isArray(b); } export { definedOptions, getDefaultIgnoreInputs, handleConflict, isCharacterKeyShortcut, optionsEqual, withDefaults };