UNPKG

shortcutter

Version:

Tiny, dependency-free library to manage keyboard shortcuts in your application.

47 lines (46 loc) 2 kB
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.'); } const SHORTCUTS = new Map(); return { add: (shortcut, callback, phases = "down|press") => { const normalizedShortcut = normalizeShortcut(shortcut); phasesIterator(phases, normalizedShortcut, (phasedShortcut, phase) => { if (SHORTCUTS.has(phasedShortcut)) { throw new Error(`Shortcut "${normalizedShortcut}" is already added to "${phase}" phase.`); } SHORTCUTS.set(phasedShortcut, callback); }); }, get(shortcut, phase) { const normalizedShortcut = normalizeShortcut(shortcut); const phasedShortcut = `${normalizedShortcut}_${phase}`; if (!SHORTCUTS.has(phasedShortcut)) { throw new Error(`Shortcut "${normalizedShortcut}" does not exist in "${contextName}" context.`); } return SHORTCUTS.get(phasedShortcut); }, has(shortcut, phase) { const normalizedShortcut = normalizeShortcut(shortcut); const phasedShortcut = `${normalizedShortcut}_${phase}`; return SHORTCUTS.has(phasedShortcut); }, remove(shortcut, phases = "down|press") { const normalizedShortcut = normalizeShortcut(shortcut); phasesIterator(phases, normalizedShortcut, (phasedShortcut) => { if (!SHORTCUTS.has(phasedShortcut)) { throw new Error(`Shortcut "${normalizedShortcut}" does not exist in "${contextName}" context.`); } SHORTCUTS.delete(phasedShortcut); }); }, getAll() { return [...SHORTCUTS.keys()]; }, clear() { SHORTCUTS.clear(); }, }; }