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