keyboard-event-to-string
Version:
Converts a JavaScript keyboard event object into a humanly readable string
57 lines • 1.66 kB
JavaScript
// Based on
// https://github.com/florian/key-event-to-string/blob/master/index.js
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;
}
export 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
};
}
export function setOptions(userOptions) {
return gOptions = Object.assign(Object.assign({}, defaultOptions), userOptions);
}
export const toString = (e) => buildKeyArray(e).join(gOptions.joinWith);
//# sourceMappingURL=keyboard-event-to-string.js.map