UNPKG

keyboard-event-to-string

Version:

Converts a JavaScript keyboard event object into a humanly readable string

63 lines 1.87 kB
"use strict"; // Based on // https://github.com/florian/key-event-to-string/blob/master/index.js Object.defineProperty(exports, "__esModule", { value: true }); exports.toString = exports.setOptions = exports.details = void 0; const defaultOptions = { alt: 'Alt', cmd: 'Cmd', ctrl: 'Ctrl', shift: 'Shift', joinWith: ' + ', hideKey: 'never' }; let gOptions = defaultOptions; const hideKeyRegExp = () => ({ 'alphanumeric': /^Key([A-Z01-9])$/, 'alpha': /^Key([A-Z])$/, 'always': /^Key(.*)$/, 'never': /^(.*)$/ })[gOptions.hideKey]; function buildKeyMap(e) { const isOnlyModifier = [16, 17, 18, 91, 93, 224].indexOf(e.keyCode) !== -1; const character = isOnlyModifier ? null : e.code.replace(hideKeyRegExp(), '$1'); return { character: character, modifiers: { cmd: e.metaKey, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey } }; } function buildKeyArray(e) { const map = buildKeyMap(e); const entries = Object.entries(map.modifiers); const result = entries .reduce((memo, [k, v]) => { if (v) memo.push(gOptions[k]); return memo; }, []); if (map.character) result.push(map.character); return result; } function details(e) { const map = buildKeyMap(e); const hasModifier = Object.values(map.modifiers).reduce((m, v) => m || v); return { hasKey: map.character != null, hasModifier: hasModifier, map: map }; } exports.details = details; function setOptions(userOptions) { return gOptions = Object.assign(Object.assign({}, defaultOptions), userOptions); } exports.setOptions = setOptions; const toString = (e) => buildKeyArray(e).join(gOptions.joinWith); exports.toString = toString; //# sourceMappingURL=keyboard-event-to-string.js.map