UNPKG

web-ui-pack

Version:
25 lines (24 loc) 865 B
import onFocusLost from "./onFocusLost"; export default function onFocusGot(element, listener, options) { let isLost = true; let removeLost; const remove = () => { removeLost?.call(element); element.removeEventListener("focusin", focusin); }; const focusin = (e) => { if (!isLost) { return; } const isFocused = (a) => element === a || element.contains(a); const isPrevFocused = e.relatedTarget instanceof Node && isFocused(e.relatedTarget); removeLost = removeLost || onFocusLost(element, () => (isLost = true), options); if (!isPrevFocused) { listener.call(element, e); options?.once && remove(); isLost = false; } }; element.addEventListener("focusin", focusin, { passive: true, ...options }); return remove; }