@nosto/nosto-react 2.2.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/index.d.ts +13 -16
  2. package/dist/index.es.js +257 -866
  3. package/dist/index.umd.js +1 -25
  4. package/package.json +3 -3
  5. package/src/components/Nosto404.tsx +2 -25
  6. package/src/components/NostoCategory.tsx +2 -30
  7. package/src/components/NostoCheckout.tsx +2 -25
  8. package/src/components/NostoHome.tsx +2 -26
  9. package/src/components/NostoOrder.tsx +2 -33
  10. package/src/components/NostoOther.tsx +2 -25
  11. package/src/components/NostoPlacement.tsx +1 -1
  12. package/src/components/NostoProduct.tsx +2 -32
  13. package/src/components/NostoProvider.tsx +11 -10
  14. package/src/components/NostoSearch.tsx +2 -30
  15. package/src/components/NostoSession.tsx +2 -43
  16. package/src/components/helpers.ts +2 -2
  17. package/src/context.ts +0 -1
  18. package/src/hooks/scriptLoader.ts +4 -4
  19. package/src/hooks/useDeepCompareEffect.ts +4 -7
  20. package/src/hooks/useLoadClientScript.ts +9 -4
  21. package/src/hooks/useNosto404.tsx +25 -0
  22. package/src/hooks/useNostoApi.ts +4 -11
  23. package/src/hooks/useNostoCategory.tsx +31 -0
  24. package/src/hooks/useNostoCheckout.tsx +25 -0
  25. package/src/hooks/useNostoContext.ts +2 -3
  26. package/src/hooks/useNostoHome.tsx +25 -0
  27. package/src/hooks/useNostoOrder.tsx +35 -0
  28. package/src/hooks/useNostoOther.tsx +25 -0
  29. package/src/hooks/useNostoProduct.tsx +37 -0
  30. package/src/hooks/useNostoSearch.tsx +31 -0
  31. package/src/hooks/useNostoSession.tsx +33 -0
  32. package/src/hooks/useRenderCampaigns.tsx +10 -8
  33. package/src/index.ts +21 -2
  34. package/src/types.ts +775 -733
  35. package/src/utils/types.ts +5 -3
  36. package/src/components/index.ts +0 -11
  37. package/src/hooks/index.ts +0 -5
