@konstructio/ui
Version:
A set of reusable and customizable React components built for konstruct.io
77 lines (76 loc) • 1.71 kB
JavaScript
import { useState as i, useEffect as d, useCallback as g } from "react";
import { filterByValue as k } from "../../../utils/index.js";
const A = ({
options: l,
inputRef: n,
wrapperRef: o,
onChange: a
}) => {
const [f, m] = i(() => l ?? []), [h, s] = i(!1), [E, b] = i("");
d(() => {
const t = new AbortController();
return n.current?.addEventListener("focus", () => s(!0), {
signal: t.signal
}), () => {
t.abort();
};
}, [n]), d(() => {
const t = new AbortController(), r = (e) => {
e.key === "Escape" && (s(!1), n.current?.blur());
}, u = (e) => {
o.current?.contains(e.target) || s(!1);
};
return document.addEventListener("keydown", r, {
signal: t.signal
}), document.addEventListener("mousedown", u, {
signal: t.signal
}), () => {
t.abort();
};
}, [n, o]), d(() => {
const t = new AbortController();
return o.current?.addEventListener(
"focusout",
(r) => {
o.current?.contains(r.relatedTarget) || s(!1);
},
{ signal: t.signal }
), () => {
t.abort();
};
}, [o]);
const c = g(
(t) => {
if (t.length === 0)
m(l);
else {
const r = l.map(({ value: e }) => e), u = k(r, t).map(
(e) => ({ value: e })
);
m(u);
}
},
[l]
), v = g(
(t) => {
b(t.target.value), c(t.target.value), a?.(t.target.value);
},
[c, a]
), O = g(
(t) => {
b(t), c(t), a?.(t), s(!1);
},
[c, a]
);
return {
inputRef: n,
newOptions: f,
showOptions: h,
value: E,
handleChange: v,
handleSelectValue: O
};
};
export {
A as useAutocomplete
};