UNPKG

@hypothesis/frontend-shared

Version:

Shared components, styles and utilities for Hypothesis projects

28 lines 806 B
import { useEffect } from 'preact/hooks'; import { ListenerCollection } from '../util/listener-collection'; /** * Listen on HTMLElement `target` for key press events for the designated `keys` * and invoke a callback. Do not listen if not `enabled`. * * @param keys - Array of keys (e.g. 'Escape', 'd') to listen for */ export function useKeyPress(keys, callback, { enabled = true } = {}) { useEffect(() => { if (!enabled) { return () => {}; } const target = document.body; const listeners = new ListenerCollection(); listeners.add(target, 'keydown', event => { if (keys.includes(event.key)) { callback(event); } }); return () => { listeners.removeAll(); }; }, [enabled, callback, keys]); } //# sourceMappingURL=use-key-press.js.map