UNPKG

@can-it/react

Version:
84 lines (83 loc) 2.22 kB
import { createContext as u, useReducer as h, useContext as d, useCallback as c, useState as w, useEffect as f } from "react"; import { jsx as l } from "react/jsx-runtime"; const p = u({}), y = u(void 0), C = (o, t) => { switch (t.type) { case "set": return { ...o, policy: t.payload.policy }; case "update": return { ...o, policy: t.payload(o.policy) }; } }; function x({ children: o, policy: t, comparators: e }) { const [i, n] = h(C, { policy: t, comparators: e }); return /* @__PURE__ */ l(p.Provider, { value: i, children: /* @__PURE__ */ l(y.Provider, { value: n, children: o }) }); } function P() { return d(p); } function D() { const o = d(y); if (!o) throw new Error("You can only use this usePolicyDispatch inside PolicyStore children"); const t = c( (i) => o({ type: "set", payload: { policy: i } }), [o] ), e = c( (i) => o({ type: "update", payload: i }), [o] ); return { set: t, update: e }; } class a { isAllowed(t, e) { return t === e; } isDenied(t, e) { return this.isAllowed(t, e); } } let A = class { constructor(t, e, i) { this.policyState = t, this.actionOperator = e || new a(), this.riOperator = i || new a(); } allowTo(t, e) { var i; return (i = this.policyState.deny) != null && i.find( (n) => this.isRequestDenied([t, e], n) ) ? !1 : !!this.policyState.allow.find( (n) => this.isRequestAllowed([t, e], n) ); } isRequestDenied(t, e) { const [i, n] = t, [s, r] = e; return this.riOperator.isDenied(n, r) && this.actionOperator.isDenied(i, s); } isRequestAllowed(t, e) { const [i, n] = t, [s, r] = e; return this.riOperator.isAllowed(n, r) && this.actionOperator.isAllowed(i, s); } }; function R(...o) { const [t, e] = w(), { policy: i, comparators: n } = P(); return f(() => { if (!i) { e(void 0); return; } const s = new A(i, n == null ? void 0 : n.action, n == null ? void 0 : n.ri); e(s.allowTo(...o)); }, [o, i, n]), t; } function I({ children: o, allowTo: t, else: e }) { return R(...t) ? o : e; } export { I as CanIt, x as CanItProvider, R as useCanIt, P as usePolicyState, D as usePolicyStore };