@nacelle/react-hooks
Version:
Custom convenience hooks for use when building apps with Nacelle
17 lines (14 loc) • 12.7 kB
JavaScript
import e,{useReducer as t,useEffect as r,useMemo as n,useContext as a,useState as c,useRef as o,useCallback as i}from"react";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var u=function(){return u=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},u.apply(this,arguments)};function l(e,t,r,n){return new(r||(r=Promise))((function(a,c){function o(e){try{u(n.next(e))}catch(e){c(e)}}function i(e){try{u(n.throw(e))}catch(e){c(e)}}function u(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,i)}u((n=n.apply(e,t||[])).next())}))}function d(e,t){var r,n,a,c,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return c={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function i(c){return function(i){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(a=2&c[0]?n.return:c[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,c[1])).done)return a;switch(n=0,a&&(c=[2&c[0],a.value]),c[0]){case 0:case 1:a=c;break;case 4:return o.label++,{value:c[1],done:!1};case 5:o.label++,n=c[1],c=[0];continue;case 7:c=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==c[0]&&2!==c[0])){o=0;continue}if(3===c[0]&&(!a||c[1]>a[0]&&c[1]<a[3])){o.label=c[1];break}if(6===c[0]&&o.label<a[1]){o.label=a[1],a=c;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(c);break}a[2]&&o.ops.pop(),o.trys.pop();continue}c=t.call(e,o)}catch(e){c=[6,e],n=0}finally{r=a=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,i])}}}function s(e,t,r){if(r||2===arguments.length)for(var n,a=0,c=t.length;a<c;a++)!n&&a in t||(n||(n=Array.prototype.slice.call(t,0,a)),n[a]=t[a]);return e.concat(n||Array.prototype.slice.call(t))}function p(e){return new Promise(((t,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)}))}function f(e,t){const r=(!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise((function(e){var t=function(){return indexedDB.databases().finally(e)};n=setInterval(t,100),t()})).finally((function(){return clearInterval(n)})):Promise.resolve()).then((()=>{const r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),p(r)}));var n;return(e,n)=>r.then((r=>n(r.transaction(t,e).objectStore(t))))}let y;function m(){return y||(y=f("keyval-store","keyval")),y}function h(e,t=m()){return t("readonly",(t=>p(t.get(e))))}function v(e,t){return e.findIndex((function(e){var r;return e.variant.id===(null===(r=t.variant)||void 0===r?void 0:r.id)}))>-1}function g(e){switch(e){case"local":return window.localStorage.setItem.bind(localStorage);case"session":return window.sessionStorage.setItem.bind(sessionStorage);case"idb":return function(e,t){return function(e,t,r=m()){return r("readwrite",(r=>(r.put(t,e),p(r.transaction))))}(e,t)};default:return function(){}}}function w(e){switch(e){case"local":return window.localStorage.removeItem.bind(localStorage);case"session":return window.sessionStorage.removeItem.bind(sessionStorage);case"idb":return function(e){return function(e,t=m()){return t("readwrite",(t=>(t.delete(e),p(t.transaction))))}(e)};default:return function(){}}}var C={cart:[],show:!1},k=function(e,t){switch(t.type){case"cart/init-cart":return t.initCart?t.initCart(e,t):function(e,t){var r=s([],t.payload,!0);return g(t.storage)(t.cacheKey||"cart",JSON.stringify(r)),u(u({},e),{cart:r})}(e,t);case"cart/add-to-cart":return t.addToCart?t.addToCart(e,t):function(e,t){var r=t.isInCart||v,n=r(e.cart,t.payload)?e.cart.map((function(e){return r([e],t.payload)?u(u({},e),{quantity:e.quantity+(t.payload.quantity||1)}):e})):s(s([],e.cart,!0),[u({},t.payload)],!1);return g(t.storage)(t.cacheKey||"cart",JSON.stringify(n)),u(u({},e),{cart:n})}(e,t);case"cart/update-item":return t.updateItem?t.updateItem(e,t):function(e,t){var r=e.cart.map((function(e){var r=t.isInCart||v,n=null;return r([e],t.payload)&&(n=u({},e),Object.keys(e).forEach((function(e){var r=t.payload[e];"id"!==e&&n[e]!==r&&(n[e]=r)}))),n||e}));return g(t.storage)(t.cacheKey||"cart",JSON.stringify(r)),u(u({},e),{cart:r})}(e,t);case"cart/remove-from-cart":return t.removeFromCart?t.removeFromCart(e,t):function(e,t){var r=t.isInCart||v,n=e.cart.filter((function(e){return!r([e],t.payload)}));return g(t.storage)(t.cacheKey||"cart",JSON.stringify(n)),u(u({},e),{cart:n})}(e,t);case"cart/increment-item":return t.incrementItem?t.incrementItem(e,t):function(e,t){var r=e.cart.map((function(e){return(t.isInCart||v)([e],t.payload)?u(u({},e),{quantity:e.quantity+1}):e}));return g(t.storage)(t.cacheKey||"cart",JSON.stringify(r)),u(u({},e),{cart:r})}(e,t);case"cart/decrement-item":return t.decrementItem?t.decrementItem(e,t):function(e,t){var r=e.cart.map((function(e){return(t.isInCart||v)([e],t.payload)?u(u({},e),{quantity:e.quantity-1}):e})).filter((function(e){return e.quantity}));return g(t.storage)(t.cacheKey||"cart",JSON.stringify(r)),u(u({},e),{cart:r})}(e,t);case"cart/clear":return t.clearCart?t.clearCart(e,t):function(e,t){return w(t.storage)(t.cacheKey||"cart"),u(u({},e),{cart:[]})}(e,t);case"cart/toggle-visibility":return t.toggleCart?t.toggleCart(e,t):function(e,t){var r=!e.show,n=t.payload;return n&&("open"===n?r=!0:"closed"===n&&(r=!1)),u(u({},e),{show:r})}(e,t);default:throw new Error("invalid action sent to cart reducer")}},S=e.createContext(null),I=e.createContext(null),b=e.createContext(v),P=function(a){var c=a.children,o=a.storage,i=void 0===o?"local":o,s=a.cacheKey,p=void 0===s?"cart":s,f=a.addToCart,y=a.clearCart,m=a.decrementItem,g=a.incrementItem,w=a.removeFromCart,P=a.toggleCart,E=a.updateItem,x=a.isInCart,A=t(k,C),K=A[0],O=A[1];r((function(){var e,t=[];!function(){l(this,void 0,void 0,(function(){var r,n;return d(this,(function(a){switch(a.label){case 0:return r="",i?"local"!==i?[3,1]:(r=window.localStorage.getItem(p),[3,4]):[3,5];case 1:return"session"!==i?[3,2]:(r=window.sessionStorage.getItem(p),[3,4]);case 2:return"idb"!==i?[3,4]:[4,h(p)];case 3:r=a.sent(),a.label=4;case 4:r&&(e=JSON.parse(r),n=!!(null==e?void 0:e.length)&&e.map((function(e){return"productId"in e})).some((function(e){return e})),(t=n?e.map((function(e){return r=(t=e).quantity,n=t.productId,a=t.image,c=t.availableForSale,o=t.createdAt,i=t.description,l=t.featuredMedia,d=t.globalHandle,s=t.handle,p=t.indexedAt,f=t.locale,y=t.media,m=t.metafields,h=t.pimSyncSource,v=t.pimSyncSourceDomain,g=t.pimSyncSourceLocale,w=t.pimSyncSourceProductId,C=t.priceRange,k=t.productType,S=t.tags,I=t.title,b=t.updatedAt,P=t.variants,E=t.vendor,x=t.compareAtPrice,A=t.compareAtPriceCurrency,K=t.id,O=t.price,T=t.priceCurrency,q=t.selectedOptions,N=t.sku,J=t.swatchSrc,D=t.weight,F=t.weightUnit,{quantity:Number.isInteger(r)?r:1,product:{availableForSale:c,createdAt:o,description:i,featuredMedia:l,globalHandle:d,handle:s,id:n,indexedAt:p,locale:f,media:y,metafields:m,pimSyncSource:h,pimSyncSourceDomain:v,pimSyncSourceLocale:g,pimSyncSourceProductId:w,priceRange:C,productType:k,tags:S,title:I,updatedAt:b,variants:P,vendor:E},variant:u(u({},t.variant),{compareAtPrice:x,compareAtPriceCurrency:A,featuredMedia:a,id:K,price:O,priceCurrency:T,selectedOptions:q,sku:N,swatchSrc:J,weight:D,weightUnit:F})};var t,r,n,a,c,o,i,l,d,s,p,f,y,m,h,v,g,w,C,k,S,I,b,P,E,x,A,K,O,T,q,N,J,D,F})):e)&&O({type:"cart/init-cart",payload:t,storage:i,cacheKey:p})),a.label=5;case 5:return[2]}}))}))}()}),[i,p]);var T=n((function(){return{initCart:function(e){return O({type:"cart/init-cart",payload:e,storage:i,cacheKey:p})},addToCart:function(e){return O({type:"cart/add-to-cart",payload:e,isInCart:x,addToCart:f,storage:i,cacheKey:p})},removeFromCart:function(e){return O({type:"cart/remove-from-cart",payload:e,isInCart:x,removeFromCart:w,storage:i,cacheKey:p})},updateItem:function(e){return O({type:"cart/update-item",payload:e,isInCart:x,updateItem:E,storage:i,cacheKey:p})},incrementItem:function(e){return O({type:"cart/increment-item",payload:e,isInCart:x,incrementItem:g,storage:i,cacheKey:p})},decrementItem:function(e){return O({type:"cart/decrement-item",payload:e,isInCart:x,decrementItem:m,storage:i,cacheKey:p})},toggleCart:function(e){return O({type:"cart/toggle-visibility",payload:e,toggleCart:P})},clearCart:function(){return O({type:"cart/clear",clearCart:y,storage:i})}}}),[x,f,w,E,g,m,P,y,i,p]);return e.createElement(S.Provider,{value:K},e.createElement(I.Provider,{value:T},e.createElement(b.Provider,{value:x||v},c)))};var E=function(){return[a(S),a(I),a(b)]},x="checkoutComplete",A="checkoutId",K="checkoutUrl";function O(e,t){if("undefined"!=typeof window){var r=window.localStorage.getItem(e);return!!r&&JSON.parse(r)}return t}function T(e,t){if(void 0===t&&(t=""),"undefined"!=typeof window){var r=window.localStorage.getItem(e);return r||""}return t}function q(e,t){"undefined"!=typeof window&&t&&window.localStorage.setItem(e,t)}function N(e){"undefined"!=typeof window&&e&&window.localStorage.removeItem(e)}var J={completed:O(x,!1),id:T(A),url:"",getCheckoutError:"",processCheckoutError:""},D=function(e,t){switch(t.type){case"checkout/clear-checkout-data":return N(x),N(A),N(K),{completed:!1,id:"",url:"",getCheckoutError:"",processCheckoutError:""};case"checkout/set-get-checkout-data":return function(e,t){var r=t.payload,n=r.completed,a=r.id,c=r.url;return q(x,n.toString()),q(A,a),q(K,c),u(u({},e),{completed:n,id:a,url:c})}(e,t);case"checkout/set-get-checkout-error":return function(e,t){return q(x,"false"),N(A),N(K),u(u({},e),{completed:!1,id:"",url:"",getCheckoutError:t.payload})}(e,t);case"checkout/set-process-checkout-data":return function(e,t){var r=t.payload,n=r.id,a=r.url;return q(A,n),q(K,a),q(x,"false"),u(u({},e),{completed:!1,id:n,url:a,processCheckoutError:""})}(e,t);case"checkout/set-process-checkout-error":return function(e,t){return q(x,"false"),N(A),N(K),u(u({},e),{completed:!1,id:"",url:"",processCheckoutError:t.payload})}(e,t);default:throw new Error("invalid action sent to checkout reducer")}},F=e.createContext({get:function(){return Promise.resolve({id:"",url:"",completed:!1})},process:function(){return Promise.resolve({id:"",url:"",completed:!1})}}),j=e.createContext(J),U=e.createContext(null),B=e.createContext(!1),L=function(n){var a=n.children,u=n.checkoutClient,l=n.redirectUserToCheckout,d=c(!1),s=d[0],p=d[1],f=o(!0),y=o(!1),m=t(D,J),h=m[0],v=m[1],g=i((function(e){return u.get(e).then((function(e){return v({type:"checkout/set-get-checkout-data",payload:e}),e})).catch((function(e){throw v({type:"checkout/set-get-checkout-error",payload:e}),new Error(e)}))}),[u]),w=i((function(e){return p(!0),u.process(e).then((function(e){return e.id&&"string"==typeof e.id&&q(A,e.id),v({type:"checkout/set-process-checkout-data",payload:e}),p(!1),e})).catch((function(e){throw v({type:"checkout/set-process-checkout-error",payload:e}),p(!1),new Error(e)}))}),[u]);return r((function(){return function(){f.current=!1}}),[]),r((function(){var e=h.completed||O(x,!1),t=h.id||T(A),r=h.url||T(K);!t||!r||e||s||y.current||(y.current=!0,g({id:t,url:r}).catch((function(e){return console.warn(e)})))}),[h,g,s]),r((function(){void 0!==l&&console.warn("[@nacelle/react-hooks|useCheckout] The `redirectUserToCheckout` prop is deprecated. Please handle the customer redirect to the checkout URL in your project code.")})),e.createElement(F.Provider,{value:u},e.createElement(j.Provider,{value:h},e.createElement(U.Provider,{value:{clearCheckoutData:function(){return v({type:"checkout/clear-checkout-data"})},getCheckout:g,processCheckout:w}},e.createElement(B.Provider,{value:s},a))))};var M=function(){return[a(j),a(U),a(B)]};export{P as CartProvider,L as CheckoutProvider,E as useCart,M as useCheckout};
//# sourceMappingURL=index.es.js.map