UNPKG

shortcutter

Version:

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

54 lines (53 loc) 1.73 kB
import { createContext } from './context'; const ERROR_NOT_ADDED = (name) => `Context '${name}' is not added.`; const ERROR_ALREADY_ADDED = (name) => `Context '${name}' is already added.`; export function useContexts() { const ACTIVE_CONTEXTS = new Set(); const AVAILABLE_CONTEXTS = new Map(); return { add(name) { if (AVAILABLE_CONTEXTS.has(name)) { throw new Error(ERROR_ALREADY_ADDED(name)); } const shortcutContext = createContext(name); AVAILABLE_CONTEXTS.set(name, shortcutContext); return shortcutContext; }, clear() { AVAILABLE_CONTEXTS.clear(); }, getActive() { return [...ACTIVE_CONTEXTS.values()]; }, get(name) { if (!AVAILABLE_CONTEXTS.has(name)) { throw new Error(ERROR_NOT_ADDED(name)); } return AVAILABLE_CONTEXTS.get(name); }, getAll() { return [...AVAILABLE_CONTEXTS.keys()]; }, has(name) { return AVAILABLE_CONTEXTS.has(name); }, isActive(name) { return ACTIVE_CONTEXTS.has(name); }, remove(name) { if (!AVAILABLE_CONTEXTS.has(name)) { throw new Error(ERROR_NOT_ADDED(name)); } AVAILABLE_CONTEXTS.delete(name); }, setActive(...contexts) { ACTIVE_CONTEXTS.clear(); contexts.forEach((name) => { if (!AVAILABLE_CONTEXTS.has(name)) { throw new Error(ERROR_NOT_ADDED(name)); } ACTIVE_CONTEXTS.add(name); }); }, }; }