UNPKG

@konstructio/ui

Version:

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

139 lines (138 loc) 2.79 kB
import { jsx as V } from "react/jsx-runtime"; import { useRef as k, useState as R, useEffect as g, useCallback as S } from "react"; import { MultiSelectDropdownContext as C } from "./MultiSelectDropdown.context.js"; import { useToggle as E } from "../../../hooks/useToggle.js"; const q = ({ children: x, defaultOptions: r = [], multiselect: i = !0, value: f, onChange: m, onBlur: u, name: h, isLoading: b, noOptionsText: j }) => { const d = k(null), [w, I] = E(!1), [y, p] = R(r), [c, v] = R([]), o = f !== void 0; g(() => { if (!o) { const n = new Set( c.map((e) => e.id) ); p( i ? r.filter((e) => !n.has(e.id)) : r.map((e) => ({ ...e, isSelected: n.has(e.id) })) ); } }, [r, i, o, c]), g(() => { if (o) { const n = f || []; v(n); const e = new Set(n.map((s) => s.id)); p( i ? r.filter((s) => !e.has(s.id)) : r.map((s) => ({ ...s, isSelected: e.has(s.id) })) ); } }, [f, o, r, i]); const l = S( (n) => { const e = n.map(({ id: t, value: O, label: P }) => ({ id: t, value: O ?? P })), s = JSON.stringify(e); d.current && (d.current.value = s), m && m({ target: { value: n, name: h ?? "" } }); }, [m, h] ), a = S( (n) => { const e = w; I(n), e && n === !1 && u && d.current && u({ target: d.current, type: "blur" }); }, [w, I, u, d] ), D = S( (n) => { if (o) { const t = [ ...i ? c : [], n ]; l(t), a(!1); return; } const e = [ ...i ? c : [], n ]; v(e); const s = e.map((t) => t.id); p(() => i ? r.filter( (t) => !s.includes(t.id) ) : r.map((t) => ({ ...t, isSelected: s.includes(t.id) }))), l(e), a(!1); }, [ r, l, i, c, a, o ] ), M = S( (n) => { if (o) { const t = c.filter( (O) => O.id !== n.id ); l(t); return; } const e = c.filter( (t) => t.id !== n.id ); v(e); const s = e.map((t) => t.id); p( () => r.filter( (t) => !s.includes(t.id) ) ), l(e); }, [r, l, c, o] ); return /* @__PURE__ */ V( C.Provider, { value: { options: y, selectedOptions: c, isOpen: w, inputRef: d, onSelectOption: D, onRemoveOption: M, onOpen: a, isLoading: b, noOptionsText: j }, children: x } ); }; export { q as MultiSelectDropdownProvider };