shortcutter
Version:
Tiny, dependency-free library to manage keyboard shortcuts in your application.
74 lines (73 loc) • 3.16 kB
JavaScript
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import { normalizeShortcut, phasesIterator } from './helpers';
export function createContext(contextName) {
if (typeof contextName !== 'string' || contextName.length < 1) {
throw new Error('Context has to has a name.');
}
var SHORTCUTS = new Map();
return {
add: function (shortcut, callback, phases) {
if (phases === void 0) { phases = "down|press"; }
var normalizedShortcut = normalizeShortcut(shortcut);
phasesIterator(phases, normalizedShortcut, function (phasedShortcut, phase) {
if (SHORTCUTS.has(phasedShortcut)) {
throw new Error("Shortcut \"".concat(normalizedShortcut, "\" is already added to \"").concat(phase, "\" phase."));
}
SHORTCUTS.set(phasedShortcut, callback);
});
},
get: function (shortcut, phase) {
var normalizedShortcut = normalizeShortcut(shortcut);
var phasedShortcut = "".concat(normalizedShortcut, "_").concat(phase);
if (!SHORTCUTS.has(phasedShortcut)) {
throw new Error("Shortcut \"".concat(normalizedShortcut, "\" does not exist in \"").concat(contextName, "\" context."));
}
return SHORTCUTS.get(phasedShortcut);
},
has: function (shortcut, phase) {
var normalizedShortcut = normalizeShortcut(shortcut);
var phasedShortcut = "".concat(normalizedShortcut, "_").concat(phase);
return SHORTCUTS.has(phasedShortcut);
},
remove: function (shortcut, phases) {
if (phases === void 0) { phases = "down|press"; }
var normalizedShortcut = normalizeShortcut(shortcut);
phasesIterator(phases, normalizedShortcut, function (phasedShortcut) {
if (!SHORTCUTS.has(phasedShortcut)) {
throw new Error("Shortcut \"".concat(normalizedShortcut, "\" does not exist in \"").concat(contextName, "\" context."));
}
SHORTCUTS.delete(phasedShortcut);
});
},
getAll: function () {
return __spreadArray([], __read(SHORTCUTS.keys()), false);
},
clear: function () {
SHORTCUTS.clear();
},
};
}