@storyblok/js 1.7.2 → 1.8.2
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +47 -2
- package/dist/storyblok-js.js +3 -3
- package/dist/storyblok-js.mjs +40 -8
- package/dist/types/index.d.ts +4 -2
- package/dist/types/types.d.ts +6 -1
- package/package.json +5 -5
package/README.md
CHANGED
@@ -97,7 +97,7 @@ const { data } = await storyblokApi.get("cdn/stories", { version: "draft" });
|
|
97
97
|
|
98
98
|
#### 2. Listen to Storyblok Visual Editor events
|
99
99
|
|
100
|
-
Use `useStoryblokBridge` to get the new story every time is triggered a `change` event from the Visual Editor. You need to pass the story id as first param, and a callback function as second param to update the new story:
|
100
|
+
Use `useStoryblokBridge` or `registerStoryblokBridge` to get the new story every time is triggered a `change` event from the Visual Editor. You need to pass the story id as first param, and a callback function as second param to update the new story:
|
101
101
|
|
102
102
|
```js
|
103
103
|
import { storyblokInit, apiPlugin, useStoryblokBridge } from "@storyblok/js";
|
@@ -180,7 +180,7 @@ const { storyblokApi } = storyblokInit({
|
|
180
180
|
});
|
181
181
|
```
|
182
182
|
|
183
|
-
If you don't use `useStoryblokBridge`, you have still access to the raw `window.StoryblokBridge`:
|
183
|
+
If you don't use `useStoryblokBridge` or `registerStoryblokBridge`, you have still access to the raw `window.StoryblokBridge`:
|
184
184
|
|
185
185
|
```js
|
186
186
|
const sbBridge = new window.StoryblokBridge(options);
|
@@ -200,6 +200,51 @@ import { renderRichText } from "@storyblok/js";
|
|
200
200
|
const renderedRichText = renderRichText(blok.richtext);
|
201
201
|
```
|
202
202
|
|
203
|
+
You can set a **custom Schema and component resolver globally** at init time by using the `richText` init option:
|
204
|
+
|
205
|
+
```js
|
206
|
+
import { RichTextSchema, storyblokInit } from "@storyblok/js";
|
207
|
+
import cloneDeep from "clone-deep";
|
208
|
+
|
209
|
+
const mySchema = cloneDeep(RichTextSchema); // you can make a copy of the default RichTextSchema
|
210
|
+
// ... and edit the nodes and marks, or add your own.
|
211
|
+
// Check the base RichTextSchema source here https://github.com/storyblok/storyblok-js-client/blob/master/source/schema.js
|
212
|
+
|
213
|
+
storyblokInit({
|
214
|
+
accessToken: "<your-token>",
|
215
|
+
richText: {
|
216
|
+
schema: mySchema,
|
217
|
+
resolver: (component, blok) => {
|
218
|
+
switch (component) {
|
219
|
+
case "my-custom-component":
|
220
|
+
return `<div class="my-component-class">${blok.text}</div>`;
|
221
|
+
default:
|
222
|
+
return "Resolver not defined";
|
223
|
+
}
|
224
|
+
},
|
225
|
+
},
|
226
|
+
});
|
227
|
+
```
|
228
|
+
|
229
|
+
You can also set a **custom Schema and component resolver only once** by passing the options as the second parameter to `renderRichText` function:
|
230
|
+
|
231
|
+
```js
|
232
|
+
import { renderRichText } from "@storyblok/js";
|
233
|
+
|
234
|
+
renderRichText(blok.richTextField, {
|
235
|
+
schema: mySchema,
|
236
|
+
resolver: (component, blok) => {
|
237
|
+
switch (component) {
|
238
|
+
case "my-custom-component":
|
239
|
+
return `<div class="my-component-class">${blok.text}</div>`;
|
240
|
+
break;
|
241
|
+
default:
|
242
|
+
return `Component ${component} not found`;
|
243
|
+
}
|
244
|
+
},
|
245
|
+
});
|
246
|
+
```
|
247
|
+
|
203
248
|
## 🔗 Related Links
|
204
249
|
|
205
250
|
- **[Storyblok Technology Hub](https://www.storyblok.com/technologies?utm_source=github.com&utm_medium=readme&utm_campaign=storyblok-js)**: Storyblok integrates with every framework so that you are free to choose the best fit for your project. We prepared the technology hub so that you can find selected beginner tutorials, videos, boilerplates, and even cheatsheets all in one place.
|
package/dist/storyblok-js.js
CHANGED
@@ -1,7 +1,7 @@
|
|
1
|
-
(function(h,d){typeof exports=="object"&&typeof module!="undefined"?d(exports,require("axios")):typeof define=="function"&&define.amd?define(["exports","axios"],d):(h=typeof globalThis!="undefined"?globalThis:h||self,d(h.storyblok={},h.e))})(this,function(h,d){"use strict";var
|
1
|
+
(function(h,d){typeof exports=="object"&&typeof module!="undefined"?d(exports,require("axios")):typeof define=="function"&&define.amd?define(["exports","axios"],d):(h=typeof globalThis!="undefined"?globalThis:h||self,d(h.storyblok={},h.e))})(this,function(h,d){"use strict";var K=Object.defineProperty,G=Object.defineProperties;var Q=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var W=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable;var A=(h,d,g)=>d in h?K(h,d,{enumerable:!0,configurable:!0,writable:!0,value:g}):h[d]=g,f=(h,d)=>{for(var g in d||(d={}))W.call(d,g)&&A(h,g,d[g]);if(M)for(var g of M(d))X.call(d,g)&&A(h,g,d[g]);return h},b=(h,d)=>G(h,Q(d));function g(n){return n&&typeof n=="object"&&"default"in n?n:{default:n}}var C=g(d);let T=!1;const w=[],_=n=>new Promise((t,e)=>{if(typeof window=="undefined"||(window.storyblokRegisterEvent=s=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}T?s():w.push(s)},document.getElementById("storyblok-javascript-bridge")))return;const r=document.createElement("script");r.async=!0,r.src=n,r.id="storyblok-javascript-bridge",r.onerror=s=>e(s),r.onload=s=>{w.forEach(o=>o()),T=!0,t(s)},document.getElementsByTagName("head")[0].appendChild(r)}),N=function(n,t){if(!n)return null;let e={};for(let r in n){let s=n[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e},P=n=>n==="email";var R={nodes:{horizontal_rule(){return{singleTag:"hr"}},blockquote(){return{tag:"blockquote"}},bullet_list(){return{tag:"ul"}},code_block(n){return{tag:["pre",{tag:"code",attrs:n.attrs}]}},hard_break(){return{singleTag:"br"}},heading(n){return{tag:`h${n.attrs.level}`}},image(n){return{singleTag:[{tag:"img",attrs:N(n.attrs,["src","alt","title"])}]}},list_item(){return{tag:"li"}},ordered_list(){return{tag:"ol"}},paragraph(){return{tag:"p"}}},marks:{bold(){return{tag:"b"}},strike(){return{tag:"strike"}},underline(){return{tag:"u"}},strong(){return{tag:"strong"}},code(){return{tag:"code"}},italic(){return{tag:"i"}},link(n){const t=f({},n.attrs),{linktype:e="url"}=n.attrs;return P(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled(n){return{tag:[{tag:"span",attrs:n.attrs}]}}}};const I=function(n){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},e=/[&<>"']/g,r=RegExp(e.source);return n&&r.test(n)?n.replace(e,s=>t[s]):n};class ${constructor(t){t||(t=R),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t={}){if(t.content&&Array.isArray(t.content)){let e="";return t.content.forEach(r=>{e+=this.renderNode(r)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let e=[];t.marks&&t.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&e.push(this.renderOpeningTag(o.tag))});const r=this.getMatchingNode(t);return r&&r.tag&&e.push(this.renderOpeningTag(r.tag)),t.content?t.content.forEach(s=>{e.push(this.renderNode(s))}):t.text?e.push(I(t.text)):r&&r.singleTag?e.push(this.renderTag(r.singleTag," /")):r&&r.html&&e.push(r.html),r&&r.tag&&e.push(this.renderClosingTag(r.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&e.push(this.renderClosingTag(o.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let o=`<${s.tag}`;if(s.attrs)for(let a in s.attrs){let i=s.attrs[a];i!==null&&(o+=` ${a}="${i}"`)}return`${o}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(r=>r.constructor===String?`</${r}>`:`</${r.tag}>`).join("")}getMatchingNode(t){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}/*!
|
2
2
|
* storyblok-js-client v4.5.2
|
3
3
|
* Universal JavaScript SDK for Storyblok's API
|
4
4
|
* (c) 2020-2022 Stobylok Team
|
5
|
-
*/function _(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function R(n,t,e){if(!_(t))throw new TypeError("Expected `limit` to be a finite number");if(!_(e))throw new TypeError("Expected `interval` to be a finite number");var r=[],s=[],o=0,i=function(){o++;var c=setTimeout(function(){o--,r.length>0&&i(),s=s.filter(function(u){return u!==c})},e);s.indexOf(c)<0&&s.push(c);var l=r.shift();l.resolve(n.apply(l.self,l.args))},a=function(){var c=arguments,l=this;return new Promise(function(u,y){r.push({resolve:u,reject:y,args:c,self:l}),o<t&&i()})};return a.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(c){c.reject(new throttle.AbortError)}),r.length=0},a}R.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const N=function(n,t){if(!n)return null;let e={};for(let r in n){let s=n[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e};var P={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:n=>({tag:`h${n.attrs.level}`}),image:n=>({singleTag:[{tag:"img",attrs:N(n.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(n){const t=p({},n.attrs),{linktype:e="url"}=n.attrs;return e==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class I{constructor(t){t||(t=P),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t={}){if(t.content&&Array.isArray(t.content)){let e="";return t.content.forEach(r=>{e+=this.renderNode(r)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let e=[];t.marks&&t.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&e.push(this.renderOpeningTag(o.tag))});const r=this.getMatchingNode(t);return r&&r.tag&&e.push(this.renderOpeningTag(r.tag)),t.content?t.content.forEach(s=>{e.push(this.renderNode(s))}):t.text?e.push(function(s){const o={"&":"&","<":"<",">":">",'"':""","'":"'"},i=/[&<>"']/g,a=RegExp(i.source);return s&&a.test(s)?s.replace(i,c=>o[c]):s}(t.text)):r&&r.singleTag?e.push(this.renderTag(r.singleTag," /")):r&&r.html&&e.push(r.html),r&&r.tag&&e.push(this.renderClosingTag(r.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&e.push(this.renderClosingTag(o.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(r=>{if(r.constructor===String)return`<${r}${e}>`;{let s=`<${r.tag}`;if(r.attrs)for(let o in r.attrs){let i=r.attrs[o];i!==null&&(s+=` ${o}="${i}"`)}return`${s}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}const q=(n=0,t=n)=>{const e=Math.abs(t-n)||0,r=n<t?1:-1;return((s=0,o)=>[...Array(s)].map(o))(e,(s,o)=>o*r+n)},b=(n,t,e)=>{const r=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],i=e?"":encodeURIComponent(s);let a;a=typeof o=="object"?b(o,t?t+encodeURIComponent("["+i+"]"):i,Array.isArray(o)):(t?t+encodeURIComponent("["+i+"]"):i)+"="+encodeURIComponent(o),r.push(a)}return r.join("&")};let k={},f={};class B{constructor(t,e){if(!e){let o=t.region?`-${t.region}`:"",i=t.https===!1?"http":"https";e=t.oauthToken===void 0?`${i}://api${o}.storyblok.com/v2`:`${i}://api${o}.storyblok.com/v1`}let r=Object.assign({},t.headers),s=5;t.oauthToken!==void 0&&(r.Authorization=t.oauthToken,s=3),t.rateLimit!==void 0&&(s=t.rateLimit),this.richTextResolver=new I(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=R(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=S.default.create({baseURL:e,timeout:t.timeout||0,headers:r,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(o=>t.responseInterceptor(o)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let r="";return e.attrs.body.forEach(s=>{r+=t(s.component,s)}),{html:r}})}parseParams(t={}){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=f[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e={}){return((r="")=>r.indexOf("/cdn/")>-1)(t)?this.parseParams(e):e}makeRequest(t,e,r,s){const o=this.factoryParamOptions(t,((i={},a=25,c=1)=>m(p({},i),{per_page:a,page:c}))(e,r,s));return this.cacheResponse(t,o)}get(t,e){let r=`/${t}`;const s=this.factoryParamOptions(r,e);return this.cacheResponse(r,s)}async getAll(t,e={},r){const s=e.per_page||25,o=`/${t}`,i=o.split("/");r=r||i[i.length-1];const a=await this.makeRequest(o,e,s,1),c=Math.ceil(a.total/s);return((l=[],u)=>l.map(u).reduce((y,F)=>[...y,...F],[]))([a,...await(async(l=[],u)=>Promise.all(l.map(u)))(q(1,c),async l=>this.makeRequest(o,e,s,l+1))],l=>Object.values(l.data[r]))}post(t,e){let r=`/${t}`;return this.throttle("post",r,e)}put(t,e){let r=`/${t}`;return this.throttle("put",r,e)}delete(t,e){let r=`/${t}`;return this.throttle("delete",r,e)}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e){const r=t[e];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(t,e,r){if(r.indexOf(t.component+"."+e)>-1){if(typeof t[e]=="string")this.relations[t[e]]&&(t[e]=this._cleanCopy(this.relations[t[e]]));else if(t[e].constructor===Array){let s=[];t[e].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),t[e]=s}}}_insertAssetsRelations(t,e){e.forEach(r=>{t.id===r.id&&(t.original=r,t.original.filename=t.filename,t.original.filename=t.original.filename.includes("https://s3.amazonaws.com/")?t.original.filename:t.original.filename.replace("https://","https://s3.amazonaws.com/"),delete t.original.s3_filename)})}iterateTree(t,e){let r=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)r(s[o]);else if(s.constructor===Object){if(s._stopResolving)return;for(let o in s)s.component&&s._uid||s.type==="link"?(this._insertRelations(s,o,e),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,e),r(s[o])}}};r(t.content)}async resolveLinks(t,e){let r=[];if(t.link_uuids){const s=t.link_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const c=Math.min(s,a+i);o.push(t.link_uuids.slice(a,c))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:o[a].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=t.links;r.forEach(s=>{this.links[s.uuid]=m(p({},s),{_stopResolving:!0})})}async resolveRelations(t,e){let r=[];if(t.rel_uuids){const s=t.rel_uuids.length;let o=[];const i=50;for(let a=0;a<s;a+=i){const c=Math.min(s,a+i);o.push(t.rel_uuids.slice(a,c))}for(let a=0;a<o.length;a++)(await this.getStories({per_page:i,language:e.language,version:e.version,by_uuids:o[a].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=t.rels;r.forEach(s=>{this.relations[s.uuid]=m(p({},s),{_stopResolving:!0})})}async resolveStories(t,e){let r=[];if(e.resolve_relations!==void 0&&e.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(r=e.resolve_relations.split(","),await this.resolveRelations(t,e)),["1","story","url"].indexOf(e.resolve_links)>-1&&(t.links||t.link_uuids)&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],r);t.story?this.iterateTree(t.story,r):t.stories.forEach(s=>{this.iterateTree(s,r)})}resolveAssetsRelations(t){const{assets:e,stories:r,story:s}=t;if(r)for(const o of r)this.iterateTree(o,e);else{if(!s)return t;this.iterateTree(s,e)}}cacheResponse(t,e,r){return r===void 0&&(r=0),new Promise(async(s,o)=>{let i=b({url:t,params:e}),a=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const l=await a.get(i);if(l)return s(l)}try{let l=await this.throttle("get",t,{params:e,paramsSerializer:y=>b(y)}),u={data:l.data,headers:l.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),l.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&a.set(i,u),u.data.cv&&(e.version=="draft"&&f[e.token]!=u.data.cv&&this.flushCache(),f[e.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(c=1e3*r,new Promise(u=>setTimeout(u,c))),this.cacheResponse(t,e,r).then(s).catch(o);o(l)}var c})}throttledRequest(t,e,r){return this.client[t](e,r)}cacheVersions(){return f}cacheVersion(){return f[this.accessToken]}setCacheVersion(t){this.accessToken&&(f[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>k[t],getAll:()=>k,set(t,e){k[t]=e},flush(){k={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const L=(n={})=>{const{apiOptions:t}=n;if(!t.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 B(t)}};var z=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const t=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};const U=new C,$="https://app.storyblok.com/f/storyblok-v2-latest.js",H=(n,t,e={})=>{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(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],s=>{s.story.id===n&&(s.action==="input"?t(s.story):window.location.reload())})})}},D=(n={})=>{const{bridge:t,accessToken:e,use:r=[],apiOptions:s={}}=n;s.accessToken=s.accessToken||e;const o={bridge:t,apiOptions:s};let i={};return r.forEach(a=>{i=p(p({},i),a(o))}),t!==!1&&w($),i},J=n=>n===""?"":n?U.render(n):(console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
5
|
+
*/function E(n){return typeof n=="number"&&n==n&&n!==1/0&&n!==-1/0}function S(n,t,e){if(!E(t))throw new TypeError("Expected `limit` to be a finite number");if(!E(e))throw new TypeError("Expected `interval` to be a finite number");var r=[],s=[],o=0,a=function(){o++;var c=setTimeout(function(){o--,r.length>0&&a(),s=s.filter(function(u){return u!==c})},e);s.indexOf(c)<0&&s.push(c);var l=r.shift();l.resolve(n.apply(l.self,l.args))},i=function(){var c=arguments,l=this;return new Promise(function(u,y){r.push({resolve:u,reject:y,args:c,self:l}),o<t&&a()})};return i.abort=function(){s.forEach(clearTimeout),s=[],r.forEach(function(c){c.reject(new throttle.AbortError)}),r.length=0},i}S.AbortError=function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"};const q=function(n,t){if(!n)return null;let e={};for(let r in n){let s=n[r];t.indexOf(r)>-1&&s!==null&&(e[r]=s)}return e};var B={nodes:{horizontal_rule:()=>({singleTag:"hr"}),blockquote:()=>({tag:"blockquote"}),bullet_list:()=>({tag:"ul"}),code_block:n=>({tag:["pre",{tag:"code",attrs:n.attrs}]}),hard_break:()=>({singleTag:"br"}),heading:n=>({tag:`h${n.attrs.level}`}),image:n=>({singleTag:[{tag:"img",attrs:q(n.attrs,["src","alt","title"])}]}),list_item:()=>({tag:"li"}),ordered_list:()=>({tag:"ol"}),paragraph:()=>({tag:"p"})},marks:{bold:()=>({tag:"b"}),strike:()=>({tag:"strike"}),underline:()=>({tag:"u"}),strong:()=>({tag:"strong"}),code:()=>({tag:"code"}),italic:()=>({tag:"i"}),link(n){const t=f({},n.attrs),{linktype:e="url"}=n.attrs;return e==="email"&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),{tag:[{tag:"a",attrs:t}]}},styled:n=>({tag:[{tag:"span",attrs:n.attrs}]})}};class L{constructor(t){t||(t=B),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t={}){if(t.content&&Array.isArray(t.content)){let e="";return t.content.forEach(r=>{e+=this.renderNode(r)}),e}return console.warn("The render method must receive an object with a content field, which is an array"),""}renderNode(t){let e=[];t.marks&&t.marks.forEach(s=>{const o=this.getMatchingMark(s);o&&e.push(this.renderOpeningTag(o.tag))});const r=this.getMatchingNode(t);return r&&r.tag&&e.push(this.renderOpeningTag(r.tag)),t.content?t.content.forEach(s=>{e.push(this.renderNode(s))}):t.text?e.push(function(s){const o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=/[&<>"']/g,i=RegExp(a.source);return s&&i.test(s)?s.replace(a,c=>o[c]):s}(t.text)):r&&r.singleTag?e.push(this.renderTag(r.singleTag," /")):r&&r.html&&e.push(r.html),r&&r.tag&&e.push(this.renderClosingTag(r.tag)),t.marks&&t.marks.slice(0).reverse().forEach(s=>{const o=this.getMatchingMark(s);o&&e.push(this.renderClosingTag(o.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(r=>{if(r.constructor===String)return`<${r}${e}>`;{let s=`<${r.tag}`;if(r.attrs)for(let o in r.attrs){let a=r.attrs[o];a!==null&&(s+=` ${o}="${a}"`)}return`${s}${e}>`}}).join("")}renderOpeningTag(t){return this.renderTag(t,"")}renderClosingTag(t){return t.constructor===String?`</${t}>`:t.slice(0).reverse().map(e=>e.constructor===String?`</${e}>`:`</${e.tag}>`).join("")}getMatchingNode(t){if(typeof this.nodes[t.type]=="function")return this.nodes[t.type](t)}getMatchingMark(t){if(typeof this.marks[t.type]=="function")return this.marks[t.type](t)}}const z=(n=0,t=n)=>{const e=Math.abs(t-n)||0,r=n<t?1:-1;return((s=0,o)=>[...Array(s)].map(o))(e,(s,o)=>o*r+n)},v=(n,t,e)=>{const r=[];for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s],a=e?"":encodeURIComponent(s);let i;i=typeof o=="object"?v(o,t?t+encodeURIComponent("["+a+"]"):a,Array.isArray(o)):(t?t+encodeURIComponent("["+a+"]"):a)+"="+encodeURIComponent(o),r.push(i)}return r.join("&")};let m={},p={};class U{constructor(t,e){if(!e){let o=t.region?`-${t.region}`:"",a=t.https===!1?"http":"https";e=t.oauthToken===void 0?`${a}://api${o}.storyblok.com/v2`:`${a}://api${o}.storyblok.com/v1`}let r=Object.assign({},t.headers),s=5;t.oauthToken!==void 0&&(r.Authorization=t.oauthToken,s=3),t.rateLimit!==void 0&&(s=t.rateLimit),this.richTextResolver=new L(t.richTextSchema),typeof t.componentResolver=="function"&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=S(this.throttledRequest,s,1e3),this.accessToken=t.accessToken,this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.client=C.default.create({baseURL:e,timeout:t.timeout||0,headers:r,proxy:t.proxy||!1}),t.responseInterceptor&&this.client.interceptors.response.use(o=>t.responseInterceptor(o)),this.resolveNestedRelations=t.resolveNestedRelations||!0}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let r="";return e.attrs.body.forEach(s=>{r+=t(s.component,s)}),{html:r}})}parseParams(t={}){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=p[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e={}){return((r="")=>r.indexOf("/cdn/")>-1)(t)?this.parseParams(e):e}makeRequest(t,e,r,s){const o=this.factoryParamOptions(t,((a={},i=25,c=1)=>b(f({},a),{per_page:i,page:c}))(e,r,s));return this.cacheResponse(t,o)}get(t,e){let r=`/${t}`;const s=this.factoryParamOptions(r,e);return this.cacheResponse(r,s)}async getAll(t,e={},r){const s=e.per_page||25,o=`/${t}`,a=o.split("/");r=r||a[a.length-1];const i=await this.makeRequest(o,e,s,1),c=Math.ceil(i.total/s);return((l=[],u)=>l.map(u).reduce((y,Y)=>[...y,...Y],[]))([i,...await(async(l=[],u)=>Promise.all(l.map(u)))(z(1,c),async l=>this.makeRequest(o,e,s,l+1))],l=>Object.values(l.data[r]))}post(t,e){let r=`/${t}`;return this.throttle("post",r,e)}put(t,e){let r=`/${t}`;return this.throttle("put",r,e)}delete(t,e){let r=`/${t}`;return this.throttle("delete",r,e)}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}setToken(t){this.accessToken=t}getToken(){return this.accessToken}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e){const r=t[e];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(t,e,r){if(r.indexOf(t.component+"."+e)>-1){if(typeof t[e]=="string")this.relations[t[e]]&&(t[e]=this._cleanCopy(this.relations[t[e]]));else if(t[e].constructor===Array){let s=[];t[e].forEach(o=>{this.relations[o]&&s.push(this._cleanCopy(this.relations[o]))}),t[e]=s}}}_insertAssetsRelations(t,e){e.forEach(r=>{t.id===r.id&&(t.original=r,t.original.filename=t.filename,t.original.filename=t.original.filename.includes("https://s3.amazonaws.com/")?t.original.filename:t.original.filename.replace("https://","https://s3.amazonaws.com/"),delete t.original.s3_filename)})}iterateTree(t,e){let r=s=>{if(s!=null){if(s.constructor===Array)for(let o=0;o<s.length;o++)r(s[o]);else if(s.constructor===Object){if(s._stopResolving)return;for(let o in s)s.component&&s._uid||s.type==="link"?(this._insertRelations(s,o,e),this._insertLinks(s,o)):"id"in s&&s.fieldtype==="asset"&&this._insertAssetsRelations(s,e),r(s[o])}}};r(t.content)}async resolveLinks(t,e){let r=[];if(t.link_uuids){const s=t.link_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(t.link_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:e.language,version:e.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=t.links;r.forEach(s=>{this.links[s.uuid]=b(f({},s),{_stopResolving:!0})})}async resolveRelations(t,e){let r=[];if(t.rel_uuids){const s=t.rel_uuids.length;let o=[];const a=50;for(let i=0;i<s;i+=a){const c=Math.min(s,i+a);o.push(t.rel_uuids.slice(i,c))}for(let i=0;i<o.length;i++)(await this.getStories({per_page:a,language:e.language,version:e.version,by_uuids:o[i].join(",")})).data.stories.forEach(c=>{r.push(c)})}else r=t.rels;r.forEach(s=>{this.relations[s.uuid]=b(f({},s),{_stopResolving:!0})})}async resolveStories(t,e){let r=[];if(e.resolve_relations!==void 0&&e.resolve_relations.length>0&&(t.rels||t.rel_uuids)&&(r=e.resolve_relations.split(","),await this.resolveRelations(t,e)),["1","story","url"].indexOf(e.resolve_links)>-1&&(t.links||t.link_uuids)&&await this.resolveLinks(t,e),this.resolveNestedRelations)for(const s in this.relations)this.iterateTree(this.relations[s],r);t.story?this.iterateTree(t.story,r):t.stories.forEach(s=>{this.iterateTree(s,r)})}resolveAssetsRelations(t){const{assets:e,stories:r,story:s}=t;if(r)for(const o of r)this.iterateTree(o,e);else{if(!s)return t;this.iterateTree(s,e)}}cacheResponse(t,e,r){return r===void 0&&(r=0),new Promise(async(s,o)=>{let a=v({url:t,params:e}),i=this.cacheProvider();if(this.cache.clear==="auto"&&e.version==="draft"&&await this.flushCache(),e.version==="published"&&t!="/cdn/spaces/me"){const l=await i.get(a);if(l)return s(l)}try{let l=await this.throttle("get",t,{params:e,paramsSerializer:y=>v(y)}),u={data:l.data,headers:l.headers};if(u.data.assets&&u.data.assets.length&&this.resolveAssetsRelations(u.data),l.headers["per-page"]&&(u=Object.assign({},u,{perPage:parseInt(l.headers["per-page"]),total:parseInt(l.headers.total)})),l.status!=200)return o(l);(u.data.story||u.data.stories)&&await this.resolveStories(u.data,e),e.version==="published"&&t!="/cdn/spaces/me"&&i.set(a,u),u.data.cv&&(e.version=="draft"&&p[e.token]!=u.data.cv&&this.flushCache(),p[e.token]=u.data.cv),s(u)}catch(l){if(l.response&&l.response.status===429&&(r+=1)<this.maxRetries)return console.log(`Hit rate limit. Retrying in ${r} seconds.`),await(c=1e3*r,new Promise(u=>setTimeout(u,c))),this.cacheResponse(t,e,r).then(s).catch(o);o(l)}var c})}throttledRequest(t,e,r){return this.client[t](e,r)}cacheVersions(){return p}cacheVersion(){return p[this.accessToken]}setCacheVersion(t){this.accessToken&&(p[this.accessToken]=t)}cacheProvider(){return this.cache.type==="memory"?{get:t=>m[t],getAll:()=>m,set(t,e){m[t]=e},flush(){m={}}}:{get(){},getAll(){},set(){},flush(){}}}async flushCache(){return await this.cacheProvider().flush(),this}}const H=(n={})=>{const{apiOptions:t}=n;if(!t.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 U(t)}};var D=n=>{if(typeof n!="object"||typeof n._editable=="undefined")return{};const t=JSON.parse(n._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let k;const j="https://app.storyblok.com/f/storyblok-v2-latest.js",x=(n,t,e={})=>{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(!n){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],s=>{s.story.id===n&&(s.action==="input"?t(s.story):window.location.reload())})})}},J=(n={})=>{const{bridge:t,accessToken:e,use:r=[],apiOptions:s={},richText:o={}}=n;s.accessToken=s.accessToken||e;const a={bridge:t,apiOptions:s};let i={};return r.forEach(c=>{i=f(f({},i),c(a))}),t!==!1&&_(j),k=new $(o.schema),o.resolver&&O(k,o.resolver),i},O=(n,t)=>{n.addNode("blok",e=>{let r="";return e.attrs.body.forEach(s=>{r+=t(s.component,s)}),{html:r}})},V=(n,t)=>{if(!k){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}if(n==="")return"";if(!n)return console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
6
6
|
|
7
|
-
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),""),
|
7
|
+
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"";let e=k;return t&&(e=new $(t.schema),t.resolver&&O(e,t.resolver)),e.render(n)},F=()=>_(j);h.RichTextSchema=R,h.apiPlugin=H,h.loadStoryblokBridge=F,h.registerStoryblokBridge=x,h.renderRichText=V,h.storyblokEditable=D,h.storyblokInit=J,h.useStoryblokBridge=x,Object.defineProperty(h,"__esModule",{value:!0}),h[Symbol.toStringTag]="Module"});
|
package/dist/storyblok-js.mjs
CHANGED
@@ -683,7 +683,7 @@ var editable = (blok) => {
|
|
683
683
|
"data-blok-uid": options.id + "-" + options.uid
|
684
684
|
};
|
685
685
|
};
|
686
|
-
|
686
|
+
let richTextResolver;
|
687
687
|
const bridgeLatest = "https://app.storyblok.com/f/storyblok-v2-latest.js";
|
688
688
|
const useStoryblokBridge = (id, cb, options = {}) => {
|
689
689
|
if (typeof window === "undefined") {
|
@@ -710,7 +710,13 @@ const useStoryblokBridge = (id, cb, options = {}) => {
|
|
710
710
|
});
|
711
711
|
};
|
712
712
|
const storyblokInit = (pluginOptions = {}) => {
|
713
|
-
const {
|
713
|
+
const {
|
714
|
+
bridge,
|
715
|
+
accessToken,
|
716
|
+
use = [],
|
717
|
+
apiOptions = {},
|
718
|
+
richText = {}
|
719
|
+
} = pluginOptions;
|
714
720
|
apiOptions.accessToken = apiOptions.accessToken || accessToken;
|
715
721
|
const options = { bridge, apiOptions };
|
716
722
|
let result = {};
|
@@ -720,18 +726,44 @@ const storyblokInit = (pluginOptions = {}) => {
|
|
720
726
|
if (bridge !== false) {
|
721
727
|
loadBridge(bridgeLatest);
|
722
728
|
}
|
729
|
+
richTextResolver = new RichTextResolver(richText.schema);
|
730
|
+
if (richText.resolver) {
|
731
|
+
setComponentResolver(richTextResolver, richText.resolver);
|
732
|
+
}
|
723
733
|
return result;
|
724
734
|
};
|
725
|
-
const
|
726
|
-
|
735
|
+
const setComponentResolver = (resolver, resolveFn) => {
|
736
|
+
resolver.addNode("blok", (node) => {
|
737
|
+
let html = "";
|
738
|
+
node.attrs.body.forEach((blok) => {
|
739
|
+
html += resolveFn(blok.component, blok);
|
740
|
+
});
|
741
|
+
return {
|
742
|
+
html
|
743
|
+
};
|
744
|
+
});
|
745
|
+
};
|
746
|
+
const renderRichText = (data, options) => {
|
747
|
+
if (!richTextResolver) {
|
748
|
+
console.error("Please initialize the Storyblok SDK before calling the renderRichText function");
|
749
|
+
return;
|
750
|
+
}
|
751
|
+
if (data === "") {
|
727
752
|
return "";
|
728
|
-
} else if (!
|
729
|
-
console.warn(`${
|
753
|
+
} else if (!data) {
|
754
|
+
console.warn(`${data} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
730
755
|
|
731
756
|
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`);
|
732
757
|
return "";
|
733
758
|
}
|
734
|
-
|
759
|
+
let localResolver = richTextResolver;
|
760
|
+
if (options) {
|
761
|
+
localResolver = new RichTextResolver(options.schema);
|
762
|
+
if (options.resolver) {
|
763
|
+
setComponentResolver(localResolver, options.resolver);
|
764
|
+
}
|
765
|
+
}
|
766
|
+
return localResolver.render(data);
|
735
767
|
};
|
736
768
|
const loadStoryblokBridge = () => loadBridge(bridgeLatest);
|
737
|
-
export { apiFactory as apiPlugin, loadStoryblokBridge, renderRichText, editable as storyblokEditable, storyblokInit, useStoryblokBridge };
|
769
|
+
export { defaultHtmlSerializer as RichTextSchema, apiFactory as apiPlugin, loadStoryblokBridge, useStoryblokBridge as registerStoryblokBridge, renderRichText, editable as storyblokEditable, storyblokInit, useStoryblokBridge };
|
package/dist/types/index.d.ts
CHANGED
@@ -1,8 +1,10 @@
|
|
1
|
-
import { SbSDKOptions, StoryblokBridgeConfigV2, StoryData, SbInitResult, Richtext, StoryblokComponentType } from "./types";
|
1
|
+
import { SbSDKOptions, StoryblokBridgeConfigV2, StoryData, SbInitResult, Richtext, StoryblokComponentType, SbRichTextOptions } from "./types";
|
2
|
+
export { default as RichTextSchema } from "storyblok-js-client/source/schema";
|
2
3
|
export declare const useStoryblokBridge: <T extends StoryblokComponentType<string> = any>(id: Number, cb: (newStory: StoryData<T>) => void, options?: StoryblokBridgeConfigV2) => void;
|
4
|
+
export { useStoryblokBridge as registerStoryblokBridge };
|
3
5
|
export { default as apiPlugin } from "./modules/api";
|
4
6
|
export { default as storyblokEditable } from "./modules/editable";
|
5
7
|
export declare const storyblokInit: (pluginOptions?: SbSDKOptions) => SbInitResult;
|
6
|
-
export declare const renderRichText: (
|
8
|
+
export declare const renderRichText: (data: Richtext, options?: SbRichTextOptions) => string;
|
7
9
|
export declare const loadStoryblokBridge: () => Promise<unknown>;
|
8
10
|
export * from "./types";
|
package/dist/types/types.d.ts
CHANGED
@@ -12,15 +12,20 @@ export interface SbInitResult {
|
|
12
12
|
storyblokApi?: StoryblokClient;
|
13
13
|
}
|
14
14
|
export declare type SbPluginFactory = (options: SbSDKOptions) => any;
|
15
|
-
export declare type SbBlokKeyDataTypes = string | number | object | boolean;
|
15
|
+
export declare type SbBlokKeyDataTypes = string | number | object | boolean | undefined;
|
16
16
|
export interface SbBlokData extends StoryblokComponent<string> {
|
17
17
|
[index: string]: SbBlokKeyDataTypes;
|
18
18
|
}
|
19
|
+
export interface SbRichTextOptions {
|
20
|
+
schema?: StoryblokConfig["richTextSchema"];
|
21
|
+
resolver?: StoryblokConfig["componentResolver"];
|
22
|
+
}
|
19
23
|
export interface SbSDKOptions {
|
20
24
|
bridge?: boolean;
|
21
25
|
accessToken?: string;
|
22
26
|
use?: any[];
|
23
27
|
apiOptions?: StoryblokConfig;
|
28
|
+
richText?: SbRichTextOptions;
|
24
29
|
}
|
25
30
|
export interface StoryblokBridgeConfigV2 {
|
26
31
|
resolveRelations?: string[];
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@storyblok/js",
|
3
|
-
"version": "1.
|
3
|
+
"version": "1.8.2",
|
4
4
|
"description": "SDK to integrate Storyblok into your project using JavaScript.",
|
5
5
|
"main": "./dist/storyblok-js.js",
|
6
6
|
"module": "./dist/storyblok-js.mjs",
|
@@ -30,17 +30,17 @@
|
|
30
30
|
"storyblok-js-client": "^4.5.6"
|
31
31
|
},
|
32
32
|
"devDependencies": {
|
33
|
-
"@babel/core": "^7.
|
34
|
-
"@babel/preset-env": "^7.
|
33
|
+
"@babel/core": "^7.19.0",
|
34
|
+
"@babel/preset-env": "^7.19.0",
|
35
35
|
"@tsconfig/recommended": "^1.0.1",
|
36
36
|
"babel-jest": "^28.1.0",
|
37
37
|
"cypress": "^9.6.1",
|
38
38
|
"eslint-plugin-cypress": "^2.12.1",
|
39
|
-
"eslint-plugin-jest": "^26.
|
39
|
+
"eslint-plugin-jest": "^26.9.0",
|
40
40
|
"jest": "^28.1.3",
|
41
41
|
"jest-console": "^0.1.0",
|
42
42
|
"start-server-and-test": "^1.14.0",
|
43
|
-
"vite": "^2.9.
|
43
|
+
"vite": "^2.9.15"
|
44
44
|
},
|
45
45
|
"babel": {
|
46
46
|
"presets": [
|