@can-it/react
Version:
2 lines (1 loc) • 1.76 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react"),l=require("react/jsx-runtime"),u=s.createContext({}),d=s.createContext(void 0),h=(o,t)=>{switch(t.type){case"set":return{...o,policy:t.payload.policy};case"update":return{...o,policy:t.payload(o.policy)}}};function C({children:o,policy:t,comparators:e}){const[i,n]=s.useReducer(h,{policy:t,comparators:e});return l.jsx(u.Provider,{value:i,children:l.jsx(d.Provider,{value:n,children:o})})}function p(){return s.useContext(u)}function w(){const o=s.useContext(d);if(!o)throw new Error("You can only use this usePolicyDispatch inside PolicyStore children");const t=s.useCallback(i=>o({type:"set",payload:{policy:i}}),[o]),e=s.useCallback(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 f=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,[r,c]=e;return this.riOperator.isDenied(n,c)&&this.actionOperator.isDenied(i,r)}isRequestAllowed(t,e){const[i,n]=t,[r,c]=e;return this.riOperator.isAllowed(n,c)&&this.actionOperator.isAllowed(i,r)}};function y(...o){const[t,e]=s.useState(),{policy:i,comparators:n}=p();return s.useEffect(()=>{if(!i){e(void 0);return}const r=new f(i,n==null?void 0:n.action,n==null?void 0:n.ri);e(r.allowTo(...o))},[o,i,n]),t}function P({children:o,allowTo:t,else:e}){return y(...t)?o:e}exports.CanIt=P;exports.CanItProvider=C;exports.useCanIt=y;exports.usePolicyState=p;exports.usePolicyStore=w;