@storyblok/react 1.0.1 → 1.0.4

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.
package/README.md CHANGED
@@ -82,16 +82,16 @@ That's it! All the features are enabled for you: the _Api Client_ for interactin
82
82
 
83
83
  `@storyblok/react` does three actions when you initialize it:
84
84
 
85
- - Provides a `useStoryblokApi` object in your app, which is an instance of [storyblok-js-client](https://github.com/storyblok/storyblok-js-client).
85
+ - Provides a `getStoryblokApi` object in your app, which is an instance of [storyblok-js-client](https://github.com/storyblok/storyblok-js-client).
86
86
  - Loads [Storyblok Bridge](https://www.storyblok.com/docs/Guides/storyblok-latest-js?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-react) for real-time visual updates.
87
87
  - Provides a `storyblokEditable` function to link editable components to the Storyblok Visual Editor.
88
88
 
89
89
  #### 1. Fetching Content
90
90
 
91
- Inject `useStoryblokApi`:
91
+ Inject `getStoryblokApi`:
92
92
 
93
93
  ```js
94
- import { storyblokInit, apiPlugin, useStoryblokApi } from "@storyblok/react";
94
+ import { storyblokInit, apiPlugin, getStoryblokApi } from "@storyblok/react";
95
95
 
96
96
  storyblokInit({
97
97
  accessToken: "YOUR_ACCESS_TOKEN",
@@ -106,7 +106,7 @@ storyblokInit({
106
106
  },
107
107
  });
108
108
 
109
- const storyblokApi = useStoryblokApi()
109
+ const storyblokApi = getStoryblokApi()
110
110
  const { data } = await storyblokApi.get("cdn/stories", { version: "draft" });
111
111
  ```
112
112
 
@@ -166,7 +166,7 @@ Where `blok` is the actual blok data coming from [Storblok's Content Delivery AP
166
166
  As an example, you can check in our [Next.js example demo](https://stackblitz.com/edit/react-next-sdk-demo?file=src%2Fpages%2Findex.jsx) how we use APIs provided from React SDK to combine with Next.js projects.
167
167
 
168
168
  ```js
169
- import { useStoryblokState, useStoryblokApi, StoryblokComponent } from "@storyblok/react";
169
+ import { useStoryblokState, getStoryblokApi, StoryblokComponent } from "@storyblok/react";
170
170
 
171
171
  export default function Home({ story: initialStory }) {
172
172
  const story = useStoryblokState(initialStory);
@@ -180,7 +180,7 @@ export default function Home({ story: initialStory }) {
180
180
 
181
181
 
182
182
  export async function getStaticProps({ preview = false }) {
183
- const storyblokApi = useStoryblokApi()
183
+ const storyblokApi = getStoryblokApi()
184
184
  let { data } = await storyblokApi.get(`cdn/stories/react`, {
185
185
  version: "draft"
186
186
  });
@@ -204,10 +204,10 @@ You can **choose the features to use** when you initialize the plugin. In that w
204
204
 
205
205
  #### Storyblok API
206
206
 
207
- You can use an `apiOptions` object. This is passed down to the (storyblok-js-client config object](https://github.com/storyblok/storyblok-js-client#class-storyblok):
207
+ You can use an `apiOptions` object. This is passed down to the [storyblok-js-client config object](https://github.com/storyblok/storyblok-js-client#class-storyblok):
208
208
 
209
209
  ```js
210
- const { useStoryblokApi } = storyblokInit({
210
+ storyblokInit({
211
211
  accessToken: "YOUR_ACCESS_TOKEN",
212
212
  apiOptions: {
213
213
  // storyblok-js-client config object
@@ -231,7 +231,7 @@ storyblokInit({});
231
231
 
232
232
  #### Storyblok Bridge
233
233
 
234
- If you don't use `useSbBridge`, you have still access to the raw `window.StoryblokBridge`:
234
+ If you don't use `useStoryblokBridge`, you still have access to the raw `window.StoryblokBridge`:
235
235
 
236
236
  ```js
237
237
  const sbBridge = new window.StoryblokBridge(options);
@@ -1,5 +1,5 @@
1
- var ne=Object.defineProperty;var v=Object.getOwnPropertySymbols;var I=Object.prototype.hasOwnProperty,x=Object.prototype.propertyIsEnumerable;var M=(l,h,p)=>h in l?ne(l,h,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[h]=p,N=(l,h)=>{for(var p in h||(h={}))I.call(h,p)&&M(l,p,h[p]);if(v)for(var p of v(h))x.call(h,p)&&M(l,p,h[p]);return l};var q=(l,h)=>{var p={};for(var f in l)I.call(l,f)&&h.indexOf(f)<0&&(p[f]=l[f]);if(l!=null&&v)for(var f of v(l))h.indexOf(f)<0&&x.call(l,f)&&(p[f]=l[f]);return p};(function(l,h){typeof exports=="object"&&typeof module!="undefined"?h(exports,require("react"),require("axios")):typeof define=="function"&&define.amd?define(["exports","react","axios"],h):(l=typeof globalThis!="undefined"?globalThis:l||self,h(l.storyblokReact={},l.React,l.t))})(this,function(l,h,p){"use strict";function f(s){return s&&typeof s=="object"&&"default"in s?s:{default:s}}var E=f(h),B=f(p),L=Object.defineProperty,U=Object.defineProperties,V=Object.getOwnPropertyDescriptors,R=Object.getOwnPropertySymbols,D=Object.prototype.hasOwnProperty,J=Object.prototype.propertyIsEnumerable,O=(s,e,t)=>e in s?L(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,g=(s,e)=>{for(var t in e||(e={}))D.call(e,t)&&O(s,t,e[t]);if(R)for(var t of R(e))J.call(e,t)&&O(s,t,e[t]);return s},_=(s,e)=>U(s,V(e));let P=!1;const j=[],Y=s=>new Promise((e,t)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=o=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}P?o():j.push(o)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=s,r.id="storyblok-javascript-bridge",r.onerror=o=>t(o),r.onload=o=>{j.forEach(n=>n()),P=!0,e(o)},document.getElementsByTagName("head")[0].appendChild(r)});/*!
1
+ var ne=Object.defineProperty;var v=Object.getOwnPropertySymbols;var x=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable;var M=(l,h,p)=>h in l?ne(l,h,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[h]=p,q=(l,h)=>{for(var p in h||(h={}))x.call(h,p)&&M(l,p,h[p]);if(v)for(var p of v(h))N.call(h,p)&&M(l,p,h[p]);return l};var B=(l,h)=>{var p={};for(var f in l)x.call(l,f)&&h.indexOf(f)<0&&(p[f]=l[f]);if(l!=null&&v)for(var f of v(l))h.indexOf(f)<0&&N.call(l,f)&&(p[f]=l[f]);return p};(function(l,h){typeof exports=="object"&&typeof module!="undefined"?h(exports,require("react"),require("axios")):typeof define=="function"&&define.amd?define(["exports","react","axios"],h):(l=typeof globalThis!="undefined"?globalThis:l||self,h(l.storyblokReact={},l.React,l.t))})(this,function(l,h,p){"use strict";function f(s){return s&&typeof s=="object"&&"default"in s?s:{default:s}}var E=f(h),L=f(p),D=Object.defineProperty,U=Object.defineProperties,V=Object.getOwnPropertyDescriptors,P=Object.getOwnPropertySymbols,J=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,R=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,g=(s,e)=>{for(var t in e||(e={}))J.call(e,t)&&R(s,t,e[t]);if(P)for(var t of P(e))Y.call(e,t)&&R(s,t,e[t]);return s},_=(s,e)=>U(s,V(e));let O=!1;const j=[],z=s=>new Promise((e,t)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=o=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}O?o():j.push(o)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=s,r.id="storyblok-javascript-bridge",r.onerror=o=>t(o),r.onload=o=>{j.forEach(n=>n()),O=!0,e(o)},document.getElementsByTagName("head")[0].appendChild(r)});/*!
2
2
  * storyblok-js-client v0.0.0-development
3
3
  * Universal JavaScript SDK for Storyblok's API
4
4
  * (c) 2020-2022 Stobylok Team
5
- */function C(s){return typeof s=="number"&&s==s&&s!==1/0&&s!==-1/0}function A(s,e,t){if(!C(e))throw new TypeError("Expected `limit` to be a finite number");if(!C(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],o=[],n=0,i=function(){n++;var u=setTimeout(function(){n--,r.length>0&&i(),o=o.filter(function(d){return d!==u})},t);o.indexOf(u)<0&&o.push(u);var c=r.shift();c.resolve(s.apply(c.self,c.args))},a=function(){var u=arguments,c=this;return new Promise(function(d,k){r.push({resolve:d,reject:k,args:u,self:c}),n<e&&i()})};return a.abort=function(){o.forEach(clearTimeout),o=[],r.forEach(function(u){u.reject(new throttle.AbortError)}),r.length=0},a}A.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const z=function(s,e){if(!s)return null;let t={};for(let r in s){let o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t};var H={nodes:{horizontal_rule:s=>({singleTag:"hr"}),blockquote:s=>({tag:"blockquote"}),bullet_list:s=>({tag:"ul"}),code_block:s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),hard_break:s=>({singleTag:"br"}),heading:s=>({tag:"h"+s.attrs.level}),image:s=>({singleTag:[{tag:"img",attrs:z(s.attrs,["src","alt","title"])}]}),list_item:s=>({tag:"li"}),ordered_list:s=>({tag:"ol"}),paragraph:s=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(s){const e=g({},s.attrs),{linktype:t="url"}=s.attrs;return t==="email"&&(e.href="mailto:"+e.href),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:s=>({tag:[{tag:"span",attrs:s.attrs}]})}};class F{constructor(e){e||(e=H),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(function(o){const n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},i=/[&<>"']/g,a=RegExp(i.source);return o&&a.test(o)?o.replace(i,u=>n[u]):o}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let o="<"+r.tag;if(r.attrs)for(let n in r.attrs){let i=r.attrs[n];i!==null&&(o+=` ${n}="${i}"`)}return`${o}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const G=(s=0,e=s)=>{const t=Math.abs(e-s)||0,r=s<e?1:-1;return((o=0,n)=>[...Array(o)].map(n))(t,(o,n)=>n*r+s)},w=(s,e,t)=>{const r=[];for(const o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;const n=s[o],i=t?"":encodeURIComponent(o);let a;a=typeof n=="object"?w(n,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")};let b={},y={};class Q{constructor(e,t){if(!t){let n=e.region?"-"+e.region:"",i=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},e.headers),o=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,o=3),e.rateLimit!==void 0&&(o=e.rateLimit),this.richTextResolver=new F(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=A(this.throttledRequest,o,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=B.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(n=>e.responseInterceptor(n))}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=y[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,o){const n=this.factoryParamOptions(e,((i={},a=25,u=1)=>_(g({},i),{per_page:a,page:u}))(t,r,o));return this.cacheResponse(e,n)}get(e,t){let r="/"+e;const o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o)}async getAll(e,t={},r){const o=t.per_page||25,n="/"+e,i=n.split("/");r=r||i[i.length-1];const a=await this.makeRequest(n,t,o,1),u=Math.ceil(a.total/o);return((c=[],d)=>c.map(d).reduce((k,se)=>[...k,...se],[]))([a,...await(async(c=[],d)=>Promise.all(c.map(d)))(G(1,u),async c=>this.makeRequest(n,t,o,c+1))],c=>Object.values(c.data[r]))}post(e,t){let r="/"+e;return this.throttle("post",r,t)}put(e,t){let r="/"+e;return this.throttle("put",r,t)}delete(e,t){let r="/"+e;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get("cdn/stories/"+e,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.indexOf(e.component+"."+t)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t].constructor===Array){let o=[];e[t].forEach(n=>{this.relations[n]&&o.push(this._cleanCopy(this.relations[n]))}),e[t]=o}}}iterateTree(e,t){let r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(let n in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,n,t),this._insertLinks(o,n)),r(o[n])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const o=e.link_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const u=Math.min(o,a+i);n.push(e.link_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.links;r.forEach(o=>{this.links[o.uuid]=_(g({},o),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const u=Math.min(o,a+i);n.push(e.rel_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.rels;r.forEach(o=>{this.relations[o.uuid]=_(g({},o),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&await this.resolveLinks(e,t);for(const o in this.relations)this.iterateTree(this.relations[o],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(o=>{this.iterateTree(o,r)})}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(o,n)=>{let i=w({url:e,params:t}),a=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const c=await a.get(i);if(c)return o(c)}try{let c=await this.throttle("get",e,{params:t,paramsSerializer:k=>w(k)}),d={data:c.data,headers:c.headers};if(c.headers["per-page"]&&(d=Object.assign({},d,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return n(c);(d.data.story||d.data.stories)&&await this.resolveStories(d.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,d),d.data.cv&&(t.version=="draft"&&y[t.token]!=d.data.cv&&this.flushCache(),y[t.token]=d.data.cv),o(d)}catch(c){if(c.response&&c.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(u=1e3*r,new Promise(d=>setTimeout(d,u))),this.cacheResponse(e,t,r).then(o).catch(n);n(c)}var u})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get:e=>b[e],getAll:()=>b,set(e,t){b[e]=t},flush(){b={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}async flushCache(){return await this.cacheProvider().flush(),this}}var W=(s={})=>{const{apiOptions:e}=s;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new Q(e)}},X=s=>{if(typeof s!="object"||typeof s._editable=="undefined")return{};const e=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};const T=(s,e,t={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],o=>{o.action=="input"&&o.story.id===s?e(o.story):window.location.reload()})})}},Z=(s={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:o={}}=s;o.accessToken=o.accessToken||t;const n={bridge:e,apiOptions:o};let i={};return r.forEach(a=>{i=g(g({},i),a(n))}),e!==!1&&Y("https://app.storyblok.com/f/storyblok-v2-latest.js"),i},K=t=>{var r=t,{blok:s}=r,e=q(r,["blok"]);if(!s)return console.error("Please provide a 'blok' property to the StoryblokComponent"),E.default.createElement("div",null,"Please provide a blok property to the StoryblokComponent");const o=$(s.component);return o?E.default.createElement(o,N({blok:s},e)):""},ee=(s,e={},t={})=>{let[r,o]=h.useState({});return m?(T(r.id,n=>o(n),t),h.useEffect(async()=>{const{data:n}=await m.get(`cdn/stories/${s}`,e);o(n.story)},[]),r):(console.error("You can't use useStoryblok if you're not loading apiPlugin."),null)},te=(s={},e={})=>{let[t,r]=h.useState(s);return T(t.id,o=>r(o),e),h.useEffect(()=>{r(s)},[s]),t};let m=null;const re=()=>(m||console.error("You can't use useStoryblokApi if you're not loading apiPlugin."),m);let S={};const $=s=>S[s]?S[s]:(console.error(`Component ${s} doesn't exist.`),!1),oe=(s={})=>{const{storyblokApi:e}=Z(s);m=e,S=s.components};l.StoryblokComponent=K,l.apiPlugin=W,l.getComponent=$,l.storyblokEditable=X,l.storyblokInit=oe,l.useStoryblok=ee,l.useStoryblokApi=re,l.useStoryblokBridge=T,l.useStoryblokState=te,Object.defineProperties(l,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
5
+ */function C(s){return typeof s=="number"&&s==s&&s!==1/0&&s!==-1/0}function A(s,e,t){if(!C(e))throw new TypeError("Expected `limit` to be a finite number");if(!C(t))throw new TypeError("Expected `interval` to be a finite number");var r=[],o=[],n=0,i=function(){n++;var u=setTimeout(function(){n--,r.length>0&&i(),o=o.filter(function(d){return d!==u})},t);o.indexOf(u)<0&&o.push(u);var c=r.shift();c.resolve(s.apply(c.self,c.args))},a=function(){var u=arguments,c=this;return new Promise(function(d,k){r.push({resolve:d,reject:k,args:u,self:c}),n<e&&i()})};return a.abort=function(){o.forEach(clearTimeout),o=[],r.forEach(function(u){u.reject(new throttle.AbortError)}),r.length=0},a}A.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const H=function(s,e){if(!s)return null;let t={};for(let r in s){let o=s[r];e.indexOf(r)>-1&&o!==null&&(t[r]=o)}return t};var F={nodes:{horizontal_rule:s=>({singleTag:"hr"}),blockquote:s=>({tag:"blockquote"}),bullet_list:s=>({tag:"ul"}),code_block:s=>({tag:["pre",{tag:"code",attrs:s.attrs}]}),hard_break:s=>({singleTag:"br"}),heading:s=>({tag:"h"+s.attrs.level}),image:s=>({singleTag:[{tag:"img",attrs:H(s.attrs,["src","alt","title"])}]}),list_item:s=>({tag:"li"}),ordered_list:s=>({tag:"ol"}),paragraph:s=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(s){const e=g({},s.attrs),{linktype:t="url"}=s.attrs;return t==="email"&&(e.href="mailto:"+e.href),e.anchor&&(e.href=`${e.href}#${e.anchor}`,delete e.anchor),{tag:[{tag:"a",attrs:e}]}},styled:s=>({tag:[{tag:"span",attrs:s.attrs}]})}};class G{constructor(e){e||(e=F),this.marks=e.marks||[],this.nodes=e.nodes||[]}addNode(e,t){this.nodes[e]=t}addMark(e,t){this.marks[e]=t}render(e={}){if(e.content&&Array.isArray(e.content)){let t="";return e.content.forEach(r=>{t+=this.renderNode(r)}),t}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(e){let t=[];e.marks&&e.marks.forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderOpeningTag(n.tag))});const r=this.getMatchingNode(e);return r&&r.tag&&t.push(this.renderOpeningTag(r.tag)),e.content?e.content.forEach(o=>{t.push(this.renderNode(o))}):e.text?t.push(function(o){const n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},i=/[&<>"']/g,a=RegExp(i.source);return o&&a.test(o)?o.replace(i,u=>n[u]):o}(e.text)):r&&r.singleTag?t.push(this.renderTag(r.singleTag," /")):r&&r.html&&t.push(r.html),r&&r.tag&&t.push(this.renderClosingTag(r.tag)),e.marks&&e.marks.slice(0).reverse().forEach(o=>{const n=this.getMatchingMark(o);n&&t.push(this.renderClosingTag(n.tag))}),t.join("")}renderTag(e,t){return e.constructor===String?`<${e}${t}>`:e.map(r=>{if(r.constructor===String)return`<${r}${t}>`;{let o="<"+r.tag;if(r.attrs)for(let n in r.attrs){let i=r.attrs[n];i!==null&&(o+=` ${n}="${i}"`)}return`${o}${t}>`}}).join("")}renderOpeningTag(e){return this.renderTag(e,"")}renderClosingTag(e){return e.constructor===String?`</${e}>`:e.slice(0).reverse().map(t=>t.constructor===String?`</${t}>`:`</${t.tag}>`).join("")}getMatchingNode(e){if(typeof this.nodes[e.type]=="function")return this.nodes[e.type](e)}getMatchingMark(e){if(typeof this.marks[e.type]=="function")return this.marks[e.type](e)}}const Q=(s=0,e=s)=>{const t=Math.abs(e-s)||0,r=s<e?1:-1;return((o=0,n)=>[...Array(o)].map(n))(t,(o,n)=>n*r+s)},w=(s,e,t)=>{const r=[];for(const o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;const n=s[o],i=t?"":encodeURIComponent(o);let a;a=typeof n=="object"?w(n,e?e+encodeURIComponent("["+i+"]"):i,Array.isArray(n)):(e?e+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")};let b={},y={};class W{constructor(e,t){if(!t){let n=e.region?"-"+e.region:"",i=e.https===!1?"http":"https";t=e.oauthToken===void 0?`${i}://api${n}.storyblok.com/v2`:`${i}://api${n}.storyblok.com/v1`}let r=Object.assign({},e.headers),o=5;e.oauthToken!==void 0&&(r.Authorization=e.oauthToken,o=3),e.rateLimit!==void 0&&(o=e.rateLimit),this.richTextResolver=new G(e.richTextSchema),typeof e.componentResolver=="function"&&this.setComponentResolver(e.componentResolver),this.maxRetries=e.maxRetries||5,this.throttle=A(this.throttledRequest,o,1e3),this.accessToken=e.accessToken,this.relations={},this.links={},this.cache=e.cache||{clear:"manual"},this.client=L.default.create({baseURL:t,timeout:e.timeout||0,headers:r,proxy:e.proxy||!1}),e.responseInterceptor&&this.client.interceptors.response.use(n=>e.responseInterceptor(n))}setComponentResolver(e){this.richTextResolver.addNode("blok",t=>{let r="";return t.attrs.body.forEach(o=>{r+=e(o.component,o)}),{html:r}})}parseParams(e={}){return e.version||(e.version="published"),e.token||(e.token=this.getToken()),e.cv||(e.cv=y[e.token]),Array.isArray(e.resolve_relations)&&(e.resolve_relations=e.resolve_relations.join(",")),e}factoryParamOptions(e,t={}){return((r="")=>r.indexOf("/cdn/")>-1)(e)?this.parseParams(t):t}makeRequest(e,t,r,o){const n=this.factoryParamOptions(e,((i={},a=25,u=1)=>_(g({},i),{per_page:a,page:u}))(t,r,o));return this.cacheResponse(e,n)}get(e,t){let r="/"+e;const o=this.factoryParamOptions(r,t);return this.cacheResponse(r,o)}async getAll(e,t={},r){const o=t.per_page||25,n="/"+e,i=n.split("/");r=r||i[i.length-1];const a=await this.makeRequest(n,t,o,1),u=Math.ceil(a.total/o);return((c=[],d)=>c.map(d).reduce((k,se)=>[...k,...se],[]))([a,...await(async(c=[],d)=>Promise.all(c.map(d)))(Q(1,u),async c=>this.makeRequest(n,t,o,c+1))],c=>Object.values(c.data[r]))}post(e,t){let r="/"+e;return this.throttle("post",r,t)}put(e,t){let r="/"+e;return this.throttle("put",r,t)}delete(e,t){let r="/"+e;return this.throttle("delete",r,t)}getStories(e){return this.get("cdn/stories",e)}getStory(e,t){return this.get("cdn/stories/"+e,t)}setToken(e){this.accessToken=e}getToken(){return this.accessToken}_cleanCopy(e){return JSON.parse(JSON.stringify(e))}_insertLinks(e,t){const r=e[t];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[r.id]?r.story=this._cleanCopy(this.links[r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[r.uuid]&&(r.story=this._cleanCopy(this.links[r.uuid]))}_insertRelations(e,t,r){if(r.indexOf(e.component+"."+t)>-1){if(typeof e[t]=="string")this.relations[e[t]]&&(e[t]=this._cleanCopy(this.relations[e[t]]));else if(e[t].constructor===Array){let o=[];e[t].forEach(n=>{this.relations[n]&&o.push(this._cleanCopy(this.relations[n]))}),e[t]=o}}}iterateTree(e,t){let r=o=>{if(o!=null){if(o.constructor===Array)for(let n=0;n<o.length;n++)r(o[n]);else if(o.constructor===Object){if(o._stopResolving)return;for(let n in o)(o.component&&o._uid||o.type==="link")&&(this._insertRelations(o,n,t),this._insertLinks(o,n)),r(o[n])}}};r(e.content)}async resolveLinks(e,t){let r=[];if(e.link_uuids){const o=e.link_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const u=Math.min(o,a+i);n.push(e.link_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.links;r.forEach(o=>{this.links[o.uuid]=_(g({},o),{_stopResolving:!0})})}async resolveRelations(e,t){let r=[];if(e.rel_uuids){const o=e.rel_uuids.length;let n=[];const i=50;for(let a=0;a<o;a+=i){const u=Math.min(o,a+i);n.push(e.rel_uuids.slice(a,u))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:i,language:t.language,version:t.version,by_uuids:n[a].join(",")})).data.stories.forEach(u=>{r.push(u)})}else r=e.rels;r.forEach(o=>{this.relations[o.uuid]=_(g({},o),{_stopResolving:!0})})}async resolveStories(e,t){let r=[];t.resolve_relations!==void 0&&t.resolve_relations.length>0&&(r=t.resolve_relations.split(","),await this.resolveRelations(e,t)),["1","story","url"].indexOf(t.resolve_links)>-1&&await this.resolveLinks(e,t);for(const o in this.relations)this.iterateTree(this.relations[o],r);e.story?this.iterateTree(e.story,r):e.stories.forEach(o=>{this.iterateTree(o,r)})}cacheResponse(e,t,r){return r===void 0&&(r=0),new Promise(async(o,n)=>{let i=w({url:e,params:t}),a=this.cacheProvider();if(this.cache.clear==="auto"&&t.version==="draft"&&await this.flushCache(),t.version==="published"&&e!="/cdn/spaces/me"){const c=await a.get(i);if(c)return o(c)}try{let c=await this.throttle("get",e,{params:t,paramsSerializer:k=>w(k)}),d={data:c.data,headers:c.headers};if(c.headers["per-page"]&&(d=Object.assign({},d,{perPage:parseInt(c.headers["per-page"]),total:parseInt(c.headers.total)})),c.status!=200)return n(c);(d.data.story||d.data.stories)&&await this.resolveStories(d.data,t),t.version==="published"&&e!="/cdn/spaces/me"&&a.set(i,d),d.data.cv&&(t.version=="draft"&&y[t.token]!=d.data.cv&&this.flushCache(),y[t.token]=d.data.cv),o(d)}catch(c){if(c.response&&c.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(u=1e3*r,new Promise(d=>setTimeout(d,u))),this.cacheResponse(e,t,r).then(o).catch(n);n(c)}var u})}throttledRequest(e,t,r){return this.client[e](t,r)}cacheVersions(){return y}cacheVersion(){return y[this.accessToken]}setCacheVersion(e){this.accessToken&&(y[this.accessToken]=e)}cacheProvider(){switch(this.cache.type){case"memory":return{get:e=>b[e],getAll:()=>b,set(e,t){b[e]=t},flush(){b={}}};default:return{get(){},getAll(){},set(){},flush(){}}}}async flushCache(){return await this.cacheProvider().flush(),this}}var X=(s={})=>{const{apiOptions:e}=s;if(!e.accessToken){console.error("You need to provide an access token to interact with Storyblok API. Read https://www.storyblok.com/docs/api/content-delivery#topics/authentication");return}return{storyblokApi:new W(e)}},Z=s=>{if(typeof s!="object"||typeof s._editable=="undefined")return{};const e=JSON.parse(s._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(e),"data-blok-uid":e.id+"-"+e.uid}};const T=(s,e,t={})=>{if(typeof window!="undefined"){if(typeof window.storyblokRegisterEvent=="undefined"){console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");return}if(!s){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(t).on(["input","published","change"],o=>{o.action=="input"&&o.story.id===s?e(o.story):window.location.reload()})})}},K=(s={})=>{const{bridge:e,accessToken:t,use:r=[],apiOptions:o={}}=s;o.accessToken=o.accessToken||t;const n={bridge:e,apiOptions:o};let i={};return r.forEach(a=>{i=g(g({},i),a(n))}),e!==!1&&z("https://app.storyblok.com/f/storyblok-v2-latest.js"),i},ee=t=>{var r=t,{blok:s}=r,e=B(r,["blok"]);if(!s)return console.error("Please provide a 'blok' property to the StoryblokComponent"),E.default.createElement("div",null,"Please provide a blok property to the StoryblokComponent");const o=I(s.component);return o?E.default.createElement(o,q({blok:s},e)):""},te=(s,e={},t={})=>{let[r,o]=h.useState({});return m?(T(r.id,n=>o(n),t),h.useEffect(async()=>{const{data:n}=await m.get(`cdn/stories/${s}`,e);o(n.story)},[]),r):(console.error("You can't use useStoryblok if you're not loading apiPlugin."),null)},re=(s={},e={})=>{let[t,r]=h.useState(s);return T(t.id,o=>r(o),e),h.useEffect(()=>{r(s)},[s]),t};let m=null;const $=()=>(m||console.error("You can't use getStoryblokApi if you're not loading apiPlugin."),m);let S={};const I=s=>S[s]?S[s]:(console.error(`Component ${s} doesn't exist.`),!1),oe=(s={})=>{const{storyblokApi:e}=K(s);m=e,S=s.components};l.StoryblokComponent=ee,l.apiPlugin=X,l.getComponent=I,l.getStoryblokApi=$,l.storyblokEditable=Z,l.storyblokInit=oe,l.useStoryblok=te,l.useStoryblokApi=$,l.useStoryblokBridge=T,l.useStoryblokState=re,Object.defineProperties(l,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
@@ -443,6 +443,10 @@ const useStoryblokBridge = (id, cb, options = {}) => {
443
443
  console.error("Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js");
444
444
  return;
445
445
  }
446
+ if (!id) {
447
+ console.warn("Story ID is not defined. Please provide a valid ID.");
448
+ return;
449
+ }
446
450
  window.storyblokRegisterEvent(() => {
447
451
  const sbBridge = new window.StoryblokBridge(options);
448
452
  sbBridge.on(["input", "published", "change"], (event) => {
@@ -505,7 +509,7 @@ const useStoryblokState = (initialStory = {}, bridgeOptions = {}) => {
505
509
  let storyblokApiInstance = null;
506
510
  const useStoryblokApi = () => {
507
511
  if (!storyblokApiInstance) {
508
- console.error("You can't use useStoryblokApi if you're not loading apiPlugin.");
512
+ console.error("You can't use getStoryblokApi if you're not loading apiPlugin.");
509
513
  }
510
514
  return storyblokApiInstance;
511
515
  };
@@ -522,4 +526,4 @@ const storyblokInit = (pluginOptions = {}) => {
522
526
  storyblokApiInstance = storyblokApi;
523
527
  componentsMap = pluginOptions.components;
524
528
  };
525
- export { StoryblokComponent, api as apiPlugin, getComponent, editable as storyblokEditable, storyblokInit, useStoryblok, useStoryblokApi, useStoryblokBridge, useStoryblokState };
529
+ export { StoryblokComponent, api as apiPlugin, getComponent, useStoryblokApi as getStoryblokApi, editable as storyblokEditable, storyblokInit, useStoryblok, useStoryblokApi, useStoryblokBridge, useStoryblokState };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storyblok/react",
3
- "version": "1.0.1",
3
+ "version": "1.0.4",
4
4
  "description": "SDK to integrate Storyblok into your project using React.",
5
5
  "main": "./dist/storyblok-react.js",
6
6
  "module": "./dist/storyblok-react.mjs",
@@ -23,19 +23,19 @@
23
23
  "prepublishOnly": "npm run build && cp ../README.md ./"
24
24
  },
25
25
  "dependencies": {
26
- "@storyblok/js": "^1.0.3"
26
+ "@storyblok/js": "^1.0.4"
27
27
  },
28
28
  "devDependencies": {
29
- "@babel/core": "^7.15.0",
29
+ "@babel/core": "^7.17.8",
30
30
  "@babel/preset-env": "^7.16.11",
31
31
  "@cypress/react": "^5.12.3",
32
32
  "@cypress/vite-dev-server": "^2.2.2",
33
33
  "@vitejs/plugin-react": "^1.1.4",
34
- "babel-jest": "^26.6.3",
35
- "cypress": "^9.5.0",
34
+ "babel-jest": "^27.5.1",
35
+ "cypress": "^9.5.3",
36
36
  "eslint-plugin-cypress": "^2.12.1",
37
- "eslint-plugin-jest": "^25.2.4",
38
- "jest": "^26.6.3",
37
+ "eslint-plugin-jest": "^26.1.3",
38
+ "jest": "^27.5.1",
39
39
  "react": "17.0.2",
40
40
  "vite": "^2.8.4"
41
41
  },