@storyblok/react 2.0.18 → 2.0.19
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/dist/storyblok-react.js +25 -2
- package/dist/storyblok-react.mjs +37 -14
- package/package.json +6 -6
package/dist/storyblok-react.js
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
-
(function(c,d){typeof exports=="object"&&typeof module!="undefined"?d(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],d):(c=typeof globalThis!="undefined"?globalThis:c||self,d(c.storyblokReact={},c.React))})(this,function(c,d){"use strict";var At=Object.defineProperty,Ot=Object.defineProperties;var xt=Object.getOwnPropertyDescriptors;var R=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable;var H=(c,d,g)=>d in c?At(c,d,{enumerable:!0,configurable:!0,writable:!0,value:g}):c[d]=g,b=(c,d)=>{for(var g in d||(d={}))B.call(d,g)&&H(c,g,d[g]);if(R)for(var g of R(d))D.call(d,g)&&H(c,g,d[g]);return c},j=(c,d)=>Ot(c,xt(d));var J=(c,d)=>{var g={};for(var f in c)B.call(c,f)&&d.indexOf(f)<0&&(g[f]=c[f]);if(c!=null&&R)for(var f of R(c))d.indexOf(f)<0&&D.call(c,f)&&(g[f]=c[f]);return g};function g(o){return o&&typeof o=="object"&&"default"in o?o:{default:o}}var f=g(d);let A=!1;const O=[],F=o=>new Promise((t,e)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}A?r():O.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=o,s.id="storyblok-javascript-bridge",s.onerror=r=>e(r),s.onload=r=>{O.forEach(i=>i()),A=!0,t(r)},document.getElementsByTagName("head")[0].appendChild(s)});var V=Object.defineProperty,Y=(o,t,e)=>t in o?V(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,u=(o,t,e)=>(Y(o,typeof t!="symbol"?t+"":t,e),e);function x(o){return!(o!==o||o===1/0||o===-1/0)}function G(o,t,e){if(!x(t))throw new TypeError("Expected `limit` to be a finite number");if(!x(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],i=0;const n=function(){i++;const a=setTimeout(function(){i--,s.length>0&&n(),r=r.filter(function(p){return p!==a})},e);r.indexOf(a)<0&&r.push(a);const l=s.shift();l.resolve(o.apply(l.self,l.args))},h=function(...a){const l=this;return new Promise(function(p,m){s.push({resolve:p,reject:m,args:a,self:l}),i<t&&n()})};return h.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},h}const Q=function(o,t){const e={};for(const s in o){const r=o[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},W=o=>o==="email",X=()=>({singleTag:"hr"}),Z=()=>({tag:"blockquote"}),K=()=>({tag:"ul"}),tt=o=>({tag:["pre",{tag:"code",attrs:o.attrs}]}),et=()=>({singleTag:"br"}),st=o=>({tag:`h${o.attrs.level}`}),rt=o=>({singleTag:[{tag:"img",attrs:Q(o.attrs,["src","alt","title"])}]}),ot=()=>({tag:"li"}),it=()=>({tag:"ol"}),nt=()=>({tag:"p"}),at=o=>({tag:[{tag:"span",attrs:{["data-type"]:"emoji",["data-name"]:o.attrs.name,emoji:o.attrs.emoji}}]}),lt=()=>({tag:"b"}),ct=()=>({tag:"strike"}),ht=()=>({tag:"u"}),ut=()=>({tag:"strong"}),dt=()=>({tag:"code"}),pt=()=>({tag:"i"}),gt=o=>{const t=b({},o.attrs),{linktype:e="url"}=o.attrs;if(W(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const s in t.custom)t[s]=t.custom[s];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},ft=o=>({tag:[{tag:"span",attrs:o.attrs}]}),mt=()=>({tag:"sub"}),yt=()=>({tag:"sup"}),bt=o=>({tag:[{tag:"span",attrs:o.attrs}]}),kt=o=>({tag:[{tag:"span",attrs:{style:`background-color:${o.attrs.color};`}}]}),vt=o=>({tag:[{tag:"span",attrs:{style:`background-color:${o.attrs.color}`}}]}),N={nodes:{horizontal_rule:X,blockquote:Z,bullet_list:K,code_block:tt,hard_break:et,heading:st,image:rt,list_item:ot,ordered_list:it,paragraph:nt,emoji:at},marks:{bold:lt,strike:ct,underline:ht,strong:ut,code:dt,italic:pt,link:gt,styled:ft,subscript:mt,superscript:yt,anchor:bt,highlight:kt,textStyle:vt}},wt=function(o){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},e=/[&<>"']/g,s=RegExp(e.source);return o&&s.test(o)?o.replace(e,r=>t[r]):o};class w{constructor(t){u(this,"marks"),u(this,"nodes"),t||(t=N),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t,e={optimizeImages:!1}){if(t&&t.content&&Array.isArray(t.content)){let s="";return t.content.forEach(r=>{s+=this.renderNode(r)}),e.optimizeImages?this.optimizeImages(s,e.optimizeImages):s}return console.warn("The render method must receive an object with a content field, which is an array"),""}optimizeImages(t,e){let s=0,r=0,i="",n="";typeof e!="boolean"&&(typeof e.width=="number"&&e.width>0&&(i+=`width="${e.width}" `,s=e.width),typeof e.height=="number"&&e.height>0&&(i+=`height="${e.height}" `,r=e.height),(e.loading==="lazy"||e.loading==="eager")&&(i+=`loading="${e.loading}" `),typeof e.class=="string"&&e.class.length>0&&(i+=`class="${e.class}" `),e.filters&&(typeof e.filters.blur=="number"&&e.filters.blur>=0&&e.filters.blur<=100&&(n+=`:blur(${e.filters.blur})`),typeof e.filters.brightness=="number"&&e.filters.brightness>=-100&&e.filters.brightness<=100&&(n+=`:brightness(${e.filters.brightness})`),e.filters.fill&&(e.filters.fill.match(/[0-9A-Fa-f]{6}/g)||e.filters.fill==="transparent")&&(n+=`:fill(${e.filters.fill})`),e.filters.format&&["webp","png","jpeg"].includes(e.filters.format)&&(n+=`:format(${e.filters.format})`),typeof e.filters.grayscale=="boolean"&&e.filters.grayscale&&(n+=":grayscale()"),typeof e.filters.quality=="number"&&e.filters.quality>=0&&e.filters.quality<=100&&(n+=`:quality(${e.filters.quality})`),e.filters.rotate&&[90,180,270].includes(e.filters.rotate)&&(n+=`:rotate(${e.filters.rotate})`),n.length>0&&(n="/filters"+n))),i.length>0&&(t=t.replace(/<img/g,`<img ${i.trim()}`));const h=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";return t=t.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${h}`),typeof e!="boolean"&&(e.sizes||e.srcset)&&(t=t.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var l,p;const m=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(m&&m.length>0){const k={srcset:(l=e.srcset)==null?void 0:l.map(y=>{if(typeof y=="number")return`//${m}/m/${y}x0${n} ${y}w`;if(typeof y=="object"&&y.length===2){let I=0,q=0;return typeof y[0]=="number"&&(I=y[0]),typeof y[1]=="number"&&(q=y[1]),`//${m}/m/${I}x${q}${n} ${I}w`}}).join(", "),sizes:(p=e.sizes)==null?void 0:p.map(y=>y).join(", ")};let C="";return k.srcset&&(C+=`srcset="${k.srcset}" `),k.sizes&&(C+=`sizes="${k.sizes}" `),a.replace(/<img/g,`<img ${C.trim()}`)}return a})),t}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const i=this.getMatchingMark(r);i&&e.push(this.renderOpeningTag(i.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(wt(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html?e.push(s.html):t.type==="emoji"&&e.push(this.renderEmoji(t)),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const i=this.getMatchingMark(r);i&&e.push(this.renderClosingTag(i.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let r=`<${s.tag}`;if(s.attrs)for(const i in s.attrs){const n=s.attrs[i];n!==null&&(r+=` ${i}="${n}"`)}return`${r}${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){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}renderEmoji(t){if(t.attrs.emoji)return t.attrs.emoji;const e=[{tag:"img",attrs:{src:t.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(e," /")}}class S{constructor(){u(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1),u(this,"getOptionsPage",(t,e=25,s=1)=>j(b({},t),{per_page:e,page:s})),u(this,"delay",t=>new Promise(e=>setTimeout(e,t))),u(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e)),u(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(i,n)=>n*r+t)}),u(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),u(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[]))}stringify(t,e,s){const r=[];for(const i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const n=t[i],h=s?"":encodeURIComponent(i);let a;typeof n=="object"?a=this.stringify(n,e?e+encodeURIComponent("["+h+"]"):h,Array.isArray(n)):a=(e?e+encodeURIComponent("["+h+"]"):h)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")}getRegionURL(t){const e="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(t){case"us":return s;case"cn":return r;default:return e}}}class $t{constructor(t){u(this,"baseURL"),u(this,"timeout"),u(this,"headers"),u(this,"responseInterceptor"),u(this,"fetch"),u(this,"ejectInterceptor"),u(this,"url"),u(this,"parameters"),this.baseURL=t.baseURL,this.headers=t.headers||new Headers,this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers=b({},e),s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const a=new S;e=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),i=new AbortController,{signal:n}=i;let h;this.timeout&&(h=setTimeout(()=>i.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:n});this.timeout&&clearTimeout(h);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((s,r)=>{if(e.test(`${t.status}`))return s(t);const i={message:new Error(t.statusText),status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};r(i)})}}let T={};const v={};class Tt{constructor(t,e){if(u(this,"client"),u(this,"maxRetries"),u(this,"throttle"),u(this,"accessToken"),u(this,"cache"),u(this,"helpers"),u(this,"resolveCounter"),u(this,"relations"),u(this,"links"),u(this,"richTextResolver"),u(this,"resolveNestedRelations"),!e){const i=new S().getRegionURL,n=t.https===!1?"http":"https";t.oauthToken?e=`${n}://${i(t.region)}/v1`:e=`${n}://${i(t.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((i,n)=>{t.headers&&t.headers[n]&&s.set(n,t.headers[n])});let r=5;t.oauthToken&&(s.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new w(t.richTextSchema):this.richTextResolver=new w,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries,this.throttle=G(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new S,this.resolveCounter=0,this.resolveNestedRelations=t.resolveNestedRelations||!0,this.client=new $t({baseURL:e,timeout:t.timeout||0,headers:s,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=v[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const i=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,i)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,i=`/${t}`,n=i.split("/"),h=s||n[n.length-1],a=1,l=await this.makeRequest(i,e,r,a),p=l.total?Math.ceil(l.total/r):1,m=await this.helpers.asyncMap(this.helpers.range(a,p),k=>this.makeRequest(i,e,r,k+1));return this.helpers.flatMap([l,...m],k=>Object.values(k.data[h]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e,s){const r=t[e];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}_insertRelations(t,e,s,r){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[r][t[e]]&&(t[e]=this._cleanCopy(this.relations[r][t[e]]));else if(t[e]&&t[e].constructor===Array){const i=[];t[e].forEach(n=>{this.relations[r][n]&&i.push(this._cleanCopy(this.relations[r][n]))}),t[e]=i}}}iterateTree(t,e,s){const r=i=>{if(i!=null){if(i.constructor===Array)for(let n=0;n<i.length;n++)r(i[n]);else if(i.constructor===Object){if(i._stopResolving)return;for(const n in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,n,e,s),this._insertLinks(i,n,s)),r(i[n])}}};r(t.content)}async resolveLinks(t,e,s){let r=[];if(t.link_uuids){const i=t.link_uuids.length,n=[],h=50;for(let a=0;a<i;a+=h){const l=Math.min(i,a+h);n.push(t.link_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:h,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.links;r.forEach(i=>{this.links[s][i.uuid]=j(b({},i),{_stopResolving:!0})})}async resolveRelations(t,e,s){let r=[];if(t.rel_uuids){const i=t.rel_uuids.length,n=[],h=50;for(let a=0;a<i;a+=h){const l=Math.min(i,a+h);n.push(t.rel_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:h,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]=j(b({},i),{_stopResolving:!0})})}async resolveStories(t,e,s){var r,i;let n=[];if(this.links[s]={},this.relations[s]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(n=e.resolve_relations.split(",")),await this.resolveRelations(t,e,s)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((r=t.links)!=null&&r.length||(i=t.link_uuids)!=null&&i.length)&&await this.resolveLinks(t,e,s),this.resolveNestedRelations)for(const h in this.relations[s])this.iterateTree(this.relations[s][h],n,s);t.story?this.iterateTree(t.story,n,s):t.stories.forEach(h=>{this.iterateTree(h,n,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(t,e,s){const r=this.helpers.stringify({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 n=await i.get(r);if(n)return Promise.resolve(n)}return new Promise((n,h)=>{try{(async()=>{var a;try{const l=await this.throttle("get",t,e);let p={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["per-page"]&&(p=Object.assign({},p,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),l.status!=200)return h(l);if(p.data.story||p.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(p.data,e,`${m}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await i.set(r,p),p.data.cv&&e.token&&(e.version=="draft"&&v[e.token]!=p.data.cv&&await this.flushCache(),v[e.token]=p.data.cv),n(p)}catch(l){return h(l)}})()}catch{}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return v}cacheVersion(){return v[this.accessToken]}setCacheVersion(t){this.accessToken&&(v[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(T[t])},getAll(){return Promise.resolve(T)},set(t,e){return T[t]=e,Promise.resolve(void 0)},flush(){return T={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this}}const _t=(o={})=>{const{apiOptions:t}=o;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 Tt(t)}},Rt=o=>{if(typeof o!="object"||typeof o._editable>"u")return{};const t=JSON.parse(o._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let E;const jt="https://app.storyblok.com/f/storyblok-v2-latest.js",_=(o,t,e={})=>{var s;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",i=+new URL((s=window.location)==null?void 0:s.href).searchParams.get("_storyblok")===o;if(!(!r||!i)){if(!o){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],n=>{n.action==="input"&&n.story.id===o?t(n.story):(n.action==="change"||n.action==="published")&&n.storyId===o&&window.location.reload()})})}},St=(o={})=>{var t,e;const{bridge:s,accessToken:r,use:i=[],apiOptions:n={},richText:h={}}=o;n.accessToken=n.accessToken||r;const a={bridge:s,apiOptions:n};let l={};i.forEach(m=>{l=b(b({},l),m(a))});const p=!(typeof window>"u")&&((e=(t=window.location)==null?void 0:t.search)==null?void 0:e.includes("_storyblok_tk"));return s!==!1&&p&&F(jt),E=new w(h.schema),h.resolver&&M(E,h.resolver),l},M=(o,t)=>{o.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})},Et=(o,t,e)=>{let s=e||E;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return o===""?"":o?(t&&(s=new w(t.schema),t.resolver&&M(s,t.resolver)),s.render(o)):(console.warn(`${o} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
|
1
|
+
(function(c,d){typeof exports=="object"&&typeof module!="undefined"?d(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],d):(c=typeof globalThis!="undefined"?globalThis:c||self,d(c.storyblokReact={},c.React))})(this,function(c,d){"use strict";var xt=Object.defineProperty,Ot=Object.defineProperties;var At=Object.getOwnPropertyDescriptors;var _=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable;var H=(c,d,g)=>d in c?xt(c,d,{enumerable:!0,configurable:!0,writable:!0,value:g}):c[d]=g,b=(c,d)=>{for(var g in d||(d={}))B.call(d,g)&&H(c,g,d[g]);if(_)for(var g of _(d))D.call(d,g)&&H(c,g,d[g]);return c},j=(c,d)=>Ot(c,At(d));var J=(c,d)=>{var g={};for(var f in c)B.call(c,f)&&d.indexOf(f)<0&&(g[f]=c[f]);if(c!=null&&_)for(var f of _(c))d.indexOf(f)<0&&D.call(c,f)&&(g[f]=c[f]);return g};function g(o){return o&&typeof o=="object"&&"default"in o?o:{default:o}}var f=g(d);let x=!1;const O=[],F=o=>new Promise((t,e)=>{if(typeof window>"u"||(window.storyblokRegisterEvent=r=>{if(window.location===window.parent.location){console.warn("You are not in Draft Mode or in the Visual Editor.");return}x?r():O.push(r)},document.getElementById("storyblok-javascript-bridge")))return;const s=document.createElement("script");s.async=!0,s.src=o,s.id="storyblok-javascript-bridge",s.onerror=r=>e(r),s.onload=r=>{O.forEach(i=>i()),x=!0,t(r)},document.getElementsByTagName("head")[0].appendChild(s)});var V=Object.defineProperty,Y=(o,t,e)=>t in o?V(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,u=(o,t,e)=>(Y(o,typeof t!="symbol"?t+"":t,e),e);function A(o){return!(o!==o||o===1/0||o===-1/0)}function W(o,t,e){if(!A(t))throw new TypeError("Expected `limit` to be a finite number");if(!A(e))throw new TypeError("Expected `interval` to be a finite number");const s=[];let r=[],i=0;const n=function(){i++;const a=setTimeout(function(){i--,s.length>0&&n(),r=r.filter(function(p){return p!==a})},e);r.indexOf(a)<0&&r.push(a);const l=s.shift();l.resolve(o.apply(l.self,l.args))},h=function(...a){const l=this;return new Promise(function(p,m){s.push({resolve:p,reject:m,args:a,self:l}),i<t&&n()})};return h.abort=function(){r.forEach(clearTimeout),r=[],s.forEach(function(a){a.reject(function(){Error.call(this,"Throttled function aborted"),this.name="AbortError"})}),s.length=0},h}const G=function(o,t){const e={};for(const s in o){const r=o[s];t.indexOf(s)>-1&&r!==null&&(e[s]=r)}return e},Q=o=>o==="email",X=()=>({singleTag:"hr"}),Z=()=>({tag:"blockquote"}),K=()=>({tag:"ul"}),tt=o=>({tag:["pre",{tag:"code",attrs:o.attrs}]}),et=()=>({singleTag:"br"}),st=o=>({tag:`h${o.attrs.level}`}),rt=o=>({singleTag:[{tag:"img",attrs:G(o.attrs,["src","alt","title"])}]}),ot=()=>({tag:"li"}),it=()=>({tag:"ol"}),nt=()=>({tag:"p"}),at=o=>({tag:[{tag:"span",attrs:{["data-type"]:"emoji",["data-name"]:o.attrs.name,emoji:o.attrs.emoji}}]}),lt=()=>({tag:"b"}),ct=()=>({tag:"strike"}),ht=()=>({tag:"u"}),ut=()=>({tag:"strong"}),dt=()=>({tag:"code"}),pt=()=>({tag:"i"}),gt=o=>{const t=b({},o.attrs),{linktype:e="url"}=o.attrs;if(Q(e)&&(t.href=`mailto:${t.href}`),t.anchor&&(t.href=`${t.href}#${t.anchor}`,delete t.anchor),t.custom){for(const s in t.custom)t[s]=t.custom[s];delete t.custom}return{tag:[{tag:"a",attrs:t}]}},ft=o=>({tag:[{tag:"span",attrs:o.attrs}]}),mt=()=>({tag:"sub"}),yt=()=>({tag:"sup"}),bt=o=>({tag:[{tag:"span",attrs:o.attrs}]}),kt=o=>({tag:[{tag:"span",attrs:{style:`background-color:${o.attrs.color};`}}]}),vt=o=>({tag:[{tag:"span",attrs:{style:`color:${o.attrs.color}`}}]}),N={nodes:{horizontal_rule:X,blockquote:Z,bullet_list:K,code_block:tt,hard_break:et,heading:st,image:rt,list_item:ot,ordered_list:it,paragraph:nt,emoji:at},marks:{bold:lt,strike:ct,underline:ht,strong:ut,code:dt,italic:pt,link:gt,styled:ft,subscript:mt,superscript:yt,anchor:bt,highlight:kt,textStyle:vt}},wt=function(o){const t={"&":"&","<":"<",">":">",'"':""","'":"'"},e=/[&<>"']/g,s=RegExp(e.source);return o&&s.test(o)?o.replace(e,r=>t[r]):o};class w{constructor(t){u(this,"marks"),u(this,"nodes"),t||(t=N),this.marks=t.marks||[],this.nodes=t.nodes||[]}addNode(t,e){this.nodes[t]=e}addMark(t,e){this.marks[t]=e}render(t,e={optimizeImages:!1}){if(t&&t.content&&Array.isArray(t.content)){let s="";return t.content.forEach(r=>{s+=this.renderNode(r)}),e.optimizeImages?this.optimizeImages(s,e.optimizeImages):s}return console.warn(`The render method must receive an Object with a "content" field.
|
|
2
|
+
The "content" field must be an array of nodes as the type ISbRichtext.
|
|
3
|
+
ISbRichtext:
|
|
4
|
+
content?: ISbRichtext[]
|
|
5
|
+
marks?: ISbRichtext[]
|
|
6
|
+
attrs?: any
|
|
7
|
+
text?: string
|
|
8
|
+
type: string
|
|
9
|
+
|
|
10
|
+
Example:
|
|
11
|
+
{
|
|
12
|
+
content: [
|
|
13
|
+
{
|
|
14
|
+
content: [
|
|
15
|
+
{
|
|
16
|
+
text: 'Hello World',
|
|
17
|
+
type: 'text'
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
type: 'paragraph'
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
type: 'doc'
|
|
24
|
+
}`),""}optimizeImages(t,e){let s=0,r=0,i="",n="";typeof e!="boolean"&&(typeof e.width=="number"&&e.width>0&&(i+=`width="${e.width}" `,s=e.width),typeof e.height=="number"&&e.height>0&&(i+=`height="${e.height}" `,r=e.height),(e.loading==="lazy"||e.loading==="eager")&&(i+=`loading="${e.loading}" `),typeof e.class=="string"&&e.class.length>0&&(i+=`class="${e.class}" `),e.filters&&(typeof e.filters.blur=="number"&&e.filters.blur>=0&&e.filters.blur<=100&&(n+=`:blur(${e.filters.blur})`),typeof e.filters.brightness=="number"&&e.filters.brightness>=-100&&e.filters.brightness<=100&&(n+=`:brightness(${e.filters.brightness})`),e.filters.fill&&(e.filters.fill.match(/[0-9A-Fa-f]{6}/g)||e.filters.fill==="transparent")&&(n+=`:fill(${e.filters.fill})`),e.filters.format&&["webp","png","jpeg"].includes(e.filters.format)&&(n+=`:format(${e.filters.format})`),typeof e.filters.grayscale=="boolean"&&e.filters.grayscale&&(n+=":grayscale()"),typeof e.filters.quality=="number"&&e.filters.quality>=0&&e.filters.quality<=100&&(n+=`:quality(${e.filters.quality})`),e.filters.rotate&&[90,180,270].includes(e.filters.rotate)&&(n+=`:rotate(${e.filters.rotate})`),n.length>0&&(n="/filters"+n))),i.length>0&&(t=t.replace(/<img/g,`<img ${i.trim()}`));const h=s>0||r>0||n.length>0?`${s}x${r}${n}`:"";return t=t.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g,`a.storyblok.com/f/$1/$2.$3/m/${h}`),typeof e!="boolean"&&(e.sizes||e.srcset)&&(t=t.replace(/<img.*?src=["|'](.*?)["|']/g,a=>{var l,p;const m=a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);if(m&&m.length>0){const k={srcset:(l=e.srcset)==null?void 0:l.map(y=>{if(typeof y=="number")return`//${m}/m/${y}x0${n} ${y}w`;if(typeof y=="object"&&y.length===2){let I=0,q=0;return typeof y[0]=="number"&&(I=y[0]),typeof y[1]=="number"&&(q=y[1]),`//${m}/m/${I}x${q}${n} ${I}w`}}).join(", "),sizes:(p=e.sizes)==null?void 0:p.map(y=>y).join(", ")};let C="";return k.srcset&&(C+=`srcset="${k.srcset}" `),k.sizes&&(C+=`sizes="${k.sizes}" `),a.replace(/<img/g,`<img ${C.trim()}`)}return a})),t}renderNode(t){const e=[];t.marks&&t.marks.forEach(r=>{const i=this.getMatchingMark(r);i&&e.push(this.renderOpeningTag(i.tag))});const s=this.getMatchingNode(t);return s&&s.tag&&e.push(this.renderOpeningTag(s.tag)),t.content?t.content.forEach(r=>{e.push(this.renderNode(r))}):t.text?e.push(wt(t.text)):s&&s.singleTag?e.push(this.renderTag(s.singleTag," /")):s&&s.html?e.push(s.html):t.type==="emoji"&&e.push(this.renderEmoji(t)),s&&s.tag&&e.push(this.renderClosingTag(s.tag)),t.marks&&t.marks.slice(0).reverse().forEach(r=>{const i=this.getMatchingMark(r);i&&e.push(this.renderClosingTag(i.tag))}),e.join("")}renderTag(t,e){return t.constructor===String?`<${t}${e}>`:t.map(s=>{if(s.constructor===String)return`<${s}${e}>`;{let r=`<${s.tag}`;if(s.attrs)for(const i in s.attrs){const n=s.attrs[i];n!==null&&(r+=` ${i}="${n}"`)}return`${r}${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){const e=this.nodes[t.type];if(typeof e=="function")return e(t)}getMatchingMark(t){const e=this.marks[t.type];if(typeof e=="function")return e(t)}renderEmoji(t){if(t.attrs.emoji)return t.attrs.emoji;const e=[{tag:"img",attrs:{src:t.attrs.fallbackImage,draggable:"false",loading:"lazy",align:"absmiddle"}}];return this.renderTag(e," /")}}class S{constructor(){u(this,"isCDNUrl",(t="")=>t.indexOf("/cdn/")>-1),u(this,"getOptionsPage",(t,e=25,s=1)=>j(b({},t),{per_page:e,page:s})),u(this,"delay",t=>new Promise(e=>setTimeout(e,t))),u(this,"arrayFrom",(t=0,e)=>[...Array(t)].map(e)),u(this,"range",(t=0,e=t)=>{const s=Math.abs(e-t)||0,r=t<e?1:-1;return this.arrayFrom(s,(i,n)=>n*r+t)}),u(this,"asyncMap",async(t,e)=>Promise.all(t.map(e))),u(this,"flatMap",(t=[],e)=>t.map(e).reduce((s,r)=>[...s,...r],[]))}stringify(t,e,s){const r=[];for(const i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const n=t[i],h=s?"":encodeURIComponent(i);let a;typeof n=="object"?a=this.stringify(n,e?e+encodeURIComponent("["+h+"]"):h,Array.isArray(n)):a=(e?e+encodeURIComponent("["+h+"]"):h)+"="+encodeURIComponent(n),r.push(a)}return r.join("&")}getRegionURL(t){const e="api.storyblok.com",s="api-us.storyblok.com",r="app.storyblokchina.cn";switch(t){case"us":return s;case"cn":return r;default:return e}}}class $t{constructor(t){u(this,"baseURL"),u(this,"timeout"),u(this,"headers"),u(this,"responseInterceptor"),u(this,"fetch"),u(this,"ejectInterceptor"),u(this,"url"),u(this,"parameters"),this.baseURL=t.baseURL,this.headers=t.headers||new Headers,this.timeout=t!=null&&t.timeout?t.timeout*1e3:0,this.responseInterceptor=t.responseInterceptor,this.fetch=(...e)=>t.fetch?t.fetch(...e):fetch(...e),this.ejectInterceptor=!1,this.url="",this.parameters={}}get(t,e){return this.url=t,this.parameters=e,this._methodHandler("get")}post(t,e){return this.url=t,this.parameters=e,this._methodHandler("post")}put(t,e){return this.url=t,this.parameters=e,this._methodHandler("put")}delete(t,e){return this.url=t,this.parameters=e,this._methodHandler("delete")}async _responseHandler(t){const e=[],s={data:{},headers:{},status:0,statusText:""};t.status!==204&&await t.json().then(r=>{s.data=r});for(const r of t.headers.entries())e[r[0]]=r[1];return s.headers=b({},e),s.status=t.status,s.statusText=t.statusText,s}async _methodHandler(t){let e=`${this.baseURL}${this.url}`,s=null;if(t==="get"){const a=new S;e=`${this.baseURL}${this.url}?${a.stringify(this.parameters)}`}else s=JSON.stringify(this.parameters);const r=new URL(e),i=new AbortController,{signal:n}=i;let h;this.timeout&&(h=setTimeout(()=>i.abort(),this.timeout));try{const a=await this.fetch(`${r}`,{method:t,headers:this.headers,body:s,signal:n});this.timeout&&clearTimeout(h);const l=await this._responseHandler(a);return this.responseInterceptor&&!this.ejectInterceptor?this._statusHandler(this.responseInterceptor(l)):this._statusHandler(l)}catch(a){return{message:a}}}eject(){this.ejectInterceptor=!0}_statusHandler(t){const e=/20[0-6]/g;return new Promise((s,r)=>{if(e.test(`${t.status}`))return s(t);const i={message:new Error(t.statusText),status:t.status,response:Array.isArray(t.data)?t.data[0]:t.data.error||t.data.slug};r(i)})}}let T={};const v={};class Tt{constructor(t,e){if(u(this,"client"),u(this,"maxRetries"),u(this,"throttle"),u(this,"accessToken"),u(this,"cache"),u(this,"helpers"),u(this,"resolveCounter"),u(this,"relations"),u(this,"links"),u(this,"richTextResolver"),u(this,"resolveNestedRelations"),!e){const i=new S().getRegionURL,n=t.https===!1?"http":"https";t.oauthToken?e=`${n}://${i(t.region)}/v1`:e=`${n}://${i(t.region)}/v2`}const s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),s.forEach((i,n)=>{t.headers&&t.headers[n]&&s.set(n,t.headers[n])});let r=5;t.oauthToken&&(s.set("Authorization",t.oauthToken),r=3),t.rateLimit&&(r=t.rateLimit),t.richTextSchema?this.richTextResolver=new w(t.richTextSchema):this.richTextResolver=new w,t.componentResolver&&this.setComponentResolver(t.componentResolver),this.maxRetries=t.maxRetries||5,this.throttle=W(this.throttledRequest,r,1e3),this.accessToken=t.accessToken||"",this.relations={},this.links={},this.cache=t.cache||{clear:"manual"},this.helpers=new S,this.resolveCounter=0,this.resolveNestedRelations=t.resolveNestedRelations||!0,this.client=new $t({baseURL:e,timeout:t.timeout||0,headers:s,responseInterceptor:t.responseInterceptor,fetch:t.fetch})}setComponentResolver(t){this.richTextResolver.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})}parseParams(t){return t.version||(t.version="published"),t.token||(t.token=this.getToken()),t.cv||(t.cv=v[t.token]),Array.isArray(t.resolve_relations)&&(t.resolve_relations=t.resolve_relations.join(",")),t}factoryParamOptions(t,e){return this.helpers.isCDNUrl(t)?this.parseParams(e):e}makeRequest(t,e,s,r){const i=this.factoryParamOptions(t,this.helpers.getOptionsPage(e,s,r));return this.cacheResponse(t,i)}get(t,e){e||(e={});const s=`/${t}`,r=this.factoryParamOptions(s,e);return this.cacheResponse(s,r)}async getAll(t,e,s){const r=(e==null?void 0:e.per_page)||25,i=`/${t}`,n=i.split("/"),h=s||n[n.length-1],a=1,l=await this.makeRequest(i,e,r,a),p=l.total?Math.ceil(l.total/r):1,m=await this.helpers.asyncMap(this.helpers.range(a,p),k=>this.makeRequest(i,e,r,k+1));return this.helpers.flatMap([l,...m],k=>Object.values(k.data[h]))}post(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("post",s,e))}put(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("put",s,e))}delete(t,e){const s=`/${t}`;return Promise.resolve(this.throttle("delete",s,e))}getStories(t){return this.get("cdn/stories",t)}getStory(t,e){return this.get(`cdn/stories/${t}`,e)}getToken(){return this.accessToken}ejectInterceptor(){this.client.eject()}_cleanCopy(t){return JSON.parse(JSON.stringify(t))}_insertLinks(t,e,s){const r=t[e];r&&r.fieldtype=="multilink"&&r.linktype=="story"&&typeof r.id=="string"&&this.links[s][r.id]?r.story=this._cleanCopy(this.links[s][r.id]):r&&r.linktype==="story"&&typeof r.uuid=="string"&&this.links[s][r.uuid]&&(r.story=this._cleanCopy(this.links[s][r.uuid]))}_insertRelations(t,e,s,r){if(s.indexOf(`${t.component}.${e}`)>-1){if(typeof t[e]=="string")this.relations[r][t[e]]&&(t[e]=this._cleanCopy(this.relations[r][t[e]]));else if(t[e]&&t[e].constructor===Array){const i=[];t[e].forEach(n=>{this.relations[r][n]&&i.push(this._cleanCopy(this.relations[r][n]))}),t[e]=i}}}iterateTree(t,e,s){const r=i=>{if(i!=null){if(i.constructor===Array)for(let n=0;n<i.length;n++)r(i[n]);else if(i.constructor===Object){if(i._stopResolving)return;for(const n in i)(i.component&&i._uid||i.type==="link")&&(this._insertRelations(i,n,e,s),this._insertLinks(i,n,s)),r(i[n])}}};r(t.content)}async resolveLinks(t,e,s){let r=[];if(t.link_uuids){const i=t.link_uuids.length,n=[],h=50;for(let a=0;a<i;a+=h){const l=Math.min(i,a+h);n.push(t.link_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:h,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.links;r.forEach(i=>{this.links[s][i.uuid]=j(b({},i),{_stopResolving:!0})})}async resolveRelations(t,e,s){let r=[];if(t.rel_uuids){const i=t.rel_uuids.length,n=[],h=50;for(let a=0;a<i;a+=h){const l=Math.min(i,a+h);n.push(t.rel_uuids.slice(a,l))}for(let a=0;a<n.length;a++)(await this.getStories({per_page:h,language:e.language,version:e.version,by_uuids:n[a].join(",")})).data.stories.forEach(l=>{r.push(l)})}else r=t.rels;r&&r.length>0&&r.forEach(i=>{this.relations[s][i.uuid]=j(b({},i),{_stopResolving:!0})})}async resolveStories(t,e,s){var r,i;let n=[];if(this.links[s]={},this.relations[s]={},typeof e.resolve_relations<"u"&&e.resolve_relations.length>0&&(typeof e.resolve_relations=="string"&&(n=e.resolve_relations.split(",")),await this.resolveRelations(t,e,s)),e.resolve_links&&["1","story","url"].indexOf(e.resolve_links)>-1&&((r=t.links)!=null&&r.length||(i=t.link_uuids)!=null&&i.length)&&await this.resolveLinks(t,e,s),this.resolveNestedRelations)for(const h in this.relations[s])this.iterateTree(this.relations[s][h],n,s);t.story?this.iterateTree(t.story,n,s):t.stories.forEach(h=>{this.iterateTree(h,n,s)}),delete this.links[s],delete this.relations[s]}async cacheResponse(t,e,s){const r=this.helpers.stringify({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 n=await i.get(r);if(n)return Promise.resolve(n)}return new Promise((n,h)=>{try{(async()=>{var a;try{const l=await this.throttle("get",t,e);let p={data:l.data,headers:l.headers};if((a=l.headers)!=null&&a["per-page"]&&(p=Object.assign({},p,{perPage:l.headers["per-page"]?parseInt(l.headers["per-page"]):0,total:l.headers["per-page"]?parseInt(l.headers.total):0})),l.status!=200)return h(l);if(p.data.story||p.data.stories){const m=this.resolveCounter=++this.resolveCounter%1e3;await this.resolveStories(p.data,e,`${m}`)}return e.version==="published"&&t!="/cdn/spaces/me"&&await i.set(r,p),p.data.cv&&e.token&&(e.version=="draft"&&v[e.token]!=p.data.cv&&await this.flushCache(),v[e.token]=p.data.cv),n(p)}catch(l){return h(l)}})()}catch{}})}throttledRequest(t,e,s){return this.client[t](e,s)}cacheVersions(){return v}cacheVersion(){return v[this.accessToken]}setCacheVersion(t){this.accessToken&&(v[this.accessToken]=t)}cacheProvider(){switch(this.cache.type){case"memory":return{get(t){return Promise.resolve(T[t])},getAll(){return Promise.resolve(T)},set(t,e){return T[t]=e,Promise.resolve(void 0)},flush(){return T={},Promise.resolve(void 0)}};case"custom":if(this.cache.custom)return this.cache.custom;default:return{get(){return Promise.resolve(void 0)},getAll(){return Promise.resolve(void 0)},set(){return Promise.resolve(void 0)},flush(){return Promise.resolve(void 0)}}}}async flushCache(){return await this.cacheProvider().flush(),this}}const Rt=(o={})=>{const{apiOptions:t}=o;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 Tt(t)}},_t=o=>{if(typeof o!="object"||typeof o._editable>"u")return{};const t=JSON.parse(o._editable.replace(/^<!--#storyblok#/,"").replace(/-->$/,""));return{"data-blok-c":JSON.stringify(t),"data-blok-uid":t.id+"-"+t.uid}};let E;const jt="https://app.storyblok.com/f/storyblok-v2-latest.js",R=(o,t,e={})=>{var s;const r=!(typeof window>"u")&&typeof window.storyblokRegisterEvent<"u",i=+new URL((s=window.location)==null?void 0:s.href).searchParams.get("_storyblok")===o;if(!(!r||!i)){if(!o){console.warn("Story ID is not defined. Please provide a valid ID.");return}window.storyblokRegisterEvent(()=>{new window.StoryblokBridge(e).on(["input","published","change"],n=>{n.action==="input"&&n.story.id===o?t(n.story):(n.action==="change"||n.action==="published")&&n.storyId===o&&window.location.reload()})})}},St=(o={})=>{var t,e;const{bridge:s,accessToken:r,use:i=[],apiOptions:n={},richText:h={}}=o;n.accessToken=n.accessToken||r;const a={bridge:s,apiOptions:n};let l={};i.forEach(m=>{l=b(b({},l),m(a))});const p=!(typeof window>"u")&&((e=(t=window.location)==null?void 0:t.search)==null?void 0:e.includes("_storyblok_tk"));return s!==!1&&p&&F(jt),E=new w(h.schema),h.resolver&&M(E,h.resolver),l},M=(o,t)=>{o.addNode("blok",e=>{let s="";return e.attrs.body.forEach(r=>{s+=t(r.component,r)}),{html:s}})},Et=(o,t,e)=>{let s=e||E;if(!s){console.error("Please initialize the Storyblok SDK before calling the renderRichText function");return}return o===""?"":o?(t&&(s=new w(t.schema),t.resolver&&M(s,t.resolver)),s.render(o)):(console.warn(`${o} is not a valid Richtext object. This might be because the value of the richtext field is empty.
|
|
2
25
|
|
|
3
|
-
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},L=d.forwardRef((s,e)=>{var r=s,{blok:o}=r,t=J(r,["blok"]);if(!o)return console.error("Please provide a 'blok' property to the StoryblokComponent"),f.default.createElement("div",null,"Please provide a blok property to the StoryblokComponent");const i=U(o.component);return i?f.default.createElement(i,b({ref:e,blok:o},t)):f.default.createElement("div",null)});L.displayName="StoryblokComponent";const Pt=(o,t={},e={})=>{let[s,r]=d.useState({});if(!$)return console.error("You can't use useStoryblok if you're not loading apiPlugin."),null;const i=typeof window!="undefined"&&typeof window.storyblokRegisterEvent!="undefined";return d.useEffect(()=>{async function n(){const{data:h}=await $.get(`cdn/stories/${o}`,t);r(h.story),i&&h.story.id&&
|
|
26
|
+
For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`),"")},L=d.forwardRef((s,e)=>{var r=s,{blok:o}=r,t=J(r,["blok"]);if(!o)return console.error("Please provide a 'blok' property to the StoryblokComponent"),f.default.createElement("div",null,"Please provide a blok property to the StoryblokComponent");const i=U(o.component);return i?f.default.createElement(i,b({ref:e,blok:o},t)):f.default.createElement("div",null)});L.displayName="StoryblokComponent";const Pt=(o,t={},e={})=>{let[s,r]=d.useState({});if(!$)return console.error("You can't use useStoryblok if you're not loading apiPlugin."),null;const i=typeof window!="undefined"&&typeof window.storyblokRegisterEvent!="undefined";return d.useEffect(()=>{async function n(){const{data:h}=await $.get(`cdn/stories/${o}`,t);r(h.story),i&&h.story.id&&R(h.story.id,a=>r(a),e)}n()},[o,JSON.stringify(t)]),s},Ct=(o=null,t={})=>{let[e,s]=d.useState(o);return!(typeof window!="undefined"&&typeof window.storyblokRegisterEvent!="undefined")||!o?o:(d.useEffect(()=>{s(o),R(e.id,i=>s(i),t)},[o]),e)};let $=null;const z=()=>($||console.error("You can't use getStoryblokApi if you're not loading apiPlugin."),$);let P={};const U=o=>P[o]?P[o]:(console.error(`Component ${o} doesn't exist.`),!1),It=(o={})=>{const{storyblokApi:t}=St(o);$=t,P=o.components};c.RichTextResolver=w,c.RichTextSchema=N,c.StoryblokComponent=L,c.apiPlugin=Rt,c.getComponent=U,c.getStoryblokApi=z,c.registerStoryblokBridge=R,c.renderRichText=Et,c.storyblokEditable=_t,c.storyblokInit=It,c.useStoryblok=Pt,c.useStoryblokApi=z,c.useStoryblokBridge=R,c.useStoryblokState=Ct,Object.defineProperties(c,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
package/dist/storyblok-react.mjs
CHANGED
|
@@ -30,22 +30,22 @@ var __objRest = (source, exclude) => {
|
|
|
30
30
|
return target;
|
|
31
31
|
};
|
|
32
32
|
import React, { forwardRef, useState, useEffect } from "react";
|
|
33
|
-
let
|
|
34
|
-
const
|
|
33
|
+
let R = false;
|
|
34
|
+
const T = [], j = (n) => new Promise((e, t) => {
|
|
35
35
|
if (typeof window > "u" || (window.storyblokRegisterEvent = (r) => {
|
|
36
36
|
if (window.location === window.parent.location) {
|
|
37
37
|
console.warn("You are not in Draft Mode or in the Visual Editor.");
|
|
38
38
|
return;
|
|
39
39
|
}
|
|
40
|
-
|
|
40
|
+
R ? r() : T.push(r);
|
|
41
41
|
}, document.getElementById("storyblok-javascript-bridge")))
|
|
42
42
|
return;
|
|
43
43
|
const s = document.createElement("script");
|
|
44
44
|
s.async = true, s.src = n, s.id = "storyblok-javascript-bridge", s.onerror = (r) => t(r), s.onload = (r) => {
|
|
45
|
-
|
|
45
|
+
T.forEach((i) => i()), R = true, e(r);
|
|
46
46
|
}, document.getElementsByTagName("head")[0].appendChild(s);
|
|
47
47
|
});
|
|
48
|
-
var
|
|
48
|
+
var I = Object.defineProperty, P = (n, e, t) => e in n ? I(n, e, { enumerable: true, configurable: true, writable: true, value: t }) : n[e] = t, h = (n, e, t) => (P(n, typeof e != "symbol" ? e + "" : e, t), t);
|
|
49
49
|
function _(n) {
|
|
50
50
|
return !(n !== n || n === 1 / 0 || n === -1 / 0);
|
|
51
51
|
}
|
|
@@ -142,11 +142,11 @@ const C = function(n, e) {
|
|
|
142
142
|
tag: "u"
|
|
143
143
|
}), K = () => ({
|
|
144
144
|
tag: "strong"
|
|
145
|
-
}),
|
|
145
|
+
}), W = () => ({
|
|
146
146
|
tag: "code"
|
|
147
|
-
}),
|
|
147
|
+
}), G = () => ({
|
|
148
148
|
tag: "i"
|
|
149
|
-
}),
|
|
149
|
+
}), Q = (n) => {
|
|
150
150
|
const e = __spreadValues({}, n.attrs), { linktype: t = "url" } = n.attrs;
|
|
151
151
|
if (O(t) && (e.href = `mailto:${e.href}`), e.anchor && (e.href = `${e.href}#${e.anchor}`, delete e.anchor), e.custom) {
|
|
152
152
|
for (const s in e.custom)
|
|
@@ -193,7 +193,7 @@ const C = function(n, e) {
|
|
|
193
193
|
{
|
|
194
194
|
tag: "span",
|
|
195
195
|
attrs: {
|
|
196
|
-
style: `
|
|
196
|
+
style: `color:${n.attrs.color}`
|
|
197
197
|
}
|
|
198
198
|
}
|
|
199
199
|
]
|
|
@@ -216,9 +216,9 @@ const C = function(n, e) {
|
|
|
216
216
|
strike: V,
|
|
217
217
|
underline: Y,
|
|
218
218
|
strong: K,
|
|
219
|
-
code:
|
|
220
|
-
italic:
|
|
221
|
-
link:
|
|
219
|
+
code: W,
|
|
220
|
+
italic: G,
|
|
221
|
+
link: Q,
|
|
222
222
|
styled: X,
|
|
223
223
|
subscript: Z,
|
|
224
224
|
superscript: ee,
|
|
@@ -253,7 +253,30 @@ class y {
|
|
|
253
253
|
s += this.renderNode(r);
|
|
254
254
|
}), t.optimizeImages ? this.optimizeImages(s, t.optimizeImages) : s;
|
|
255
255
|
}
|
|
256
|
-
return console.warn(
|
|
256
|
+
return console.warn(`The render method must receive an Object with a "content" field.
|
|
257
|
+
The "content" field must be an array of nodes as the type ISbRichtext.
|
|
258
|
+
ISbRichtext:
|
|
259
|
+
content?: ISbRichtext[]
|
|
260
|
+
marks?: ISbRichtext[]
|
|
261
|
+
attrs?: any
|
|
262
|
+
text?: string
|
|
263
|
+
type: string
|
|
264
|
+
|
|
265
|
+
Example:
|
|
266
|
+
{
|
|
267
|
+
content: [
|
|
268
|
+
{
|
|
269
|
+
content: [
|
|
270
|
+
{
|
|
271
|
+
text: 'Hello World',
|
|
272
|
+
type: 'text'
|
|
273
|
+
}
|
|
274
|
+
],
|
|
275
|
+
type: 'paragraph'
|
|
276
|
+
}
|
|
277
|
+
],
|
|
278
|
+
type: 'doc'
|
|
279
|
+
}`), "";
|
|
257
280
|
}
|
|
258
281
|
optimizeImages(e, t) {
|
|
259
282
|
let s = 0, r = 0, i = "", o = "";
|
|
@@ -461,7 +484,7 @@ class ae {
|
|
|
461
484
|
e.headers && e.headers[o] && s.set(o, e.headers[o]);
|
|
462
485
|
});
|
|
463
486
|
let r = 5;
|
|
464
|
-
e.oauthToken && (s.set("Authorization", e.oauthToken), r = 3), e.rateLimit && (r = e.rateLimit), e.richTextSchema ? this.richTextResolver = new y(e.richTextSchema) : this.richTextResolver = new y(), e.componentResolver && this.setComponentResolver(e.componentResolver), this.maxRetries = e.maxRetries, this.throttle = S(this.throttledRequest, r, 1e3), this.accessToken = e.accessToken || "", this.relations = {}, this.links = {}, this.cache = e.cache || { clear: "manual" }, this.helpers = new v(), this.resolveCounter = 0, this.resolveNestedRelations = e.resolveNestedRelations || true, this.client = new ne({
|
|
487
|
+
e.oauthToken && (s.set("Authorization", e.oauthToken), r = 3), e.rateLimit && (r = e.rateLimit), e.richTextSchema ? this.richTextResolver = new y(e.richTextSchema) : this.richTextResolver = new y(), e.componentResolver && this.setComponentResolver(e.componentResolver), this.maxRetries = e.maxRetries || 5, this.throttle = S(this.throttledRequest, r, 1e3), this.accessToken = e.accessToken || "", this.relations = {}, this.links = {}, this.cache = e.cache || { clear: "manual" }, this.helpers = new v(), this.resolveCounter = 0, this.resolveNestedRelations = e.resolveNestedRelations || true, this.client = new ne({
|
|
465
488
|
baseURL: t,
|
|
466
489
|
timeout: e.timeout || 0,
|
|
467
490
|
headers: s,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storyblok/react",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.19",
|
|
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",
|
|
@@ -24,19 +24,19 @@
|
|
|
24
24
|
"prepublishOnly": "npm run build && cp ../README.md ./"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@storyblok/js": "^2.1.
|
|
27
|
+
"@storyblok/js": "^2.1.4"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@babel/core": "^7.21.
|
|
31
|
-
"@babel/preset-env": "^7.21.
|
|
30
|
+
"@babel/core": "^7.21.8",
|
|
31
|
+
"@babel/preset-env": "^7.21.5",
|
|
32
32
|
"@cypress/react": "^5.12.5",
|
|
33
33
|
"@cypress/vite-dev-server": "^2.2.3",
|
|
34
34
|
"@tsconfig/recommended": "^1.0.2",
|
|
35
|
-
"@types/react": "18.2.
|
|
35
|
+
"@types/react": "18.2.6",
|
|
36
36
|
"@vitejs/plugin-react": "^1.3.2",
|
|
37
37
|
"babel-jest": "^29.5.0",
|
|
38
38
|
"cypress": "^9.7.0",
|
|
39
|
-
"eslint-plugin-cypress": "^2.13.
|
|
39
|
+
"eslint-plugin-cypress": "^2.13.3",
|
|
40
40
|
"eslint-plugin-jest": "^27.2.1",
|
|
41
41
|
"jest": "^29.5.0",
|
|
42
42
|
"react": "^18.2.0",
|