@tanstack/hotkeys
Version:
Type-safe, framework-agnostic keyboard hotkey management for the browser
133 lines (131 loc) • 4.38 kB
JavaScript
import { isKeyNameShape, isModifierCode, modifierAlias, physicalCodeOf, splitChordParts } from "./_keyboard-event.js";
// src/validate.ts
/**
* Validates a hotkey and returns any warnings or errors.
* Each issue has a `reason` code, so apps can write their own messages.
* Issues in a sequence carry the index of their `step`.
*
* Checks for:
* - Valid syntax (modifier+...+key format)
* - Known modifiers
* - A key that isn't a modifier
* - Known keys
*
* @param hotkey - The hotkey string to validate
* @returns A ValidationResult with validity status, warnings, and errors
*
* @example
* ```ts
* validateHotkey('Mod+S')
* // { valid: true, warnings: [], errors: [] }
*
* validateHotkey('')
* // { valid: false, warnings: [], errors: [{ reason: 'empty' }] }
*
* validateHotkey(['G', 'Foo+H'])
* // { valid: false, warnings: [], errors: [{ reason: 'unknown-modifier', part: 'Foo', step: 1 }] }
* ```
*/
function validateHotkey(hotkey) {
if (typeof hotkey !== "string") {
if (hotkey.length === 0) return invalid("empty");
if (hotkey.length === 1) return validateChord(hotkey[0]);
const results = hotkey.map(validateChord);
const withStep = (key) => results.flatMap((result, step) => result[key].map((issue) => ({
...issue,
step
})));
return {
valid: results.every((result) => result.valid),
warnings: withStep("warnings"),
errors: withStep("errors")
};
}
return validateChord(hotkey);
}
function invalid(reason) {
return {
valid: false,
warnings: [],
errors: [{ reason }]
};
}
function validateChord(hotkey) {
const warnings = [];
const errors = [];
if (!hotkey || hotkey.trim() === "") return invalid("empty");
const parts = splitChordParts(hotkey).map((p) => p.trim());
if (parts.length === 0 || parts.some((p) => p === "")) return invalid("empty-part");
const modifierParts = parts.slice(0, -1);
const keyPart = parts[parts.length - 1];
for (const modifier of modifierParts) if (!modifierAlias(modifier)) errors.push({
reason: "unknown-modifier",
part: modifier
});
const code = physicalCodeOf(keyPart);
if (keyPart.length > 1 && (keyPart.startsWith("[") || keyPart.endsWith("]")) && code === void 0) errors.push({
reason: "invalid-physical-key",
part: keyPart
});
if (code !== void 0 ? isModifierCode(code) : modifierAlias(keyPart)) errors.push({
reason: "modifier-only",
part: keyPart
});
if (code === void 0 && !isKeyNameShape(keyPart)) warnings.push({
reason: "unknown-key",
part: keyPart
});
return {
valid: errors.length === 0,
warnings,
errors
};
}
/** Lists issues for a console message, such as `unknown-modifier 'Ctl'`. */
function describeIssues(issues) {
return issues.map(({ reason, part, step }) => (step === void 0 ? "" : `step ${step + 1} `) + reason + (part === void 0 ? "" : ` '${part}'`)).join(", ");
}
/**
* Validates a hotkey and throws an error if invalid.
* Useful for development-time validation.
*
* @param hotkey - The hotkey string to validate
* @throws Error if the hotkey is invalid
*
* @example
* ```ts
* assertValidHotkey('Mod+S') // OK
* assertValidHotkey('') // Throws Error: [hotkeys] Invalid hotkey '': empty
* ```
*/
function assertValidHotkey(hotkey) {
const result = validateHotkey(hotkey);
if (!result.valid) throw new Error(`[hotkeys] Invalid hotkey '${String(hotkey)}': ${describeIssues(result.errors)}`);
}
/**
* Validates a hotkey and logs errors and warnings to the console.
* Useful for development-time feedback. Logs nothing in production builds.
*
* @param hotkey - The hotkey string to validate
* @returns True if the hotkey is valid (may still have warnings)
*
* @example
* ```ts
* checkHotkey('Control+escape')
* // Console: [hotkeys] Hotkey 'Control+escape' may never fire: unknown-key 'escape'
* // Returns: true
*
* checkHotkey('Ctl+K')
* // Console: [hotkeys] Invalid hotkey 'Ctl+K': unknown-modifier 'Ctl'
* // Returns: false
* ```
*/
function checkHotkey(hotkey) {
const result = validateHotkey(hotkey);
if (typeof process !== "undefined" && process.env.NODE_ENV !== "production") {
if (result.errors.length > 0) console.error(`[hotkeys] Invalid hotkey '${String(hotkey)}': ${describeIssues(result.errors)}`);
if (result.warnings.length > 0) console.warn(`[hotkeys] Hotkey '${String(hotkey)}' may never fire: ${describeIssues(result.warnings)}`);
}
return result.valid;
}
export { assertValidHotkey, checkHotkey, validateHotkey };