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