UNPKG

@konstructio/ui

Version:

A set of reusable and customizable React components built for konstruct.io

82 lines (81 loc) 1.88 kB
import { useState as d, useEffect as m, useCallback as b } from "react"; import { filterByValue as y } from "../../../utils/index.js"; const S = ({ options: u, inputRef: l, wrapperRef: o, onChange: r }) => { const [v, f] = d(() => u ?? []), [O, n] = d(!1), [g, E] = d(""); m(() => { var s; const t = new AbortController(); return (s = l.current) == null || s.addEventListener("focus", () => n(!0), { signal: t.signal }), () => { t.abort(); }; }, [l]), m(() => { const t = new AbortController(), s = (e) => { var a; e.key === "Escape" && (n(!1), (a = l.current) == null || a.blur()); }, c = (e) => { var a; (a = o.current) != null && a.contains(e.target) || n(!1); }; return document.addEventListener("keydown", s, { signal: t.signal }), document.addEventListener("mousedown", c, { signal: t.signal }), () => { t.abort(); }; }, [l, o]), m(() => { var s; const t = new AbortController(); return (s = o.current) == null || s.addEventListener( "focusout", (c) => { var e; (e = o.current) != null && e.contains(c.relatedTarget) || n(!1); }, { signal: t.signal } ), () => { t.abort(); }; }, [o]); const i = b( (t) => { if (t.length === 0) f(u); else { const s = u.map(({ value: e }) => e), c = y(s, t).map( (e) => ({ value: e }) ); f(c); } }, [u] ), k = b( (t) => { E(t.target.value), i(t.target.value), r == null || r(t.target.value); }, [i, r] ), w = b( (t) => { E(t), i(t), r == null || r(t), n(!1); }, [i, r] ); return { inputRef: l, newOptions: v, showOptions: O, value: g, handleChange: k, handleSelectValue: w }; }; export { S as useAutocomplete };