web-ui-pack
Version:
Web package with UI elements
25 lines (24 loc) • 865 B
JavaScript
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;
}