@clopezochoa/detect-autofill-react
Version:
React hook to detect browser's autofill
62 lines (61 loc) • 1.93 kB
JavaScript
import { useRef as c, useLayoutEffect as w, useEffect as T } from "react";
import { detectAutofill as p } from "../assets/detect-autofill.js";
import '../assets/useDetectAutofill.css';/* empty css */
function v() {
const t = /* @__PURE__ */ new Set();
return {
subscribe(o) {
return t.add(o), {
unsubscribe: () => t.delete(o)
};
},
next(o) {
t.forEach((n) => n(o));
}
};
}
const L = (t) => {
const o = c(!1), n = c(v()), u = c(null);
return w(() => {
if (!t) return;
const r = window.setTimeout(() => {
t.style.animation = "none", t.offsetWidth, t.style.animation = "";
}, 10);
return () => {
clearTimeout(r);
};
}, [t]), T(() => {
if (!t) return;
let r = !0;
u.current = new AbortController();
const a = u.current.signal, i = (e) => {
!r || o.current === e || (o.current = e, n.current.next(e));
}, f = (e) => {
e.animationName === "onAutoFillStart" ? i(!0) : e.animationName === "onAutoFillCancel" && i(!1);
};
t.addEventListener("animationstart", f);
const b = window.setTimeout(() => {
p(t, a).then((e) => {
r && !a.aborted && i(e);
});
}, 60), s = () => {
a.aborted || (t.focus(), window.setTimeout(() => {
t.blur(), window.setTimeout(() => {
t.value.trim() !== "" && i(!0);
}, 1);
}, 0));
}, d = () => s(), l = () => s();
t.addEventListener("input", d), window.addEventListener("load", l);
const m = window.setTimeout(s, 1e3);
return () => {
var e;
r = !1, t.removeEventListener("animationstart", f), t.removeEventListener("input", d), window.removeEventListener("load", l), (e = u.current) == null || e.abort(), clearTimeout(b), clearTimeout(m);
};
}, [t]), {
autofillStatusRef: o,
autofillStatusSubject: n.current
};
};
export {
L as useAutofillDetectionRef
};