package/dist/index.umd.js CHANGED
@@ -1,25 +1 @@
1
- (function(m,E){typeof exports=="object"&&typeof module<"u"?E(exports,require("react"),require("react-dom/client")):typeof define=="function"&&define.amd?define(["exports","react","react-dom/client"],E):(m=typeof globalThis<"u"?globalThis:m||self,E(m["@nosto/nosto-react"]={},m.React,m.ReactDOM))})(this,function(m,E,Ge){"use strict";const ue=t=>String(t)==="[object Object]";function le(t){if(!ue(t))return!1;const o=t.constructor;if(o===void 0)return!0;const a=o.prototype;return!(!ue(a)||!a.hasOwnProperty("isPrototypeOf"))}function Z(t,o){if(t===o)return!0;if(t instanceof Date&&o instanceof Date)return t.getTime()===o.getTime();if(t instanceof Array&&o instanceof Array)return t.length!==o.length?!1:t.every((a,c)=>Z(a,o[c]));if(le(t)&&le(o)){const a=Object.entries(t);return a.length!==Object.keys(o).length?!1:a.every(([c,i])=>Z(i,o[c]))}return!1}function fe(t,o){return E.useEffect(t,Ke(o))}function Ke(t){const o=E.useRef(t),a=E.useRef(0);return Z(t,o.current)||(o.current=t,a.current+=1),E.useMemo(()=>o.current,[a.current])}const q=E.createContext({account:"",currentVariation:"",responseMode:"HTML",clientScriptLoaded:!1});function H(){return E.useContext(q)}function A(t,o,a){const{clientScriptLoaded:c,currentVariation:i,responseMode:p}=H();(a!=null&&a.deep?fe:E.useEffect)(()=>{c&&window.nostojs(h=>{h.defaultSession().setVariation(i).setResponseMode(p),t(h)})},[c,i,p,...o??[]])}var Q={exports:{}},M={};/**
2
- * @license React
3
- * react-jsx-runtime.production.min.js
4
- *
5
- * Copyright (c) Facebook, Inc. and its affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */var de;function $e(){if(de)return M;de=1;var t=E,o=Symbol.for("react.element"),a=Symbol.for("react.fragment"),c=Object.prototype.hasOwnProperty,i=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};function C(h,g,O){var w,f={},S=null,j=null;O!==void 0&&(S=""+O),g.key!==void 0&&(S=""+g.key),g.ref!==void 0&&(j=g.ref);for(w in g)c.call(g,w)&&!p.hasOwnProperty(w)&&(f[w]=g[w]);if(h&&h.defaultProps)for(w in g=h.defaultProps,g)f[w]===void 0&&(f[w]=g[w]);return{$$typeof:o,type:h,key:S,ref:j,props:f,_owner:i.current}}return M.Fragment=a,M.jsx=C,M.jsxs=C,M}var W={};/**
10
- * @license React
11
- * react-jsx-runtime.development.js
12
- *
13
- * Copyright (c) Facebook, Inc. and its affiliates.
14
- *
15
- * This source code is licensed under the MIT license found in the
16
- * LICENSE file in the root directory of this source tree.
17
- */var me;function Xe(){return me||(me=1,process.env.NODE_ENV!=="production"&&function(){var t=E,o=Symbol.for("react.element"),a=Symbol.for("react.portal"),c=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),p=Symbol.for("react.profiler"),C=Symbol.for("react.provider"),h=Symbol.for("react.context"),g=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),w=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),j=Symbol.for("react.offscreen"),F=Symbol.iterator,B="@@iterator";function z(e){if(e===null||typeof e!="object")return null;var r=F&&e[F]||e[B];return typeof r=="function"?r:null}var T=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(e){{for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];pt("error",e,n)}}function pt(e,r,n){{var s=T.ReactDebugCurrentFrame,d=s.getStackAddendum();d!==""&&(r+="%s",n=n.concat([d]));var v=n.map(function(l){return String(l)});v.unshift("Warning: "+r),Function.prototype.apply.call(console[e],console,v)}}var ht=!1,gt=!1,yt=!1,Rt=!1,Et=!1,Ce;Ce=Symbol.for("react.module.reference");function wt(e){return!!(typeof e=="string"||typeof e=="function"||e===c||e===p||Et||e===i||e===O||e===w||Rt||e===j||ht||gt||yt||typeof e=="object"&&e!==null&&(e.$$typeof===S||e.$$typeof===f||e.$$typeof===C||e.$$typeof===h||e.$$typeof===g||e.$$typeof===Ce||e.getModuleId!==void 0))}function bt(e,r,n){var s=e.displayName;if(s)return s;var d=r.displayName||r.name||"";return d!==""?n+"("+d+")":n}function _e(e){return e.displayName||"Context"}function N(e){if(e==null)return null;if(typeof e.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case c:return"Fragment";case a:return"Portal";case p:return"Profiler";case i:return"StrictMode";case O:return"Suspense";case w:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case h:var r=e;return _e(r)+".Consumer";case C:var n=e;return _e(n._context)+".Provider";case g:return bt(e,e.render,"ForwardRef");case f:var s=e.displayName||null;return s!==null?s:N(e.type)||"Memo";case S:{var d=e,v=d._payload,l=d._init;try{return N(l(v))}catch{return null}}}return null}var x=Object.assign,Y=0,Se,Pe,Oe,Te,je,Ne,ke;function Ae(){}Ae.__reactDisabledLog=!0;function Ct(){{if(Y===0){Se=console.log,Pe=console.info,Oe=console.warn,Te=console.error,je=console.group,Ne=console.groupCollapsed,ke=console.groupEnd;var e={configurable:!0,enumerable:!0,value:Ae,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}Y++}}function _t(){{if(Y--,Y===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:x({},e,{value:Se}),info:x({},e,{value:Pe}),warn:x({},e,{value:Oe}),error:x({},e,{value:Te}),group:x({},e,{value:je}),groupCollapsed:x({},e,{value:Ne}),groupEnd:x({},e,{value:ke})})}Y<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var te=T.ReactCurrentDispatcher,re;function J(e,r,n){{if(re===void 0)try{throw Error()}catch(d){var s=d.stack.trim().match(/\n( *(at )?)/);re=s&&s[1]||""}return`
18
- `+re+e}}var ne=!1,G;{var St=typeof WeakMap=="function"?WeakMap:Map;G=new St}function De(e,r){if(!e||ne)return"";{var n=G.get(e);if(n!==void 0)return n}var s;ne=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var v;v=te.current,te.current=null,Ct();try{if(r){var l=function(){throw Error()};if(Object.defineProperty(l.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(l,[])}catch(k){s=k}Reflect.construct(e,[],l)}else{try{l.call()}catch(k){s=k}e.call(l.prototype)}}else{try{throw Error()}catch(k){s=k}e()}}catch(k){if(k&&s&&typeof k.stack=="string"){for(var u=k.stack.split(`
19
- `),_=s.stack.split(`
20
- `),y=u.length-1,R=_.length-1;y>=1&&R>=0&&u[y]!==_[R];)R--;for(;y>=1&&R>=0;y--,R--)if(u[y]!==_[R]){if(y!==1||R!==1)do if(y--,R--,R<0||u[y]!==_[R]){var P=`
21
- `+u[y].replace(" at new "," at ");return e.displayName&&P.includes("<anonymous>")&&(P=P.replace("<anonymous>",e.displayName)),typeof e=="function"&&G.set(e,P),P}while(y>=1&&R>=0);break}}}finally{ne=!1,te.current=v,_t(),Error.prepareStackTrace=d}var I=e?e.displayName||e.name:"",Je=I?J(I):"";return typeof e=="function"&&G.set(e,Je),Je}function Pt(e,r,n){return De(e,!1)}function Ot(e){var r=e.prototype;return!!(r&&r.isReactComponent)}function K(e,r,n){if(e==null)return"";if(typeof e=="function")return De(e,Ot(e));if(typeof e=="string")return J(e);switch(e){case O:return J("Suspense");case w:return J("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case g:return Pt(e.render);case f:return K(e.type,r,n);case S:{var s=e,d=s._payload,v=s._init;try{return K(v(d),r,n)}catch{}}}return""}var $=Object.prototype.hasOwnProperty,xe={},Fe=T.ReactDebugCurrentFrame;function X(e){if(e){var r=e._owner,n=K(e.type,e._source,r?r.type:null);Fe.setExtraStackFrame(n)}else Fe.setExtraStackFrame(null)}function Tt(e,r,n,s,d){{var v=Function.call.bind($);for(var l in e)if(v(e,l)){var u=void 0;try{if(typeof e[l]!="function"){var _=Error((s||"React class")+": "+n+" type `"+l+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[l]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw _.name="Invariant Violation",_}u=e[l](r,l,s,n,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(y){u=y}u&&!(u instanceof Error)&&(X(d),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",s||"React class",n,l,typeof u),X(null)),u instanceof Error&&!(u.message in xe)&&(xe[u.message]=!0,X(d),b("Failed %s type: %s",n,u.message),X(null))}}}var jt=Array.isArray;function oe(e){return jt(e)}function Nt(e){{var r=typeof Symbol=="function"&&Symbol.toStringTag,n=r&&e[Symbol.toStringTag]||e.constructor.name||"Object";return n}}function kt(e){try{return Le(e),!1}catch{return!0}}function Le(e){return""+e}function Ie(e){if(kt(e))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Nt(e)),Le(e)}var U=T.ReactCurrentOwner,At={key:!0,ref:!0,__self:!0,__source:!0},Me,We,ae;ae={};function Dt(e){if($.call(e,"ref")){var r=Object.getOwnPropertyDescriptor(e,"ref").get;if(r&&r.isReactWarning)return!1}return e.ref!==void 0}function xt(e){if($.call(e,"key")){var r=Object.getOwnPropertyDescriptor(e,"key").get;if(r&&r.isReactWarning)return!1}return e.key!==void 0}function Ft(e,r){if(typeof e.ref=="string"&&U.current&&r&&U.current.stateNode!==r){var n=N(U.current.type);ae[n]||(b('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',N(U.current.type),e.ref),ae[n]=!0)}}function Lt(e,r){{var n=function(){Me||(Me=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",r))};n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}}function It(e,r){{var n=function(){We||(We=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",r))};n.isReactWarning=!0,Object.defineProperty(e,"ref",{get:n,configurable:!0})}}var Mt=function(e,r,n,s,d,v,l){var u={$$typeof:o,type:e,key:r,ref:n,props:l,_owner:v};return u._store={},Object.defineProperty(u._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(u,"_self",{configurable:!1,enumerable:!1,writable:!1,value:s}),Object.defineProperty(u,"_source",{configurable:!1,enumerable:!1,writable:!1,value:d}),Object.freeze&&(Object.freeze(u.props),Object.freeze(u)),u};function Wt(e,r,n,s,d){{var v,l={},u=null,_=null;n!==void 0&&(Ie(n),u=""+n),xt(r)&&(Ie(r.key),u=""+r.key),Dt(r)&&(_=r.ref,Ft(r,d));for(v in r)$.call(r,v)&&!At.hasOwnProperty(v)&&(l[v]=r[v]);if(e&&e.defaultProps){var y=e.defaultProps;for(v in y)l[v]===void 0&&(l[v]=y[v])}if(u||_){var R=typeof e=="function"?e.displayName||e.name||"Unknown":e;u&&Lt(l,R),_&&It(l,R)}return Mt(e,u,_,d,s,U.current,l)}}var ie=T.ReactCurrentOwner,Ve=T.ReactDebugCurrentFrame;function L(e){if(e){var r=e._owner,n=K(e.type,e._source,r?r.type:null);Ve.setExtraStackFrame(n)}else Ve.setExtraStackFrame(null)}var se;se=!1;function ce(e){return typeof e=="object"&&e!==null&&e.$$typeof===o}function Ye(){{if(ie.current){var e=N(ie.current.type);if(e)return`
22
-
23
- Check the render method of \``+e+"`."}return""}}function Vt(e){return""}var Ue={};function Yt(e){{var r=Ye();if(!r){var n=typeof e=="string"?e:e.displayName||e.name;n&&(r=`
24
-
25
- Check the top-level render call using <`+n+">.")}return r}}function He(e,r){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var n=Yt(r);if(Ue[n])return;Ue[n]=!0;var s="";e&&e._owner&&e._owner!==ie.current&&(s=" It was passed a child from "+N(e._owner.type)+"."),L(e),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,s),L(null)}}function Be(e,r){{if(typeof e!="object")return;if(oe(e))for(var n=0;n<e.length;n++){var s=e[n];ce(s)&&He(s,r)}else if(ce(e))e._store&&(e._store.validated=!0);else if(e){var d=z(e);if(typeof d=="function"&&d!==e.entries)for(var v=d.call(e),l;!(l=v.next()).done;)ce(l.value)&&He(l.value,r)}}}function Ut(e){{var r=e.type;if(r==null||typeof r=="string")return;var n;if(typeof r=="function")n=r.propTypes;else if(typeof r=="object"&&(r.$$typeof===g||r.$$typeof===f))n=r.propTypes;else return;if(n){var s=N(r);Tt(n,e.props,"prop",s,e)}else if(r.PropTypes!==void 0&&!se){se=!0;var d=N(r);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",d||"Unknown")}typeof r.getDefaultProps=="function"&&!r.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ht(e){{for(var r=Object.keys(e.props),n=0;n<r.length;n++){var s=r[n];if(s!=="children"&&s!=="key"){L(e),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",s),L(null);break}}e.ref!==null&&(L(e),b("Invalid attribute `ref` supplied to `React.Fragment`."),L(null))}}function ze(e,r,n,s,d,v){{var l=wt(e);if(!l){var u="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(u+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var _=Vt();_?u+=_:u+=Ye();var y;e===null?y="null":oe(e)?y="array":e!==void 0&&e.$$typeof===o?(y="<"+(N(e.type)||"Unknown")+" />",u=" Did you accidentally export a JSX literal instead of a component?"):y=typeof e,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",y,u)}var R=Wt(e,r,n,d,v);if(R==null)return R;if(l){var P=r.children;if(P!==void 0)if(s)if(oe(P)){for(var I=0;I<P.length;I++)Be(P[I],e);Object.freeze&&Object.freeze(P)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Be(P,e)}return e===c?Ht(R):Ut(R),R}}function Bt(e,r,n){return ze(e,r,n,!0)}function zt(e,r,n){return ze(e,r,n,!1)}var Jt=zt,Gt=Bt;W.Fragment=c,W.jsx=Jt,W.jsxs=Gt}()),W}process.env.NODE_ENV==="production"?Q.exports=$e():Q.exports=Xe();var ee=Q.exports;function Ze(t){return E.cloneElement(t.recommendationComponent,{nostoRecommendation:t.nostoRecommendation})}function qe(t){if(!window.nostojs)throw new Error("Nosto has not yet been initialized");window.nostojs(o=>{o.placements.injectCampaigns(t.recommendations)})}function D(){const{responseMode:t,recommendationComponent:o}=H(),a=E.useRef({});if(t=="HTML")return{renderCampaigns:qe};function c(i){var C;const p=((C=i.campaigns)==null?void 0:C.recommendations)??{};for(const h in p){const g=p[h],O="#"+h,w=document.querySelector(O);w&&(a.current[h]||(a.current[h]=Ge.createRoot(w)),a.current[h].render(ee.jsx(Ze,{recommendationComponent:o,nostoRecommendation:g})))}}return{renderCampaigns:c}}function Qe(){return typeof window.nosto<"u"}function et(t,o){return new Promise((a,c)=>{const i=document.createElement("script");i.type="text/javascript",i.src=t,i.async=!0,i.onload=()=>a(),i.onerror=()=>c(),Object.entries((o==null?void 0:o.attributes)??{}).forEach(([p,C])=>i.setAttribute(p,C)),(o==null?void 0:o.position)==="head"?document.head.appendChild(i):document.body.appendChild(i)})}function tt(t){const{host:o="connect.nosto.com",scriptLoader:a=et,account:c,shopifyMarkets:i,loadScript:p=!0}=t,[C,h]=E.useState(!1);return E.useEffect(()=>{function g(){var f;"nostoReactTest"in window&&((f=window.nosto)==null||f.reload({site:"localhost"})),h(!0)}async function O(f,S={}){const j=`//${o}${f}`,F={"nosto-client-script":"",...S};await a(j,{attributes:F}),g()}function w(){var B,z;const f=document.querySelector("[nosto-client-script]"),S=String((i==null?void 0:i.marketId)||""),j=(i==null?void 0:i.language)||"",F=(f==null?void 0:f.getAttribute("nosto-language"))!==j||(f==null?void 0:f.getAttribute("nosto-market-id"))!==S;if(!f||F){C&&h(!1);const T=document.querySelector("#nosto-sandbox");(B=f==null?void 0:f.parentNode)==null||B.removeChild(f),(z=T==null?void 0:T.parentNode)==null||z.removeChild(T);const b=`/script/shopify/market/nosto.js?merchant=${c}&market=${S}&locale=${j.toLowerCase()}`;O(b,{"nosto-language":j,"nosto-market-id":S})}}if(window.nostojs||(window.nostojs=f=>{(window.nostojs.q=window.nostojs.q||[]).push(f)},window.nostojs(f=>f.setAutoLoad(!1))),!p){window.nosto?g():window.nostojs(g);return}if(!Qe()&&!i){const f=`/include/${c}`;O(f)}i&&w()},[i==null?void 0:i.marketId,i==null?void 0:i.language]),{clientScriptLoaded:C}}function rt(t){return ve(t),null}function ve(t){const{renderCampaigns:o}=D();A(async a=>{const c=await a.defaultSession().viewNotFound().setPlacements((t==null?void 0:t.placements)||a.placements.getPlacements()).load();o(c)})}function nt(t){return pe(t),null}function pe(t){const{renderCampaigns:o}=D();A(async a=>{const c=await a.defaultSession().viewOther().setPlacements((t==null?void 0:t.placements)||a.placements.getPlacements()).load();o(c)})}function ot(t){return he(t),null}function he(t){const{renderCampaigns:o}=D();A(async a=>{const c=await a.defaultSession().viewCart().setPlacements((t==null?void 0:t.placements)||a.placements.getPlacements()).load();o(c)})}function at(t){return ge(t),null}function ge({product:t,tagging:o,placements:a}){const{renderCampaigns:c}=D();A(async i=>{const p=await i.defaultSession().viewProduct(o??t).setPlacements(a||i.placements.getPlacements()).load();c(p)},[t,o==null?void 0:o.selected_sku_id])}function it(t){return ye(t),null}function ye({category:t,placements:o}){const{renderCampaigns:a}=D();A(async c=>{const i=await c.defaultSession().viewCategory(t).setPlacements(o||c.placements.getPlacements()).load();a(i)},[t])}function st(t){return Re(t),null}function Re({query:t,placements:o}){const{renderCampaigns:a}=D();A(async c=>{const i=await c.defaultSession().viewSearch(t).setPlacements(o||c.placements.getPlacements()).load();a(i)},[t])}function V(t){return!t||typeof t!="object"||ct(t)||ut(t)?t:Array.isArray(t)?t.map(V):Object.keys(t).reduce((o,a)=>{const c=a[0].toLowerCase()+a.slice(1).replace(/([A-Z]+)/g,(i,p)=>"_"+p.toLowerCase());return o[c]=V(t[a]),o},{})}function ct(t){return Object.prototype.toString.call(t)==="[object Date]"}function ut(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function lt(t){return Ee(t),null}function Ee({order:t,placements:o}){const{renderCampaigns:a}=D();A(async c=>{const i=await c.defaultSession().addOrder(V(t)).setPlacements(o||c.placements.getPlacements()).load();a(i)},[t],{deep:!0})}function ft(t){return we(t),null}function we(t){const{renderCampaigns:o}=D();A(async a=>{const c=await a.defaultSession().viewFrontPage().setPlacements((t==null?void 0:t.placements)||a.placements.getPlacements()).load();o(c)})}function dt({id:t,pageType:o}){return ee.jsx("div",{className:"nosto_element",id:t},t+(o||""))}function mt(t){const{account:o,multiCurrency:a=!1,children:c,recommendationComponent:i}=t,p=a?t.currentVariation:"";if(i&&!E.isValidElement(i))throw new Error("The recommendationComponent prop must be a valid React element. Please provide a valid React element.");const C=i?"JSON_ORIGINAL":"HTML",{clientScriptLoaded:h}=tt(t);return ee.jsx(q.Provider,{value:{account:o,clientScriptLoaded:h,currentVariation:p,responseMode:C,recommendationComponent:i},children:c})}function vt(t){return be(t),null}function be({cart:t,customer:o}={}){const{clientScriptLoaded:a}=H();fe(()=>{const c=t?V(t):void 0,i=o?V(o):void 0;a&&window.nostojs(p=>{p.defaultSession().setResponseMode("HTML").setCart(c).setCustomer(i).viewOther().load({skipPageViews:!0})})},[a,t,o])}m.Nosto404=rt,m.NostoCategory=it,m.NostoCheckout=ot,m.NostoContext=q,m.NostoHome=ft,m.NostoOrder=lt,m.NostoOther=nt,m.NostoPlacement=dt,m.NostoProduct=at,m.NostoProvider=mt,m.NostoSearch=st,m.NostoSession=vt,m.useNosto404=ve,m.useNostoCategory=ye,m.useNostoCheckout=he,m.useNostoContext=H,m.useNostoHome=we,m.useNostoOrder=Ee,m.useNostoOther=pe,m.useNostoProduct=ge,m.useNostoSearch=Re,m.useNostoSession=be,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
1
+ (function(r,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("react"),require("react/jsx-runtime"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","react-dom"],a):(r=typeof globalThis<"u"?globalThis:r||self,a(r["@nosto/nosto-react"]={},r.React,r["react/jsx-runtime"],r.ReactDOM))})(this,function(r,a,p,z){"use strict";const j=a.createContext({account:"",currentVariation:"",responseMode:"HTML",clientScriptLoaded:!1});function y(){return a.useContext(j)}const R=e=>String(e)==="[object Object]";function L(e){if(!R(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!R(n)||!n.hasOwnProperty("isPrototypeOf"))}function v(e,t){if(e===t)return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Array&&t instanceof Array)return e.length!==t.length?!1:e.every((n,s)=>v(n,t[s]));if(L(e)&&L(t)){const n=Object.entries(e);return n.length!==Object.keys(t).length?!1:n.every(([s,o])=>v(o,t[s]))}return!1}function _(e,t){return a.useEffect(e,U(t))}function U(e){const t=a.useRef(e),n=a.useRef(0);return v(e,t.current)||(t.current=e,n.current+=1),a.useMemo(()=>t.current,[n.current])}function l(e,t,n){const{clientScriptLoaded:s}=y();(n!=null&&n.deep?_:a.useEffect)(()=>{s&&window.nostojs(e)},[s,...t??[]])}var E,S=z;if(process.env.NODE_ENV==="production")E=S.createRoot,S.hydrateRoot;else{var T=S.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;E=function(e,t){T.usingClientEntryPoint=!0;try{return S.createRoot(e,t)}finally{T.usingClientEntryPoint=!1}}}function W(e){return a.cloneElement(e.recommendationComponent,{nostoRecommendation:e.nostoRecommendation})}function B(e){if(!window.nostojs)throw new Error("Nosto has not yet been initialized");window.nostojs(t=>{t.placements.injectCampaigns(e.recommendations)})}function m(){const{responseMode:e,recommendationComponent:t}=y(),n=a.useRef({});if(e=="HTML")return{renderCampaigns:B};function s(o){var d;const i=((d=o.campaigns)==null?void 0:d.recommendations)??{};for(const u in i){const f=i[u],h="#"+u,P=document.querySelector(h);P&&(n.current[u]||(n.current[u]=E(P)),n.current[u].render(p.jsx(W,{recommendationComponent:t,nostoRecommendation:f})))}}return{renderCampaigns:s}}function A(e){const{renderCampaigns:t}=m();l(async n=>{const s=await n.defaultSession().viewNotFound().setPlacements((e==null?void 0:e.placements)||n.placements.getPlacements()).load();t(s)})}function G(e){return A(e),null}function D({category:e,placements:t}){const{renderCampaigns:n}=m();l(async s=>{const o=await s.defaultSession().viewCategory(e).setPlacements(t||s.placements.getPlacements()).load();n(o)},[e])}function J(e){return D(e),null}function k(e){const{renderCampaigns:t}=m();l(async n=>{const s=await n.defaultSession().viewCart().setPlacements((e==null?void 0:e.placements)||n.placements.getPlacements()).load();t(s)})}function Y(e){return k(e),null}function I(e){const{renderCampaigns:t}=m();l(async n=>{const s=await n.defaultSession().viewFrontPage().setPlacements((e==null?void 0:e.placements)||n.placements.getPlacements()).load();t(s)})}function Z(e){return I(e),null}function w(e){return!e||typeof e!="object"||K(e)||Q(e)?e:Array.isArray(e)?e.map(w):Object.keys(e).reduce((t,n)=>{const s=n[0].toLowerCase()+n.slice(1).replace(/([A-Z]+)/g,(o,i)=>"_"+i.toLowerCase());return t[s]=w(e[n]),t},{})}function K(e){return Object.prototype.toString.call(e)==="[object Date]"}function Q(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function q({order:e,placements:t}){const{renderCampaigns:n}=m();l(async s=>{const o=await s.defaultSession().addOrder(w(e)).setPlacements(t||s.placements.getPlacements()).load();n(o)},[e],{deep:!0})}function X(e){return q(e),null}function H(e){const{renderCampaigns:t}=m();l(async n=>{const s=await n.defaultSession().viewOther().setPlacements((e==null?void 0:e.placements)||n.placements.getPlacements()).load();t(s)})}function x(e){return H(e),null}function ee({id:e,pageType:t}){return p.jsx("div",{className:"nosto_element",id:e},e+(t||""))}function V({product:e,tagging:t,placements:n}){const{renderCampaigns:s}=m();if(t&&!t.product_id)throw new Error("The product object must contain a product_id property");l(async o=>{const i=await o.defaultSession().viewProduct(t??e).setPlacements(n||o.placements.getPlacements()).load();s(i)},[e,t==null?void 0:t.selected_sku_id])}function te(e){return V(e),null}function ne(){return typeof window.nosto<"u"}function oe(e,t){return new Promise((n,s)=>{const o=document.createElement("script");o.type="text/javascript",o.src=e,o.async=!0,o.onload=()=>n(),o.onerror=()=>s(),Object.entries((t==null?void 0:t.attributes)??{}).forEach(([i,d])=>o.setAttribute(i,d)),(t==null?void 0:t.position)==="head"?document.head.appendChild(o):document.body.appendChild(o)})}function se(e){const{host:t="connect.nosto.com",scriptLoader:n=oe,account:s,shopifyMarkets:o,loadScript:i=!0}=e,[d,u]=a.useState(!1);return a.useEffect(()=>{function f(){var c;"nostoReactTest"in window&&((c=window.nosto)==null||c.reload({site:"localhost"})),u(!0)}async function h(c,N={}){const C=`//${t}${c}`,g={"nosto-client-script":"",...N};await n(C,{attributes:g}),f()}function P(){var M,F;const c=document.querySelector("[nosto-client-script]"),N=String((o==null?void 0:o.marketId)||""),C=(o==null?void 0:o.language)||"",g=(c==null?void 0:c.getAttribute("nosto-language"))!==C||(c==null?void 0:c.getAttribute("nosto-market-id"))!==N;if(!c||g){d&&u(!1);const O=document.querySelector("#nosto-sandbox");(M=c==null?void 0:c.parentNode)==null||M.removeChild(c),(F=O==null?void 0:O.parentNode)==null||F.removeChild(O);const ie=`/script/shopify/market/nosto.js?merchant=${s}&market=${N}&locale=${C.toLowerCase()}`;h(ie,{"nosto-language":C,"nosto-market-id":N})}}if(window.nostojs||(window.nostojs=c=>{(window.nostojs.q=window.nostojs.q||[]).push(c)},window.nostojs(c=>c.setAutoLoad(!1))),!i){window.nosto?f():window.nostojs(f);return}if(!ne()&&!o){const c=`/include/${s}`;h(c)}o&&P()},[o==null?void 0:o.marketId,o==null?void 0:o.language]),{clientScriptLoaded:d}}function re(e){const{account:t,multiCurrency:n=!1,children:s,recommendationComponent:o}=e,i=n?e.currentVariation:"";if(o&&!a.isValidElement(o))throw new Error("The recommendationComponent prop must be a valid React element. Please provide a valid React element.");const d=o?"JSON_ORIGINAL":"HTML",{clientScriptLoaded:u}=se(e);return u&&window.nostojs(f=>{f.defaultSession().setVariation(i).setResponseMode(d)}),p.jsx(j.Provider,{value:{account:t,clientScriptLoaded:u,currentVariation:i,responseMode:d,recommendationComponent:o},children:s})}function $({query:e,placements:t}){const{renderCampaigns:n}=m();l(async s=>{const o=await s.defaultSession().viewSearch(e).setPlacements(t||s.placements.getPlacements()).load();n(o)},[e])}function ce(e){return $(e),null}function b({cart:e,customer:t}={}){const{clientScriptLoaded:n}=y();_(()=>{const s=e?w(e):void 0,o=t?w(t):void 0;n&&window.nostojs(i=>{i.defaultSession().setCart(s).setCustomer(o).viewOther().load({skipPageViews:!0})})},[n,e,t])}function ae(e){return b(e),null}r.Nosto404=G,r.NostoCategory=J,r.NostoCheckout=Y,r.NostoContext=j,r.NostoHome=Z,r.NostoOrder=X,r.NostoOther=x,r.NostoPlacement=ee,r.NostoProduct=te,r.NostoProvider=re,r.NostoSearch=ce,r.NostoSession=ae,r.useNosto404=A,r.useNostoCategory=D,r.useNostoCheckout=k,r.useNostoContext=y,r.useNostoHome=I,r.useNostoOrder=q,r.useNostoOther=H,r.useNostoProduct=V,r.useNostoSearch=$,r.useNostoSession=b,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nosto/nosto-react",
3
3
  "description": "Component library to simply implementing Nosto on React.",
4
- "version": "2.2.0",
4
+ "version": "2.2.2",
5
5
  "author": "Mridang Agarwalla, Dominik Gilg",
6
6
  "license": "ISC",
7
7
  "repository": {
@@ -43,8 +43,8 @@
43
43
  "eslint-plugin-promise": "^6.1.1",
44
44
  "eslint-plugin-react": "^7.33.2",
45
45
  "prettier": "^2.0.5",
46
- "react": "*",
47
- "react-dom": "*",
46
+ "react": "^18.3.1",
47
+ "react-dom": "^18.3.1",
48
48
  "react-router": "^6.25.1",
49
49
  "react-router-dom": "^6.25.1",
50
50
  "rimraf": "^3.0.2",
@@ -1,9 +1,4 @@
1
- import { useNostoApi, useRenderCampaigns } from "../hooks"
2
-
3
- /**
4
- * @group Components
5
- */
6
- export type Nosto404Props = { placements?: string[] }
1
+ import { Nosto404Props, useNosto404 } from "../hooks/useNosto404"
7
2
 
8
3
  /**
9
4
  * You can personalise your cart and checkout pages by using the `Nosto404` component.
@@ -25,25 +20,7 @@ export type Nosto404Props = { placements?: string[] }
25
20
  *
26
21
  * @group Components
27
22
  */
28
- export default function Nosto404(props: Nosto404Props) {
23
+ export function Nosto404(props: Nosto404Props) {
29
24
  useNosto404(props)
30
25
  return null
31
26
  }
32
-
33
- /**
34
- * You can personalise your cart and checkout pages by using the `useNosto404` hook.
35
- *
36
- * @group Hooks
37
- */
38
- export function useNosto404(props?: Nosto404Props) {
39
- const { renderCampaigns } = useRenderCampaigns()
40
-
41
- useNostoApi(
42
- async (api) => {
43
- const data = await api.defaultSession()
44
- .viewNotFound()
45
- .setPlacements(props?.placements || api.placements.getPlacements())
46
- .load()
47
- renderCampaigns(data)
48
- })
49
- }
@@ -1,12 +1,4 @@
1
- import { useNostoApi, useRenderCampaigns } from "../hooks"
2
-
3
- /**
4
- * @group Components
5
- */
6
- export type NostoCategoryProps = {
7
- category: string
8
- placements?: string[]
9
- }
1
+ import { NostoCategoryProps, useNostoCategory } from "../hooks/useNostoCategory"
10
2
 
11
3
  /**
12
4
  * You can personalise your category and collection pages by using the NostoCategory component.
@@ -30,27 +22,7 @@ export type NostoCategoryProps = {
30
22
  *
31
23
  * @group Components
32
24
  */
33
- export default function NostoCategory(props: NostoCategoryProps) {
25
+ export function NostoCategory(props: NostoCategoryProps) {
34
26
  useNostoCategory(props)
35
27
  return null
36
28
  }
37
-
38
- /**
39
- * You can personalise your category and collection pages by using the useNostoCategory hook.
40
- *
41
- * @group Hooks
42
- */
43
- export function useNostoCategory({ category, placements }: NostoCategoryProps) {
44
- const { renderCampaigns } = useRenderCampaigns()
45
-
46
- useNostoApi(
47
- async (api) => {
48
- const data = await api.defaultSession()
49
- .viewCategory(category)
50
- .setPlacements(placements || api.placements.getPlacements())
51
- .load()
52
- renderCampaigns(data)
53
- },
54
- [category]
55
- )
56
- }
@@ -1,9 +1,4 @@
1
- import { useNostoApi, useRenderCampaigns } from "../hooks"
2
-
3
- /**
4
- * @group Components
5
- */
6
- export type NostoCheckoutProps = { placements?: string[] }
1
+ import { NostoCheckoutProps, useNostoCheckout } from "../hooks/useNostoCheckout"
7
2
 
8
3
  /**
9
4
  * You can personalise your cart and checkout pages by using the NostoCheckout component.
@@ -24,25 +19,7 @@ export type NostoCheckoutProps = { placements?: string[] }
24
19
  *
25
20
  * @group Components
26
21
  */
27
- export default function NostoCheckout(props: NostoCheckoutProps) {
22
+ export function NostoCheckout(props: NostoCheckoutProps) {
28
23
  useNostoCheckout(props)
29
24
  return null
30
25
  }
31
-
32
- /**
33
- * You can personalise your cart and checkout pages by using the useNostoCheckout hook.
34
- *
35
- * @group Hooks
36
- */
37
- export function useNostoCheckout(props?: NostoCheckoutProps) {
38
- const { renderCampaigns } = useRenderCampaigns()
39
-
40
- useNostoApi(
41
- async (api) => {
42
- const data = await api.defaultSession()
43
- .viewCart()
44
- .setPlacements(props?.placements || api.placements.getPlacements())
45
- .load()
46
- renderCampaigns(data)
47
- })
48
- }
@@ -1,9 +1,4 @@
1
- import { useRenderCampaigns, useNostoApi } from "../hooks"
2
-
3
- /**
4
- * @group Components
5
- */
6
- export type NostoHomeProps = { placements?: string[] }
1
+ import { NostoHomeProps, useNostoHome } from "../hooks/useNostoHome"
7
2
 
8
3
  /**
9
4
  * The `NostoHome` component must be used to personalise the home page. The component does not require any props.
@@ -28,26 +23,7 @@ export type NostoHomeProps = { placements?: string[] }
28
23
  *
29
24
  * @group Components
30
25
  */
31
- export default function NostoHome(props: NostoHomeProps) {
26
+ export function NostoHome(props: NostoHomeProps) {
32
27
  useNostoHome(props)
33
28
  return null
34
29
  }
35
-
36
- /**
37
- * You can personalise your home page by using the useNostoHome hook.
38
- *
39
- * @group Hooks
40
- */
41
- export function useNostoHome(props?: NostoHomeProps) {
42
- const { renderCampaigns } = useRenderCampaigns()
43
-
44
- useNostoApi(
45
- async (api) => {
46
- const data = await api.defaultSession()
47
- .viewFrontPage()
48
- .setPlacements(props?.placements || api.placements.getPlacements())
49
- .load()
50
- renderCampaigns(data)
51
- }
52
- )
53
- }
@@ -1,14 +1,4 @@
1
- import { Order } from "../types"
2
- import { useRenderCampaigns, useNostoApi } from "../hooks"
3
- import { snakeize } from "../utils/snakeize"
4
-
5
- /**
6
- * @group Components
7
- */
8
- export type NostoOrderProps = {
9
- order: Order
10
- placements?: string[]
11
- }
1
+ import { NostoOrderProps, useNostoOrder } from "../hooks/useNostoOrder"
12
2
 
13
3
  /**
14
4
  * You can personalise your order-confirmation/thank-you page by using the `NostoOrder` component.
@@ -29,28 +19,7 @@ export type NostoOrderProps = {
29
19
  *
30
20
  * @group Components
31
21
  */
32
- export default function NostoOrder(props: NostoOrderProps) {
22
+ export function NostoOrder(props: NostoOrderProps) {
33
23
  useNostoOrder(props)
34
24
  return null
35
25
  }
36
-
37
- /**
38
- * You can personalise your order-confirmation/thank-you page by using the `useNostoOrder` hook.
39
- *
40
- * @group Hooks
41
- */
42
- export function useNostoOrder({ order, placements }: NostoOrderProps) {
43
- const { renderCampaigns } = useRenderCampaigns()
44
-
45
- useNostoApi(
46
- async (api) => {
47
- const data = await api.defaultSession()
48
- .addOrder(snakeize(order))
49
- .setPlacements(placements || api.placements.getPlacements())
50
- .load()
51
- renderCampaigns(data)
52
- },
53
- [order],
54
- { deep: true }
55
- )
56
- }
@@ -1,9 +1,4 @@
1
- import { useRenderCampaigns, useNostoApi } from "../hooks"
2
-
3
- /**
4
- * @group Components
5
- */
6
- export type NostoOtherProps = { placements?: string[] }
1
+ import { NostoOtherProps, useNostoOther } from "../hooks/useNostoOther"
7
2
 
8
3
  /**
9
4
  * You can personalise your miscellaneous pages by using the NostoOther component.
@@ -24,25 +19,7 @@ export type NostoOtherProps = { placements?: string[] }
24
19
  *
25
20
  * @group Components
26
21
  */
27
- export default function NostoOther(props: NostoOtherProps) {
22
+ export function NostoOther(props: NostoOtherProps) {
28
23
  useNostoOther(props)
29
24
  return null
30
25
  }
31
-
32
- /**
33
- * You can personalise your miscellaneous pages by using the useNostoOther hook.
34
- *
35
- * @group Hooks
36
- */
37
- export function useNostoOther(props?: NostoOtherProps) {
38
- const { renderCampaigns } = useRenderCampaigns()
39
-
40
- useNostoApi(
41
- async (api) => {
42
- const data = await api.defaultSession()
43
- .viewOther()
44
- .setPlacements(props?.placements || api.placements.getPlacements())
45
- .load()
46
- renderCampaigns(data)
47
- })
48
- }
@@ -16,6 +16,6 @@ export type NostoPlacementProps = { id: string; pageType?: string }
16
16
  *
17
17
  * @group Components
18
18
  */
19
- export default function NostoPlacement({ id, pageType }: NostoPlacementProps) {
19
+ export function NostoPlacement({ id, pageType }: NostoPlacementProps) {
20
20
  return <div className="nosto_element" id={id} key={id + (pageType || "")} />
21
21
  }
@@ -1,14 +1,4 @@
1
- import { useRenderCampaigns, useNostoApi } from "../hooks"
2
- import { Product } from "../types"
3
-
4
- /**
5
- * @group Components
6
- */
7
- export type NostoProductProps = {
8
- product: string
9
- tagging?: Product
10
- placements?: string[]
11
- }
1
+ import { NostoProductProps, useNostoProduct } from "../hooks/useNostoProduct"
12
2
 
13
3
  /**
14
4
  * The NostoProduct component must be used to personalise the product page.
@@ -34,27 +24,7 @@ export type NostoProductProps = {
34
24
  *
35
25
  * @group Components
36
26
  */
37
- export default function NostoProduct(props: NostoProductProps) {
27
+ export function NostoProduct(props: NostoProductProps) {
38
28
  useNostoProduct(props)
39
29
  return null
40
30
  }
41
-
42
- /**
43
- * You can personalise your product pages by using the useNostoProduct hook.
44
- *
45
- * @group Hooks
46
- */
47
- export function useNostoProduct({ product, tagging, placements }: NostoProductProps) {
48
- const { renderCampaigns } = useRenderCampaigns()
49
-
50
- useNostoApi(
51
- async (api) => {
52
- const data = await api.defaultSession()
53
- .viewProduct(tagging ?? product)
54
- .setPlacements(placements || api.placements.getPlacements())
55
- .load()
56
- renderCampaigns(data)
57
- },
58
- [product, tagging?.selected_sku_id]
59
- )
60
- }
@@ -1,8 +1,8 @@
1
1
  import { isValidElement } from "react"
2
2
  import { NostoContext, RecommendationComponent } from "../context"
3
- import { useLoadClientScript } from "../hooks"
4
- import type { ReactElement } from "react"
3
+ import type { ReactNode } from "react"
5
4
  import { ScriptLoadOptions } from "../hooks/scriptLoader"
5
+ import { useLoadClientScript } from "../hooks/useLoadClientScript"
6
6
 
7
7
  /**
8
8
  * @group Components
@@ -23,7 +23,7 @@ export interface NostoProviderProps {
23
23
  /**
24
24
  * children
25
25
  */
26
- children: ReactElement | ReactElement[]
26
+ children: ReactNode | ReactNode[]
27
27
  /**
28
28
  * Indicates if merchant uses multiple currencies
29
29
  */
@@ -70,13 +70,8 @@ export interface NostoProviderProps {
70
70
  *
71
71
  * @group Components
72
72
  */
73
- export default function NostoProvider(props: NostoProviderProps) {
74
- const {
75
- account,
76
- multiCurrency = false,
77
- children,
78
- recommendationComponent,
79
- } = props
73
+ export function NostoProvider(props: NostoProviderProps) {
74
+ const { account, multiCurrency = false, children, recommendationComponent } = props
80
75
 
81
76
  // Pass currentVariation as empty string if multiCurrency is disabled
82
77
  const currentVariation = multiCurrency ? props.currentVariation : ""
@@ -92,6 +87,12 @@ export default function NostoProvider(props: NostoProviderProps) {
92
87
 
93
88
  const { clientScriptLoaded } = useLoadClientScript(props)
94
89
 
90
+ if (clientScriptLoaded) {
91
+ window.nostojs(api => {
92
+ api.defaultSession().setVariation(currentVariation!).setResponseMode(responseMode)
93
+ })
94
+ }
95
+
95
96
  return (
96
97
  <NostoContext.Provider
97
98
  value={{
@@ -1,12 +1,4 @@
1
- import { useRenderCampaigns, useNostoApi } from "../hooks"
2
-
3
- /**
4
- * @group Components
5
- */
6
- export type NostoSearchProps = {
7
- query: string
8
- placements?: string[]
9
- }
1
+ import { NostoSearchProps, useNostoSearch } from "../hooks/useNostoSearch"
10
2
 
11
3
  /**
12
4
  * You can personalise your search pages by using the NostoSearch component.
@@ -31,27 +23,7 @@ export type NostoSearchProps = {
31
23
  *
32
24
  * @group Components
33
25
  */
34
- export default function NostoSearch(props: NostoSearchProps) {
26
+ export function NostoSearch(props: NostoSearchProps) {
35
27
  useNostoSearch(props)
36
28
  return null
37
29
  }
38
-
39
- /**
40
- * You can personalise your search pages by using the useNostoSearch hook.
41
- *
42
- * @group Hooks
43
- */
44
- export function useNostoSearch({ query, placements }: NostoSearchProps) {
45
- const { renderCampaigns } = useRenderCampaigns()
46
-
47
- useNostoApi(
48
- async (api) => {
49
- const data = await api.defaultSession()
50
- .viewSearch(query)
51
- .setPlacements(placements || api.placements.getPlacements())
52
- .load()
53
- renderCampaigns(data)
54
- },
55
- [query]
56
- )
57
- }
@@ -1,18 +1,4 @@
1
- import { useNostoContext, useDeepCompareEffect } from "../hooks"
2
- import { Cart as CartSnakeCase, Customer as CustomerSnakeCase } from "../types"
3
- import { snakeize } from "../utils/snakeize"
4
- import { ToCamelCase } from "../utils/types"
5
-
6
- type Cart = CartSnakeCase | ToCamelCase<CartSnakeCase>
7
- type Customer = CustomerSnakeCase | ToCamelCase<CustomerSnakeCase>
8
-
9
- /**
10
- * @group Components
11
- */
12
- export type NostoSessionProps = {
13
- cart?: Cart
14
- customer?: Customer
15
- }
1
+ import { NostoSessionProps, useNostoSession } from "../hooks/useNostoSession"
16
2
 
17
3
  /**
18
4
  * Nosto React requires that you pass it the details of current cart contents and the details of the currently logged-in customer, if any, on every route change.
@@ -24,34 +10,7 @@ export type NostoSessionProps = {
24
10
  *
25
11
  * @group Components
26
12
  */
27
- export default function NostoSession(props?: NostoSessionProps) {
13
+ export function NostoSession(props?: NostoSessionProps) {
28
14
  useNostoSession(props)
29
15
  return null
30
16
  }
31
-
32
- /**
33
- * Nosto React requires that you pass it the details of current cart contents and the details of the currently logged-in customer, if any, on every route change.
34
- *
35
- * @group Hooks
36
- */
37
- export function useNostoSession({ cart, customer }: NostoSessionProps = {}) {
38
- const { clientScriptLoaded } = useNostoContext()
39
-
40
- useDeepCompareEffect(() => {
41
- const currentCart = cart ? snakeize(cart) : undefined
42
- const currentCustomer = customer ? snakeize(customer) : undefined
43
-
44
- if (clientScriptLoaded) {
45
- window.nostojs(api => {
46
- api
47
- .defaultSession()
48
- .setResponseMode("HTML")
49
- .setCart(currentCart)
50
- .setCustomer(currentCustomer)
51
- .viewOther()
52
- .load({ skipPageViews: true })
53
- })
54
- }
55
- }, [clientScriptLoaded, cart, customer])
56
-
57
- }
@@ -1,3 +1,3 @@
1
1
  export function isNostoLoaded() {
2
- return typeof window.nosto !== "undefined"
3
- }
2
+ return typeof window.nosto !== "undefined"
3
+ }
package/src/context.ts CHANGED
@@ -28,4 +28,3 @@ export const NostoContext = createContext<NostoContextType>({
28
28
  responseMode: "HTML",
29
29
  clientScriptLoaded: false
30
30
  })
31
-
@@ -8,9 +8,9 @@ export default function scriptLoader(scriptSrc: string, options?: ScriptLoadOpti
8
8
  script.onerror = () => reject()
9
9
  Object.entries(options?.attributes ?? {}).forEach(([k, v]) => script.setAttribute(k, v))
10
10
  if (options?.position === "head") {
11
- document.head.appendChild(script)
11
+ document.head.appendChild(script)
12
12
  } else {
13
- document.body.appendChild(script)
13
+ document.body.appendChild(script)
14
14
  }
15
15
  })
16
16
  }
@@ -26,5 +26,5 @@ export type ScriptLoadOptions = {
26
26
  /**
27
27
  * Indicates the attributes of the script element
28
28
  */
29
- attributes?: Record<string, string>
30
- }
29
+ attributes?: Record<string, string>
30
+ }
@@ -1,16 +1,13 @@
1
- import { useEffect, useRef, useMemo } from "react"
1
+ import { useEffect, useRef, useMemo, type EffectCallback, type DependencyList } from "react"
2
2
  import { deepCompare } from "../utils/compare"
3
3
 
4
- export function useDeepCompareEffect(
5
- callback: Parameters<typeof useEffect>[0],
6
- dependencies: Parameters<typeof useEffect>[1]
7
- ): ReturnType<typeof useEffect> {
4
+ export function useDeepCompareEffect(callback: EffectCallback, dependencies: DependencyList) {
8
5
  return useEffect(callback, useDeepCompareMemoize(dependencies))
9
6
  }
10
7
 
11
8
  function useDeepCompareMemoize<T>(value: T) {
12
- const ref = useRef<T>(value);
13
- const signalRef = useRef<number>(0)
9
+ const ref = useRef<T>(value)
10
+ const signalRef = useRef(0)
14
11
 
15
12
  if (!deepCompare(value, ref.current)) {
16
13
  ref.current = value
@@ -7,7 +7,13 @@ import scriptLoaderFn from "./scriptLoader"
7
7
  type NostoScriptProps = Pick<NostoProviderProps, "account" | "host" | "shopifyMarkets" | "loadScript" | "scriptLoader">
8
8
 
9
9
  export function useLoadClientScript(props: NostoScriptProps) {
10
- const { host = "connect.nosto.com", scriptLoader = scriptLoaderFn, account, shopifyMarkets, loadScript = true } = props
10
+ const {
11
+ host = "connect.nosto.com",
12
+ scriptLoader = scriptLoaderFn,
13
+ account,
14
+ shopifyMarkets,
15
+ loadScript = true
16
+ } = props
11
17
  const [clientScriptLoaded, setClientScriptLoaded] = useState(false)
12
18
 
13
19
  useEffect(() => {
@@ -49,8 +55,7 @@ export function useLoadClientScript(props: NostoScriptProps) {
49
55
  existingScript?.parentNode?.removeChild(existingScript)
50
56
  nostoSandbox?.parentNode?.removeChild(nostoSandbox)
51
57
 
52
- const urlPartial =
53
- `/script/shopify/market/nosto.js?merchant=${account}&market=${marketId}&locale=${language.toLowerCase()}`
58
+ const urlPartial = `/script/shopify/market/nosto.js?merchant=${account}&market=${marketId}&locale=${language.toLowerCase()}`
54
59
  injectScriptElement(urlPartial, { "nosto-language": language, "nosto-market-id": marketId })
55
60
  }
56
61
  }
@@ -81,4 +86,4 @@ export function useLoadClientScript(props: NostoScriptProps) {
81
86
  }, [shopifyMarkets?.marketId, shopifyMarkets?.language])
82
87
 
83
88
  return { clientScriptLoaded }
84
- }
89
+ }