UNPKG

@konstructio/ui

Version:

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

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