UNPKG

@hypothesis/frontend-shared

Version:

Shared components, styles and utilities for Hypothesis projects

28 lines 919 B
import { useEffect } from 'preact/hooks'; import { ListenerCollection } from '../util/listener-collection'; /** * Listen on container for focusout events. If a focusout event's relatedTarget * is outside of the `container` element, invoke the `callback`. * Do not listen if not `enabled`. */ export function useFocusAway(container, callback, { enabled = true } = {}) { useEffect(() => { if (!enabled || !container.current) { return () => {}; } const listeners = new ListenerCollection(); listeners.add(container.current, 'focusout', e => { // Event type is not being properly inferred as FocusEvent const event = e; if (container.current && !container.current.contains(event.relatedTarget)) { callback(event); } }); return () => { listeners.removeAll(); }; }, [container, enabled, callback]); } //# sourceMappingURL=use-focus-away.js.map