@storyblok/react 2.0.19 → 2.1.0

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.
@@ -1,862 +1,52 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target[prop] = source[prop];
29
- }
30
- return target;
31
- };
32
- import React, { forwardRef, useState, useEffect } from "react";
33
- let R = false;
34
- const T = [], j = (n) => new Promise((e, t) => {
35
- if (typeof window > "u" || (window.storyblokRegisterEvent = (r) => {
36
- if (window.location === window.parent.location) {
37
- console.warn("You are not in Draft Mode or in the Visual Editor.");
38
- return;
39
- }
40
- R ? r() : T.push(r);
41
- }, document.getElementById("storyblok-javascript-bridge")))
42
- return;
43
- const s = document.createElement("script");
44
- s.async = true, s.src = n, s.id = "storyblok-javascript-bridge", s.onerror = (r) => t(r), s.onload = (r) => {
45
- T.forEach((i) => i()), R = true, e(r);
46
- }, document.getElementsByTagName("head")[0].appendChild(s);
47
- });
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
- function _(n) {
50
- return !(n !== n || n === 1 / 0 || n === -1 / 0);
51
- }
52
- function S(n, e, t) {
53
- if (!_(e))
54
- throw new TypeError("Expected `limit` to be a finite number");
55
- if (!_(t))
56
- throw new TypeError("Expected `interval` to be a finite number");
57
- const s = [];
58
- let r = [], i = 0;
59
- const o = function() {
60
- i++;
61
- const a = setTimeout(function() {
62
- i--, s.length > 0 && o(), r = r.filter(function(u) {
63
- return u !== a;
64
- });
65
- }, t);
66
- r.indexOf(a) < 0 && r.push(a);
67
- const l = s.shift();
68
- l.resolve(n.apply(l.self, l.args));
69
- }, c = function(...a) {
70
- const l = this;
71
- return new Promise(function(u, d) {
72
- s.push({
73
- resolve: u,
74
- reject: d,
75
- args: a,
76
- self: l
77
- }), i < e && o();
78
- });
79
- };
80
- return c.abort = function() {
81
- r.forEach(clearTimeout), r = [], s.forEach(function(a) {
82
- a.reject(function() {
83
- Error.call(this, "Throttled function aborted"), this.name = "AbortError";
84
- });
85
- }), s.length = 0;
86
- }, c;
87
- }
88
- const C = function(n, e) {
89
- const t = {};
90
- for (const s in n) {
91
- const r = n[s];
92
- e.indexOf(s) > -1 && r !== null && (t[s] = r);
93
- }
94
- return t;
95
- }, O = (n) => n === "email", A = () => ({
96
- singleTag: "hr"
97
- }), N = () => ({
98
- tag: "blockquote"
99
- }), L = () => ({
100
- tag: "ul"
101
- }), M = (n) => ({
102
- tag: [
103
- "pre",
104
- {
105
- tag: "code",
106
- attrs: n.attrs
107
- }
108
- ]
109
- }), z = () => ({
110
- singleTag: "br"
111
- }), U = (n) => ({
112
- tag: `h${n.attrs.level}`
113
- }), q = (n) => ({
114
- singleTag: [
115
- {
116
- tag: "img",
117
- attrs: C(n.attrs, ["src", "alt", "title"])
118
- }
119
- ]
120
- }), H = () => ({
121
- tag: "li"
122
- }), B = () => ({
123
- tag: "ol"
124
- }), D = () => ({
125
- tag: "p"
126
- }), F = (n) => ({
127
- tag: [
128
- {
129
- tag: "span",
130
- attrs: {
131
- ["data-type"]: "emoji",
132
- ["data-name"]: n.attrs.name,
133
- emoji: n.attrs.emoji
134
- }
135
- }
136
- ]
137
- }), J = () => ({
138
- tag: "b"
139
- }), V = () => ({
140
- tag: "strike"
141
- }), Y = () => ({
142
- tag: "u"
143
- }), K = () => ({
144
- tag: "strong"
145
- }), W = () => ({
146
- tag: "code"
147
- }), G = () => ({
148
- tag: "i"
149
- }), Q = (n) => {
150
- const e = __spreadValues({}, n.attrs), { linktype: t = "url" } = n.attrs;
151
- if (O(t) && (e.href = `mailto:${e.href}`), e.anchor && (e.href = `${e.href}#${e.anchor}`, delete e.anchor), e.custom) {
152
- for (const s in e.custom)
153
- e[s] = e.custom[s];
154
- delete e.custom;
155
- }
156
- return {
157
- tag: [
158
- {
159
- tag: "a",
160
- attrs: e
161
- }
162
- ]
163
- };
164
- }, X = (n) => ({
165
- tag: [
166
- {
167
- tag: "span",
168
- attrs: n.attrs
169
- }
170
- ]
171
- }), Z = () => ({
172
- tag: "sub"
173
- }), ee = () => ({
174
- tag: "sup"
175
- }), te = (n) => ({
176
- tag: [
177
- {
178
- tag: "span",
179
- attrs: n.attrs
180
- }
181
- ]
182
- }), se = (n) => ({
183
- tag: [
184
- {
185
- tag: "span",
186
- attrs: {
187
- style: `background-color:${n.attrs.color};`
188
- }
189
- }
190
- ]
191
- }), re = (n) => ({
192
- tag: [
193
- {
194
- tag: "span",
195
- attrs: {
196
- style: `color:${n.attrs.color}`
197
- }
198
- }
199
- ]
200
- }), ie = {
201
- nodes: {
202
- horizontal_rule: A,
203
- blockquote: N,
204
- bullet_list: L,
205
- code_block: M,
206
- hard_break: z,
207
- heading: U,
208
- image: q,
209
- list_item: H,
210
- ordered_list: B,
211
- paragraph: D,
212
- emoji: F
213
- },
214
- marks: {
215
- bold: J,
216
- strike: V,
217
- underline: Y,
218
- strong: K,
219
- code: W,
220
- italic: G,
221
- link: Q,
222
- styled: X,
223
- subscript: Z,
224
- superscript: ee,
225
- anchor: te,
226
- highlight: se,
227
- textStyle: re
228
- }
229
- }, oe = function(n) {
230
- const e = {
231
- "&": "&amp;",
232
- "<": "&lt;",
233
- ">": "&gt;",
234
- '"': "&quot;",
235
- "'": "&#39;"
236
- }, t = /[&<>"']/g, s = RegExp(t.source);
237
- return n && s.test(n) ? n.replace(t, (r) => e[r]) : n;
238
- };
239
- class y {
240
- constructor(e) {
241
- h(this, "marks"), h(this, "nodes"), e || (e = ie), this.marks = e.marks || [], this.nodes = e.nodes || [];
242
- }
243
- addNode(e, t) {
244
- this.nodes[e] = t;
245
- }
246
- addMark(e, t) {
247
- this.marks[e] = t;
248
- }
249
- render(e, t = { optimizeImages: false }) {
250
- if (e && e.content && Array.isArray(e.content)) {
251
- let s = "";
252
- return e.content.forEach((r) => {
253
- s += this.renderNode(r);
254
- }), t.optimizeImages ? this.optimizeImages(s, t.optimizeImages) : s;
255
- }
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
- }`), "";
280
- }
281
- optimizeImages(e, t) {
282
- let s = 0, r = 0, i = "", o = "";
283
- typeof t != "boolean" && (typeof t.width == "number" && t.width > 0 && (i += `width="${t.width}" `, s = t.width), typeof t.height == "number" && t.height > 0 && (i += `height="${t.height}" `, r = t.height), (t.loading === "lazy" || t.loading === "eager") && (i += `loading="${t.loading}" `), typeof t.class == "string" && t.class.length > 0 && (i += `class="${t.class}" `), t.filters && (typeof t.filters.blur == "number" && t.filters.blur >= 0 && t.filters.blur <= 100 && (o += `:blur(${t.filters.blur})`), typeof t.filters.brightness == "number" && t.filters.brightness >= -100 && t.filters.brightness <= 100 && (o += `:brightness(${t.filters.brightness})`), t.filters.fill && (t.filters.fill.match(/[0-9A-Fa-f]{6}/g) || t.filters.fill === "transparent") && (o += `:fill(${t.filters.fill})`), t.filters.format && ["webp", "png", "jpeg"].includes(t.filters.format) && (o += `:format(${t.filters.format})`), typeof t.filters.grayscale == "boolean" && t.filters.grayscale && (o += ":grayscale()"), typeof t.filters.quality == "number" && t.filters.quality >= 0 && t.filters.quality <= 100 && (o += `:quality(${t.filters.quality})`), t.filters.rotate && [90, 180, 270].includes(t.filters.rotate) && (o += `:rotate(${t.filters.rotate})`), o.length > 0 && (o = "/filters" + o))), i.length > 0 && (e = e.replace(/<img/g, `<img ${i.trim()}`));
284
- const c = s > 0 || r > 0 || o.length > 0 ? `${s}x${r}${o}` : "";
285
- return e = e.replace(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g, `a.storyblok.com/f/$1/$2.$3/m/${c}`), typeof t != "boolean" && (t.sizes || t.srcset) && (e = e.replace(/<img.*?src=["|'](.*?)["|']/g, (a) => {
286
- var l, u;
287
- const d = a.match(/a.storyblok.com\/f\/(\d+)\/([^.]+)\.(gif|jpg|jpeg|png|tif|tiff|bmp)/g);
288
- if (d && d.length > 0) {
289
- const g = {
290
- srcset: (l = t.srcset) == null ? void 0 : l.map((p) => {
291
- if (typeof p == "number")
292
- return `//${d}/m/${p}x0${o} ${p}w`;
293
- if (typeof p == "object" && p.length === 2) {
294
- let k = 0, $ = 0;
295
- return typeof p[0] == "number" && (k = p[0]), typeof p[1] == "number" && ($ = p[1]), `//${d}/m/${k}x${$}${o} ${k}w`;
296
- }
297
- }).join(", "),
298
- sizes: (u = t.sizes) == null ? void 0 : u.map((p) => p).join(", ")
299
- };
300
- let b = "";
301
- return g.srcset && (b += `srcset="${g.srcset}" `), g.sizes && (b += `sizes="${g.sizes}" `), a.replace(/<img/g, `<img ${b.trim()}`);
302
- }
303
- return a;
304
- })), e;
305
- }
306
- renderNode(e) {
307
- const t = [];
308
- e.marks && e.marks.forEach((r) => {
309
- const i = this.getMatchingMark(r);
310
- i && t.push(this.renderOpeningTag(i.tag));
311
- });
312
- const s = this.getMatchingNode(e);
313
- return s && s.tag && t.push(this.renderOpeningTag(s.tag)), e.content ? e.content.forEach((r) => {
314
- t.push(this.renderNode(r));
315
- }) : e.text ? t.push(oe(e.text)) : s && s.singleTag ? t.push(this.renderTag(s.singleTag, " /")) : s && s.html ? t.push(s.html) : e.type === "emoji" && t.push(this.renderEmoji(e)), s && s.tag && t.push(this.renderClosingTag(s.tag)), e.marks && e.marks.slice(0).reverse().forEach((r) => {
316
- const i = this.getMatchingMark(r);
317
- i && t.push(this.renderClosingTag(i.tag));
318
- }), t.join("");
319
- }
320
- renderTag(e, t) {
321
- return e.constructor === String ? `<${e}${t}>` : e.map((s) => {
322
- if (s.constructor === String)
323
- return `<${s}${t}>`;
324
- {
325
- let r = `<${s.tag}`;
326
- if (s.attrs)
327
- for (const i in s.attrs) {
328
- const o = s.attrs[i];
329
- o !== null && (r += ` ${i}="${o}"`);
330
- }
331
- return `${r}${t}>`;
332
- }
333
- }).join("");
334
- }
335
- renderOpeningTag(e) {
336
- return this.renderTag(e, "");
337
- }
338
- renderClosingTag(e) {
339
- return e.constructor === String ? `</${e}>` : e.slice(0).reverse().map((t) => t.constructor === String ? `</${t}>` : `</${t.tag}>`).join("");
340
- }
341
- getMatchingNode(e) {
342
- const t = this.nodes[e.type];
343
- if (typeof t == "function")
344
- return t(e);
345
- }
346
- getMatchingMark(e) {
347
- const t = this.marks[e.type];
348
- if (typeof t == "function")
349
- return t(e);
350
- }
351
- renderEmoji(e) {
352
- if (e.attrs.emoji)
353
- return e.attrs.emoji;
354
- const t = [
355
- {
356
- tag: "img",
357
- attrs: {
358
- src: e.attrs.fallbackImage,
359
- draggable: "false",
360
- loading: "lazy",
361
- align: "absmiddle"
362
- }
363
- }
364
- ];
365
- return this.renderTag(t, " /");
366
- }
367
- }
368
- class v {
369
- constructor() {
370
- h(this, "isCDNUrl", (e = "") => e.indexOf("/cdn/") > -1), h(this, "getOptionsPage", (e, t = 25, s = 1) => __spreadProps(__spreadValues({}, e), {
371
- per_page: t,
372
- page: s
373
- })), h(this, "delay", (e) => new Promise((t) => setTimeout(t, e))), h(this, "arrayFrom", (e = 0, t) => [...Array(e)].map(t)), h(this, "range", (e = 0, t = e) => {
374
- const s = Math.abs(t - e) || 0, r = e < t ? 1 : -1;
375
- return this.arrayFrom(s, (i, o) => o * r + e);
376
- }), h(this, "asyncMap", async (e, t) => Promise.all(e.map(t))), h(this, "flatMap", (e = [], t) => e.map(t).reduce((s, r) => [...s, ...r], []));
377
- }
378
- stringify(e, t, s) {
379
- const r = [];
380
- for (const i in e) {
381
- if (!Object.prototype.hasOwnProperty.call(e, i))
382
- continue;
383
- const o = e[i], c = s ? "" : encodeURIComponent(i);
384
- let a;
385
- typeof o == "object" ? a = this.stringify(o, t ? t + encodeURIComponent("[" + c + "]") : c, Array.isArray(o)) : a = (t ? t + encodeURIComponent("[" + c + "]") : c) + "=" + encodeURIComponent(o), r.push(a);
386
- }
387
- return r.join("&");
388
- }
389
- getRegionURL(e) {
390
- const t = "api.storyblok.com", s = "api-us.storyblok.com", r = "app.storyblokchina.cn";
391
- switch (e) {
392
- case "us":
393
- return s;
394
- case "cn":
395
- return r;
396
- default:
397
- return t;
398
- }
399
- }
400
- }
401
- class ne {
402
- constructor(e) {
403
- h(this, "baseURL"), h(this, "timeout"), h(this, "headers"), h(this, "responseInterceptor"), h(this, "fetch"), h(this, "ejectInterceptor"), h(this, "url"), h(this, "parameters"), this.baseURL = e.baseURL, this.headers = e.headers || new Headers(), this.timeout = e != null && e.timeout ? e.timeout * 1e3 : 0, this.responseInterceptor = e.responseInterceptor, this.fetch = (...t) => e.fetch ? e.fetch(...t) : fetch(...t), this.ejectInterceptor = false, this.url = "", this.parameters = {};
404
- }
405
- get(e, t) {
406
- return this.url = e, this.parameters = t, this._methodHandler("get");
407
- }
408
- post(e, t) {
409
- return this.url = e, this.parameters = t, this._methodHandler("post");
410
- }
411
- put(e, t) {
412
- return this.url = e, this.parameters = t, this._methodHandler("put");
413
- }
414
- delete(e, t) {
415
- return this.url = e, this.parameters = t, this._methodHandler("delete");
416
- }
417
- async _responseHandler(e) {
418
- const t = [], s = {
419
- data: {},
420
- headers: {},
421
- status: 0,
422
- statusText: ""
423
- };
424
- e.status !== 204 && await e.json().then((r) => {
425
- s.data = r;
426
- });
427
- for (const r of e.headers.entries())
428
- t[r[0]] = r[1];
429
- return s.headers = __spreadValues({}, t), s.status = e.status, s.statusText = e.statusText, s;
430
- }
431
- async _methodHandler(e) {
432
- let t = `${this.baseURL}${this.url}`, s = null;
433
- if (e === "get") {
434
- const a = new v();
435
- t = `${this.baseURL}${this.url}?${a.stringify(this.parameters)}`;
436
- } else
437
- s = JSON.stringify(this.parameters);
438
- const r = new URL(t), i = new AbortController(), { signal: o } = i;
439
- let c;
440
- this.timeout && (c = setTimeout(() => i.abort(), this.timeout));
441
- try {
442
- const a = await this.fetch(`${r}`, {
443
- method: e,
444
- headers: this.headers,
445
- body: s,
446
- signal: o
447
- });
448
- this.timeout && clearTimeout(c);
449
- const l = await this._responseHandler(a);
450
- return this.responseInterceptor && !this.ejectInterceptor ? this._statusHandler(this.responseInterceptor(l)) : this._statusHandler(l);
451
- } catch (a) {
452
- return {
453
- message: a
454
- };
455
- }
456
- }
457
- eject() {
458
- this.ejectInterceptor = true;
459
- }
460
- _statusHandler(e) {
461
- const t = /20[0-6]/g;
462
- return new Promise((s, r) => {
463
- if (t.test(`${e.status}`))
464
- return s(e);
465
- const i = {
466
- message: new Error(e.statusText),
467
- status: e.status,
468
- response: Array.isArray(e.data) ? e.data[0] : e.data.error || e.data.slug
469
- };
470
- r(i);
471
- });
472
- }
473
- }
474
- let m = {};
475
- const f = {};
476
- class ae {
477
- constructor(e, t) {
478
- if (h(this, "client"), h(this, "maxRetries"), h(this, "throttle"), h(this, "accessToken"), h(this, "cache"), h(this, "helpers"), h(this, "resolveCounter"), h(this, "relations"), h(this, "links"), h(this, "richTextResolver"), h(this, "resolveNestedRelations"), !t) {
479
- const i = new v().getRegionURL, o = e.https === false ? "http" : "https";
480
- e.oauthToken ? t = `${o}://${i(e.region)}/v1` : t = `${o}://${i(e.region)}/v2`;
481
- }
482
- const s = new Headers();
483
- s.set("Content-Type", "application/json"), s.set("Accept", "application/json"), s.forEach((i, o) => {
484
- e.headers && e.headers[o] && s.set(o, e.headers[o]);
485
- });
486
- let r = 5;
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({
488
- baseURL: t,
489
- timeout: e.timeout || 0,
490
- headers: s,
491
- responseInterceptor: e.responseInterceptor,
492
- fetch: e.fetch
493
- });
494
- }
495
- setComponentResolver(e) {
496
- this.richTextResolver.addNode("blok", (t) => {
497
- let s = "";
498
- return t.attrs.body.forEach((r) => {
499
- s += e(r.component, r);
500
- }), {
501
- html: s
502
- };
503
- });
504
- }
505
- parseParams(e) {
506
- return e.version || (e.version = "published"), e.token || (e.token = this.getToken()), e.cv || (e.cv = f[e.token]), Array.isArray(e.resolve_relations) && (e.resolve_relations = e.resolve_relations.join(",")), e;
507
- }
508
- factoryParamOptions(e, t) {
509
- return this.helpers.isCDNUrl(e) ? this.parseParams(t) : t;
510
- }
511
- makeRequest(e, t, s, r) {
512
- const i = this.factoryParamOptions(e, this.helpers.getOptionsPage(t, s, r));
513
- return this.cacheResponse(e, i);
514
- }
515
- get(e, t) {
516
- t || (t = {});
517
- const s = `/${e}`, r = this.factoryParamOptions(s, t);
518
- return this.cacheResponse(s, r);
519
- }
520
- async getAll(e, t, s) {
521
- const r = (t == null ? void 0 : t.per_page) || 25, i = `/${e}`, o = i.split("/"), c = s || o[o.length - 1], a = 1, l = await this.makeRequest(i, t, r, a), u = l.total ? Math.ceil(l.total / r) : 1, d = await this.helpers.asyncMap(this.helpers.range(a, u), (g) => this.makeRequest(i, t, r, g + 1));
522
- return this.helpers.flatMap([l, ...d], (g) => Object.values(g.data[c]));
523
- }
524
- post(e, t) {
525
- const s = `/${e}`;
526
- return Promise.resolve(this.throttle("post", s, t));
527
- }
528
- put(e, t) {
529
- const s = `/${e}`;
530
- return Promise.resolve(this.throttle("put", s, t));
531
- }
532
- delete(e, t) {
533
- const s = `/${e}`;
534
- return Promise.resolve(this.throttle("delete", s, t));
535
- }
536
- getStories(e) {
537
- return this.get("cdn/stories", e);
538
- }
539
- getStory(e, t) {
540
- return this.get(`cdn/stories/${e}`, t);
541
- }
542
- getToken() {
543
- return this.accessToken;
544
- }
545
- ejectInterceptor() {
546
- this.client.eject();
547
- }
548
- _cleanCopy(e) {
549
- return JSON.parse(JSON.stringify(e));
550
- }
551
- _insertLinks(e, t, s) {
552
- const r = e[t];
553
- 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]));
554
- }
555
- _insertRelations(e, t, s, r) {
556
- if (s.indexOf(`${e.component}.${t}`) > -1) {
557
- if (typeof e[t] == "string")
558
- this.relations[r][e[t]] && (e[t] = this._cleanCopy(this.relations[r][e[t]]));
559
- else if (e[t] && e[t].constructor === Array) {
560
- const i = [];
561
- e[t].forEach((o) => {
562
- this.relations[r][o] && i.push(this._cleanCopy(this.relations[r][o]));
563
- }), e[t] = i;
564
- }
565
- }
566
- }
567
- iterateTree(e, t, s) {
568
- const r = (i) => {
569
- if (i != null) {
570
- if (i.constructor === Array)
571
- for (let o = 0; o < i.length; o++)
572
- r(i[o]);
573
- else if (i.constructor === Object) {
574
- if (i._stopResolving)
575
- return;
576
- for (const o in i)
577
- (i.component && i._uid || i.type === "link") && (this._insertRelations(i, o, t, s), this._insertLinks(i, o, s)), r(i[o]);
578
- }
579
- }
580
- };
581
- r(e.content);
582
- }
583
- async resolveLinks(e, t, s) {
584
- let r = [];
585
- if (e.link_uuids) {
586
- const i = e.link_uuids.length, o = [], c = 50;
587
- for (let a = 0; a < i; a += c) {
588
- const l = Math.min(i, a + c);
589
- o.push(e.link_uuids.slice(a, l));
590
- }
591
- for (let a = 0; a < o.length; a++)
592
- (await this.getStories({
593
- per_page: c,
594
- language: t.language,
595
- version: t.version,
596
- by_uuids: o[a].join(",")
597
- })).data.stories.forEach((l) => {
598
- r.push(l);
599
- });
600
- } else
601
- r = e.links;
602
- r.forEach((i) => {
603
- this.links[s][i.uuid] = __spreadProps(__spreadValues({}, i), {
604
- _stopResolving: true
605
- });
606
- });
607
- }
608
- async resolveRelations(e, t, s) {
609
- let r = [];
610
- if (e.rel_uuids) {
611
- const i = e.rel_uuids.length, o = [], c = 50;
612
- for (let a = 0; a < i; a += c) {
613
- const l = Math.min(i, a + c);
614
- o.push(e.rel_uuids.slice(a, l));
615
- }
616
- for (let a = 0; a < o.length; a++)
617
- (await this.getStories({
618
- per_page: c,
619
- language: t.language,
620
- version: t.version,
621
- by_uuids: o[a].join(",")
622
- })).data.stories.forEach((l) => {
623
- r.push(l);
624
- });
625
- } else
626
- r = e.rels;
627
- r && r.length > 0 && r.forEach((i) => {
628
- this.relations[s][i.uuid] = __spreadProps(__spreadValues({}, i), {
629
- _stopResolving: true
630
- });
631
- });
632
- }
633
- async resolveStories(e, t, s) {
634
- var r, i;
635
- let o = [];
636
- if (this.links[s] = {}, this.relations[s] = {}, typeof t.resolve_relations < "u" && t.resolve_relations.length > 0 && (typeof t.resolve_relations == "string" && (o = t.resolve_relations.split(",")), await this.resolveRelations(e, t, s)), t.resolve_links && ["1", "story", "url"].indexOf(t.resolve_links) > -1 && ((r = e.links) != null && r.length || (i = e.link_uuids) != null && i.length) && await this.resolveLinks(e, t, s), this.resolveNestedRelations)
637
- for (const c in this.relations[s])
638
- this.iterateTree(this.relations[s][c], o, s);
639
- e.story ? this.iterateTree(e.story, o, s) : e.stories.forEach((c) => {
640
- this.iterateTree(c, o, s);
641
- }), delete this.links[s], delete this.relations[s];
642
- }
643
- async cacheResponse(e, t, s) {
644
- const r = this.helpers.stringify({ url: e, params: t }), i = this.cacheProvider();
645
- if (this.cache.clear === "auto" && t.version === "draft" && await this.flushCache(), t.version === "published" && e != "/cdn/spaces/me") {
646
- const o = await i.get(r);
647
- if (o)
648
- return Promise.resolve(o);
649
- }
650
- return new Promise((o, c) => {
651
- try {
652
- (async () => {
653
- var a;
654
- try {
655
- const l = await this.throttle("get", e, t);
656
- let u = { data: l.data, headers: l.headers };
657
- if ((a = l.headers) != null && a["per-page"] && (u = Object.assign({}, u, {
658
- perPage: l.headers["per-page"] ? parseInt(l.headers["per-page"]) : 0,
659
- total: l.headers["per-page"] ? parseInt(l.headers.total) : 0
660
- })), l.status != 200)
661
- return c(l);
662
- if (u.data.story || u.data.stories) {
663
- const d = this.resolveCounter = ++this.resolveCounter % 1e3;
664
- await this.resolveStories(u.data, t, `${d}`);
665
- }
666
- return t.version === "published" && e != "/cdn/spaces/me" && await i.set(r, u), u.data.cv && t.token && (t.version == "draft" && f[t.token] != u.data.cv && await this.flushCache(), f[t.token] = u.data.cv), o(u);
667
- } catch (l) {
668
- return c(l);
669
- }
670
- })();
671
- } catch {
672
- }
673
- });
674
- }
675
- throttledRequest(e, t, s) {
676
- return this.client[e](t, s);
677
- }
678
- cacheVersions() {
679
- return f;
680
- }
681
- cacheVersion() {
682
- return f[this.accessToken];
683
- }
684
- setCacheVersion(e) {
685
- this.accessToken && (f[this.accessToken] = e);
686
- }
687
- cacheProvider() {
688
- switch (this.cache.type) {
689
- case "memory":
690
- return {
691
- get(e) {
692
- return Promise.resolve(m[e]);
693
- },
694
- getAll() {
695
- return Promise.resolve(m);
696
- },
697
- set(e, t) {
698
- return m[e] = t, Promise.resolve(void 0);
699
- },
700
- flush() {
701
- return m = {}, Promise.resolve(void 0);
702
- }
703
- };
704
- case "custom":
705
- if (this.cache.custom)
706
- return this.cache.custom;
707
- default:
708
- return {
709
- get() {
710
- return Promise.resolve(void 0);
711
- },
712
- getAll() {
713
- return Promise.resolve(void 0);
714
- },
715
- set() {
716
- return Promise.resolve(void 0);
717
- },
718
- flush() {
719
- return Promise.resolve(void 0);
720
- }
721
- };
722
- }
723
- }
724
- async flushCache() {
725
- return await this.cacheProvider().flush(), this;
726
- }
727
- }
728
- const le = (n = {}) => {
729
- const { apiOptions: e } = n;
730
- if (!e.accessToken) {
731
- 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");
732
- return;
733
- }
734
- return { storyblokApi: new ae(e) };
735
- }, ce = (n) => {
736
- if (typeof n != "object" || typeof n._editable > "u")
737
- return {};
738
- const e = JSON.parse(n._editable.replace(/^<!--#storyblok#/, "").replace(/-->$/, ""));
739
- return {
740
- "data-blok-c": JSON.stringify(e),
741
- "data-blok-uid": e.id + "-" + e.uid
742
- };
743
- };
744
- let w;
745
- const x = "https://app.storyblok.com/f/storyblok-v2-latest.js", he = (n, e, t = {}) => {
746
- var c;
747
- const r = !(typeof window > "u") && typeof window.storyblokRegisterEvent < "u", o = +new URL((c = window.location) == null ? void 0 : c.href).searchParams.get("_storyblok") === n;
748
- if (!(!r || !o)) {
749
- if (!n) {
750
- console.warn("Story ID is not defined. Please provide a valid ID.");
751
- return;
752
- }
753
- window.storyblokRegisterEvent(() => {
754
- new window.StoryblokBridge(t).on(["input", "published", "change"], (l) => {
755
- l.action === "input" && l.story.id === n ? e(l.story) : (l.action === "change" || l.action === "published") && l.storyId === n && window.location.reload();
756
- });
757
- });
758
- }
759
- }, ue = (n = {}) => {
760
- var u, d;
761
- const {
762
- bridge: e,
763
- accessToken: t,
764
- use: s = [],
765
- apiOptions: r = {},
766
- richText: i = {}
767
- } = n;
768
- r.accessToken = r.accessToken || t;
769
- const o = { bridge: e, apiOptions: r };
770
- let c = {};
771
- s.forEach((g) => {
772
- c = __spreadValues(__spreadValues({}, c), g(o));
773
- });
774
- const l = !(typeof window > "u") && ((d = (u = window.location) == null ? void 0 : u.search) == null ? void 0 : d.includes("_storyblok_tk"));
775
- return e !== false && l && j(x), w = new y(i.schema), i.resolver && E(w, i.resolver), c;
776
- }, E = (n, e) => {
777
- n.addNode("blok", (t) => {
778
- let s = "";
779
- return t.attrs.body.forEach((r) => {
780
- s += e(r.component, r);
781
- }), {
782
- html: s
783
- };
784
- });
785
- }, de = (n, e, t) => {
786
- let s = t || w;
787
- if (!s) {
788
- console.error("Please initialize the Storyblok SDK before calling the renderRichText function");
789
- return;
790
- }
791
- return n === "" ? "" : n ? (e && (s = new y(e.schema), e.resolver && E(s, e.resolver)), s.render(n)) : (console.warn(`${n} is not a valid Richtext object. This might be because the value of the richtext field is empty.
792
-
793
- For more info about the richtext object check https://github.com/storyblok/storyblok-js#rendering-rich-text`), "");
794
- };
795
- const StoryblokComponent = forwardRef((_a, ref) => {
796
- var _b = _a, { blok } = _b, restProps = __objRest(_b, ["blok"]);
797
- if (!blok) {
798
- console.error("Please provide a 'blok' property to the StoryblokComponent");
799
- return /* @__PURE__ */ React.createElement("div", null, "Please provide a blok property to the StoryblokComponent");
800
- }
801
- const Component = getComponent(blok.component);
802
- if (Component) {
803
- return /* @__PURE__ */ React.createElement(Component, __spreadValues({
804
- ref,
805
- blok
806
- }, restProps));
807
- }
808
- return /* @__PURE__ */ React.createElement("div", null);
809
- });
810
- StoryblokComponent.displayName = "StoryblokComponent";
1
+ import { useState, useEffect } from "react";
2
+ import { h as he } from "./storyblok-js-612aedc3.mjs";
3
+ import { y, i, l, p, d, c } from "./storyblok-js-612aedc3.mjs";
4
+ import { u as useStoryblokApi } from "./index-f1318b50.mjs";
5
+ import { S, g, s } from "./index-f1318b50.mjs";
6
+ import { u } from "./client-16ee9ae1.mjs";
811
7
  const useStoryblok = (slug, apiOptions = {}, bridgeOptions = {}) => {
812
- let [story, setStory] = useState({});
8
+ const storyblokApiInstance = useStoryblokApi();
813
9
  if (!storyblokApiInstance) {
814
- console.error("You can't use useStoryblok if you're not loading apiPlugin.");
10
+ console.error(
11
+ "You can't use useStoryblok if you're not loading apiPlugin."
12
+ );
815
13
  return null;
816
14
  }
15
+ let [story, setStory] = useState({});
817
16
  const isBridgeEnable = typeof window !== "undefined" && typeof window.storyblokRegisterEvent !== "undefined";
818
17
  useEffect(() => {
819
18
  async function initStory() {
820
- const { data } = await storyblokApiInstance.get(`cdn/stories/${slug}`, apiOptions);
19
+ const { data } = await storyblokApiInstance.get(
20
+ `cdn/stories/${slug}`,
21
+ apiOptions
22
+ );
821
23
  setStory(data.story);
822
24
  if (isBridgeEnable && data.story.id) {
823
- he(data.story.id, (story2) => setStory(story2), bridgeOptions);
25
+ he(
26
+ data.story.id,
27
+ (story2) => setStory(story2),
28
+ bridgeOptions
29
+ );
824
30
  }
825
31
  }
826
32
  initStory();
827
33
  }, [slug, JSON.stringify(apiOptions)]);
828
34
  return story;
829
35
  };
830
- const useStoryblokState = (initialStory = null, bridgeOptions = {}) => {
831
- let [story, setStory] = useState(initialStory);
832
- const isBridgeEnable = typeof window !== "undefined" && typeof window.storyblokRegisterEvent !== "undefined";
833
- if (!isBridgeEnable || !initialStory) {
834
- return initialStory;
835
- }
836
- useEffect(() => {
837
- setStory(initialStory);
838
- he(story.id, (newStory) => setStory(newStory), bridgeOptions);
839
- }, [initialStory]);
840
- return story;
841
- };
842
- let storyblokApiInstance = null;
843
- const useStoryblokApi = () => {
844
- if (!storyblokApiInstance) {
845
- console.error("You can't use getStoryblokApi if you're not loading apiPlugin.");
846
- }
847
- return storyblokApiInstance;
848
- };
849
- let componentsMap = {};
850
- const getComponent = (componentKey) => {
851
- if (!componentsMap[componentKey]) {
852
- console.error(`Component ${componentKey} doesn't exist.`);
853
- return false;
854
- }
855
- return componentsMap[componentKey];
856
- };
857
- const storyblokInit = (pluginOptions = {}) => {
858
- const { storyblokApi } = ue(pluginOptions);
859
- storyblokApiInstance = storyblokApi;
860
- componentsMap = pluginOptions.components;
36
+ export {
37
+ y as RichTextResolver,
38
+ i as RichTextSchema,
39
+ S as StoryblokComponent,
40
+ l as apiPlugin,
41
+ g as getComponent,
42
+ useStoryblokApi as getStoryblokApi,
43
+ p as loadStoryblokBridge,
44
+ he as registerStoryblokBridge,
45
+ d as renderRichText,
46
+ c as storyblokEditable,
47
+ s as storyblokInit,
48
+ useStoryblok,
49
+ useStoryblokApi,
50
+ he as useStoryblokBridge,
51
+ u as useStoryblokState
861
52
  };
862
- export { y as RichTextResolver, ie as RichTextSchema, StoryblokComponent, le as apiPlugin, getComponent, useStoryblokApi as getStoryblokApi, he as registerStoryblokBridge, de as renderRichText, ce as storyblokEditable, storyblokInit, useStoryblok, useStoryblokApi, he as useStoryblokBridge, useStoryblokState };