UNPKG

@mitcsutt/kiln-forms

Version:

Kiln forms: typed React forms on TanStack Form, in component or JSON schema mode, rendered through kiln-ui

103 lines (102 loc) • 2 kB
import { useEffect as e, useRef as t, useState as n } from "react"; //#region src/hooks/useOptions.ts var r = 50; function i(e, t, n) { for (e.delete(t), e.set(t, n); e.size > r;) { let t = e.keys().next(); if (t.done) break; e.delete(t.value); } } function a(e, t) { let n = e.get(t); return n && (e.delete(t), e.set(t, n)), n; } var o = []; function s(e) { return typeof e == "object" && !!e && e.name === "AbortError"; } function c(r, c = {}) { let { query: l = "", deps: u, values: d, debounceMs: f = 250, minQueryLength: p = 0 } = c, m = typeof r == "function" ? r : null, h = `${l}\u0000${JSON.stringify(u ?? [])}`, [g, _] = n(() => ({ key: "", result: { options: o, status: "idle" } })), v = t(d), y = t(m), b = t(!0), [x] = n(() => /* @__PURE__ */ new Map()), S = m !== null; return e(() => { v.current = d, y.current = m; }), e(() => { if (!S) return; if (l.length < p) { _({ key: h, result: { options: o, status: "idle" } }); return; } let e = a(x, h); if (e) { _({ key: h, result: { options: e, status: "ready" } }); return; } let t = new AbortController(), n = b.current ? 0 : f; b.current = !1, _((e) => ({ key: h, result: { options: e.result.options, status: "loading" } })); let r = setTimeout(() => { let e = y.current; e && e({ query: l, values: v.current, signal: t.signal }).then((e) => { t.signal.aborted || (i(x, h, e), _({ key: h, result: { options: e, status: "ready" } })); }, (e) => { t.signal.aborted || s(e) || _((t) => ({ key: h, result: { options: t.result.options, status: "error", error: e } })); }); }, n); return () => { clearTimeout(r), t.abort(); }; }, [ S, x, h, l, p, f ]), m ? g.result : { options: r, status: "ready" }; } //#endregion export { c as useOptions }; //# sourceMappingURL=useOptions.js.map