vue-datocms 2.0.0 → 3.0.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.
@@ -0,0 +1,859 @@
1
+ import hypenateStyleName from 'hyphenate-style-name';
2
+ import { ref, onMounted, onBeforeUnmount, defineComponent, h, isVue2, isVue3, watchEffect, reactive, computed, toRaw } from 'vue-demi';
3
+ import { render, renderNodeRule, defaultMetaTransformer } from 'datocms-structured-text-generic-html-renderer';
4
+ export { renderMarkRule, renderNodeRule, renderNodeRule as renderRule } from 'datocms-structured-text-generic-html-renderer';
5
+ import { isRoot, isInlineItem, RenderError, isStructuredText, isItemLink, isBlock } from 'datocms-structured-text-utils';
6
+ export { RenderError } from 'datocms-structured-text-utils';
7
+ import { subscribeToQuery } from 'datocms-listen';
8
+
9
+ const isSsr = () => {
10
+ return typeof window === "undefined";
11
+ };
12
+ const isIntersectionObserverAvailable = () => {
13
+ return isSsr() ? false : !!window.IntersectionObserver;
14
+ };
15
+
16
+ const useInView = ({ threshold, rootMargin }) => {
17
+ const observer = ref(null);
18
+ const elRef = ref(null);
19
+ const inView = ref(false);
20
+ onMounted(() => {
21
+ if (isIntersectionObserverAvailable()) {
22
+ observer.value = new IntersectionObserver(
23
+ (entries) => {
24
+ const image = entries[0];
25
+ if (image.isIntersecting && observer.value) {
26
+ inView.value = true;
27
+ observer.value.disconnect();
28
+ }
29
+ },
30
+ {
31
+ threshold,
32
+ rootMargin
33
+ }
34
+ );
35
+ if (elRef.value) {
36
+ observer.value.observe(elRef.value);
37
+ }
38
+ }
39
+ });
40
+ onBeforeUnmount(() => {
41
+ if (isIntersectionObserverAvailable() && observer.value) {
42
+ observer.value.disconnect();
43
+ }
44
+ });
45
+ return { inView, elRef };
46
+ };
47
+
48
+ var __defProp$4 = Object.defineProperty;
49
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
50
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
51
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
52
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
53
+ var __spreadValues$4 = (a, b) => {
54
+ for (var prop in b || (b = {}))
55
+ if (__hasOwnProp$4.call(b, prop))
56
+ __defNormalProp$4(a, prop, b[prop]);
57
+ if (__getOwnPropSymbols$4)
58
+ for (var prop of __getOwnPropSymbols$4(b)) {
59
+ if (__propIsEnum$4.call(b, prop))
60
+ __defNormalProp$4(a, prop, b[prop]);
61
+ }
62
+ return a;
63
+ };
64
+ const Source = defineComponent({
65
+ props: {
66
+ srcset: {
67
+ type: String
68
+ },
69
+ sizes: {
70
+ type: String
71
+ },
72
+ type: {
73
+ type: String
74
+ }
75
+ },
76
+ setup({ srcset, sizes, type }) {
77
+ return () => h("source", __spreadValues$4(__spreadValues$4({}, isVue2 && {
78
+ attrs: {
79
+ srcset,
80
+ sizes,
81
+ type
82
+ }
83
+ }), isVue3 && {
84
+ srcset,
85
+ sizes,
86
+ type
87
+ }));
88
+ }
89
+ });
90
+
91
+ var __defProp$3 = Object.defineProperty;
92
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
93
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
94
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
95
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
96
+ var __spreadValues$3 = (a, b) => {
97
+ for (var prop in b || (b = {}))
98
+ if (__hasOwnProp$3.call(b, prop))
99
+ __defNormalProp$3(a, prop, b[prop]);
100
+ if (__getOwnPropSymbols$3)
101
+ for (var prop of __getOwnPropSymbols$3(b)) {
102
+ if (__propIsEnum$3.call(b, prop))
103
+ __defNormalProp$3(a, prop, b[prop]);
104
+ }
105
+ return a;
106
+ };
107
+ const universalBtoa = (str) => isSsr() ? Buffer.from(str.toString(), "binary").toString("base64") : window.btoa(str);
108
+ const Sizer = defineComponent({
109
+ props: {
110
+ sizerClass: {
111
+ type: String
112
+ },
113
+ sizerStyle: {
114
+ type: Object,
115
+ default: () => ({})
116
+ },
117
+ width: {
118
+ type: Number
119
+ },
120
+ height: {
121
+ type: Number
122
+ },
123
+ explicitWidth: {
124
+ type: Boolean
125
+ }
126
+ },
127
+ setup({ sizerClass, sizerStyle, width, height, explicitWidth }) {
128
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"></svg>`;
129
+ return () => h("img", __spreadValues$3(__spreadValues$3({
130
+ class: sizerClass,
131
+ style: __spreadValues$3({
132
+ display: "block",
133
+ width: explicitWidth ? `${width}px` : "100%"
134
+ }, sizerStyle)
135
+ }, isVue2 && {
136
+ attrs: {
137
+ src: `data:image/svg+xml;base64,${universalBtoa(svg)}`,
138
+ role: "presentation"
139
+ }
140
+ }), isVue3 && {
141
+ src: `data:image/svg+xml;base64,${universalBtoa(svg)}`,
142
+ role: "presentation"
143
+ }));
144
+ }
145
+ });
146
+
147
+ var __defProp$2 = Object.defineProperty;
148
+ var __defProps$2 = Object.defineProperties;
149
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
150
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
151
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
152
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
153
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
154
+ var __spreadValues$2 = (a, b) => {
155
+ for (var prop in b || (b = {}))
156
+ if (__hasOwnProp$2.call(b, prop))
157
+ __defNormalProp$2(a, prop, b[prop]);
158
+ if (__getOwnPropSymbols$2)
159
+ for (var prop of __getOwnPropSymbols$2(b)) {
160
+ if (__propIsEnum$2.call(b, prop))
161
+ __defNormalProp$2(a, prop, b[prop]);
162
+ }
163
+ return a;
164
+ };
165
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
166
+ const escape = (s) => {
167
+ s = "" + s;
168
+ s = s.replace(/&/g, "&amp;");
169
+ s = s.replace(/</g, "&lt;");
170
+ s = s.replace(/>/g, "&gt;");
171
+ s = s.replace(/"/g, "&quot;");
172
+ s = s.replace(/'/g, "&#39;");
173
+ return s;
174
+ };
175
+ const toCss = (object) => {
176
+ if (!object) {
177
+ return null;
178
+ }
179
+ let result = "";
180
+ for (var styleName in object) {
181
+ if (Object.prototype.hasOwnProperty.call(object, styleName) && object[styleName]) {
182
+ result += `${hypenateStyleName(styleName)}: ${object[styleName]}; `;
183
+ }
184
+ }
185
+ return result.length > 0 ? result : null;
186
+ };
187
+ const tag = (tagName, attrs, content) => {
188
+ const serializedAttrs = [];
189
+ if (attrs) {
190
+ for (var attrName in attrs) {
191
+ if (Object.prototype.hasOwnProperty.call(attrs, attrName)) {
192
+ const value = attrs[attrName];
193
+ if (value) {
194
+ serializedAttrs.push(`${escape(attrName)}="${escape(value)}"`);
195
+ }
196
+ }
197
+ }
198
+ }
199
+ const attrsString = serializedAttrs.length > 0 ? ` ${serializedAttrs.join(" ")}` : "";
200
+ return content ? `<${tagName}${attrsString}>${content.join("")}</${tagName}>` : `<${tagName}${attrsString} />`;
201
+ };
202
+ const absolutePositioning = {
203
+ position: "absolute",
204
+ left: "0px",
205
+ top: "0px",
206
+ width: "100%",
207
+ height: "100%"
208
+ };
209
+ const imageAddStrategy = ({ lazyLoad, inView, loaded }) => {
210
+ if (!lazyLoad) {
211
+ return true;
212
+ }
213
+ if (isSsr()) {
214
+ return false;
215
+ }
216
+ if (isIntersectionObserverAvailable()) {
217
+ return inView || loaded;
218
+ }
219
+ return true;
220
+ };
221
+ const imageShowStrategy = ({ lazyLoad, loaded }) => {
222
+ if (!lazyLoad) {
223
+ return true;
224
+ }
225
+ if (isSsr()) {
226
+ return false;
227
+ }
228
+ if (isIntersectionObserverAvailable()) {
229
+ return loaded;
230
+ }
231
+ return true;
232
+ };
233
+ const Image = defineComponent({
234
+ name: "DatocmsImage",
235
+ props: {
236
+ data: {
237
+ type: Object,
238
+ required: true
239
+ },
240
+ pictureClass: {
241
+ type: String
242
+ },
243
+ fadeInDuration: {
244
+ type: Number
245
+ },
246
+ intersectionTreshold: {
247
+ type: Number,
248
+ default: 0
249
+ },
250
+ intersectionThreshold: {
251
+ type: Number
252
+ },
253
+ intersectionMargin: {
254
+ type: String,
255
+ default: "0px 0px 0px 0px"
256
+ },
257
+ lazyLoad: {
258
+ type: Boolean,
259
+ default: true
260
+ },
261
+ rootStyle: {
262
+ type: Object,
263
+ default: () => ({})
264
+ },
265
+ pictureStyle: {
266
+ type: Object,
267
+ default: () => ({})
268
+ },
269
+ explicitWidth: {
270
+ type: Boolean
271
+ },
272
+ layout: {
273
+ type: String,
274
+ default: () => "responsive",
275
+ validator: (value) => ["intrinsic", "fixed", "responsive", "fill"].includes(value)
276
+ },
277
+ objectFit: {
278
+ type: String
279
+ },
280
+ objectPosition: {
281
+ type: String
282
+ }
283
+ },
284
+ setup(props) {
285
+ const loaded = ref(false);
286
+ function handleLoad() {
287
+ loaded.value = true;
288
+ }
289
+ const { inView, elRef } = useInView({
290
+ threshold: props.intersectionThreshold || props.intersectionTreshold || 0,
291
+ rootMargin: props.intersectionMargin || "0px 0px 0px 0px"
292
+ });
293
+ return {
294
+ inView,
295
+ elRef,
296
+ loaded,
297
+ handleLoad
298
+ };
299
+ },
300
+ render() {
301
+ const addImage = imageAddStrategy({
302
+ lazyLoad: this.lazyLoad,
303
+ inView: this.inView,
304
+ loaded: this.loaded
305
+ });
306
+ const showImage = imageShowStrategy({
307
+ lazyLoad: this.lazyLoad,
308
+ inView: this.inView,
309
+ loaded: this.loaded
310
+ });
311
+ const webpSource = this.data.webpSrcSet && h(Source, __spreadValues$2(__spreadValues$2({}, isVue2 && {
312
+ props: {
313
+ srcset: this.data.webpSrcSet,
314
+ sizes: this.data.sizes,
315
+ type: "image/webp"
316
+ }
317
+ }), isVue3 && {
318
+ srcset: this.data.webpSrcSet,
319
+ sizes: this.data.sizes,
320
+ type: "image/webp"
321
+ }));
322
+ const regularSource = this.data.srcSet && h(Source, __spreadValues$2(__spreadValues$2({}, isVue2 && {
323
+ props: {
324
+ srcset: this.data.srcSet,
325
+ sizes: this.data.sizes
326
+ }
327
+ }), isVue3 && {
328
+ srcset: this.data.srcSet,
329
+ sizes: this.data.sizes
330
+ }));
331
+ const transition = typeof this.fadeInDuration === "undefined" || this.fadeInDuration > 0 ? `opacity ${this.fadeInDuration || 500}ms ${this.fadeInDuration || 500}ms` : void 0;
332
+ const placeholder = h("div", {
333
+ style: __spreadValues$2({
334
+ backgroundImage: this.data.base64 ? `url(${this.data.base64})` : null,
335
+ backgroundColor: this.data.bgColor,
336
+ backgroundSize: "cover",
337
+ opacity: showImage ? 0 : 1,
338
+ objectFit: this.objectFit,
339
+ objectPosition: this.objectPosition,
340
+ transition
341
+ }, absolutePositioning)
342
+ });
343
+ const { width, aspectRatio } = this.data;
344
+ const height = this.data.height || width / aspectRatio;
345
+ const sizer = this.layout !== "fill" ? h(Sizer, __spreadValues$2(__spreadValues$2({}, isVue2 && {
346
+ props: {
347
+ sizerClass: this.pictureClass,
348
+ sizerStyle: this.pictureStyle,
349
+ width,
350
+ height,
351
+ explicitWidth: this.explicitWidth
352
+ }
353
+ }), isVue3 && {
354
+ sizerClass: this.pictureClass,
355
+ sizerStyle: this.pictureStyle,
356
+ width,
357
+ height,
358
+ explicitWidth: this.explicitWidth
359
+ })) : null;
360
+ return h(
361
+ "div",
362
+ {
363
+ style: __spreadValues$2(__spreadValues$2({
364
+ display: this.explicitWidth ? "inline-block" : "block",
365
+ overflow: "hidden"
366
+ }, this.layout === "fill" ? absolutePositioning : this.layout === "intrinsic" ? { position: "relative", width: "100%", maxWidth: `${width}px` } : this.layout === "fixed" ? { position: "relative", width: `${width}px` } : { position: "relative" }), this.rootStyle),
367
+ ref: "elRef"
368
+ },
369
+ [
370
+ sizer,
371
+ placeholder,
372
+ addImage && h("picture", null, [
373
+ webpSource,
374
+ regularSource,
375
+ this.data.src && h("img", __spreadProps$2(__spreadValues$2(__spreadValues$2({}, isVue2 && {
376
+ attrs: {
377
+ src: this.data.src,
378
+ alt: this.data.alt,
379
+ title: this.data.title
380
+ },
381
+ on: {
382
+ load: this.handleLoad
383
+ }
384
+ }), isVue3 && {
385
+ src: this.data.src,
386
+ alt: this.data.alt,
387
+ title: this.data.title,
388
+ onLoad: this.handleLoad
389
+ }), {
390
+ class: this.pictureClass,
391
+ style: __spreadProps$2(__spreadValues$2(__spreadValues$2({}, absolutePositioning), this.pictureStyle), {
392
+ opacity: showImage ? 1 : 0,
393
+ transition,
394
+ objectFit: this.objectFit,
395
+ objectPosition: this.objectPosition
396
+ })
397
+ }))
398
+ ]),
399
+ h("noscript", __spreadValues$2(__spreadValues$2({}, isVue2 && {
400
+ domProps: {
401
+ innerHTML: tag("picture", {}, [
402
+ this.data.webpSrcSet && tag("source", {
403
+ srcset: this.data.webpSrcSet,
404
+ sizes: this.data.sizes,
405
+ type: "image/webp"
406
+ }),
407
+ this.data.srcSet && tag("source", {
408
+ srcset: this.data.srcSet,
409
+ sizes: this.data.sizes
410
+ }),
411
+ tag("img", {
412
+ src: this.data.src,
413
+ alt: this.data.alt,
414
+ title: this.data.title,
415
+ class: this.pictureClass,
416
+ style: toCss(__spreadValues$2(__spreadValues$2({}, this.pictureStyle), absolutePositioning)),
417
+ loading: "lazy"
418
+ })
419
+ ])
420
+ }
421
+ }), isVue3 && {
422
+ innerHTML: tag("picture", {}, [
423
+ this.data.webpSrcSet && tag("source", {
424
+ srcset: this.data.webpSrcSet,
425
+ sizes: this.data.sizes,
426
+ type: "image/webp"
427
+ }),
428
+ this.data.srcSet && tag("source", {
429
+ srcset: this.data.srcSet,
430
+ sizes: this.data.sizes
431
+ }),
432
+ tag("img", {
433
+ src: this.data.src,
434
+ alt: this.data.alt,
435
+ title: this.data.title,
436
+ class: this.pictureClass,
437
+ style: toCss(__spreadValues$2(__spreadValues$2({}, this.pictureStyle), absolutePositioning)),
438
+ loading: "lazy"
439
+ })
440
+ ])
441
+ }))
442
+ ]
443
+ );
444
+ }
445
+ });
446
+ const DatocmsImagePlugin = {
447
+ install: (Vue) => {
448
+ Vue.component("DatocmsImage", Image);
449
+ }
450
+ };
451
+
452
+ const hAdapter = (tagName, props, childOrChildren) => {
453
+ return h(
454
+ tagName,
455
+ props,
456
+ Array.isArray(childOrChildren) ? childOrChildren : [childOrChildren]
457
+ );
458
+ };
459
+ const defaultAdapter = {
460
+ renderNode: hAdapter,
461
+ renderMark: hAdapter,
462
+ renderFragment: (children, key) => children,
463
+ renderText: (text, key) => text
464
+ };
465
+ function appendKeyToValidElement(element, key) {
466
+ if (element !== null && typeof element !== "string" && element.key === null) {
467
+ element.key = key;
468
+ }
469
+ return element;
470
+ }
471
+ const StructuredText = defineComponent({
472
+ name: "DatocmsStructuredText",
473
+ props: {
474
+ data: {
475
+ type: Object
476
+ },
477
+ customRules: {
478
+ type: Array
479
+ },
480
+ customNodeRules: {
481
+ type: Array
482
+ },
483
+ customMarkRules: {
484
+ type: Array
485
+ },
486
+ renderInlineRecord: {
487
+ type: Function
488
+ },
489
+ renderLinkToRecord: {
490
+ type: Function
491
+ },
492
+ renderBlock: {
493
+ type: Function
494
+ },
495
+ metaTransformer: { type: Function },
496
+ renderText: { type: Function },
497
+ renderNode: { type: Function },
498
+ renderFragment: { type: Function }
499
+ },
500
+ setup(props) {
501
+ return () => {
502
+ return render(props.data, {
503
+ adapter: {
504
+ renderText: props.renderText || defaultAdapter.renderText,
505
+ renderNode: props.renderNode || defaultAdapter.renderNode,
506
+ renderFragment: props.renderFragment || defaultAdapter.renderFragment
507
+ },
508
+ metaTransformer: props.metaTransformer,
509
+ customMarkRules: props.customMarkRules,
510
+ customNodeRules: [
511
+ renderNodeRule(
512
+ isRoot,
513
+ ({ adapter: { renderNode }, key, children }) => {
514
+ return renderNode("div", { key }, children);
515
+ }
516
+ ),
517
+ renderNodeRule(isInlineItem, ({ node, key }) => {
518
+ if (!props.renderInlineRecord) {
519
+ throw new RenderError(
520
+ `The Structured Text document contains an 'inlineItem' node, but no 'renderInlineRecord' prop is specified!`,
521
+ node
522
+ );
523
+ }
524
+ if (!isStructuredText(props.data) || !props.data.links) {
525
+ throw new RenderError(
526
+ `The Structured Text document contains an 'inlineItem' node, but .links is not present!`,
527
+ node
528
+ );
529
+ }
530
+ const item = props.data.links.find((item2) => item2.id === node.item);
531
+ if (!item) {
532
+ throw new RenderError(
533
+ `The Structured Text document contains an 'inlineItem' node, but cannot find a record with ID ${node.item} inside .links!`,
534
+ node
535
+ );
536
+ }
537
+ return appendKeyToValidElement(
538
+ props.renderInlineRecord({ record: item }),
539
+ key
540
+ );
541
+ }),
542
+ renderNodeRule(isItemLink, ({ node, key, children }) => {
543
+ if (!props.renderLinkToRecord) {
544
+ throw new RenderError(
545
+ `The Structured Text document contains an 'itemLink' node, but no 'renderLinkToRecord' prop is specified!`,
546
+ node
547
+ );
548
+ }
549
+ if (!isStructuredText(props.data) || !props.data.links) {
550
+ throw new RenderError(
551
+ `The Structured Text document contains an 'itemLink' node, but .links is not present!`,
552
+ node
553
+ );
554
+ }
555
+ const item = props.data.links.find((item2) => item2.id === node.item);
556
+ if (!item) {
557
+ throw new RenderError(
558
+ `The Structured Text document contains an 'itemLink' node, but cannot find a record with ID ${node.item} inside .links!`,
559
+ node
560
+ );
561
+ }
562
+ return appendKeyToValidElement(
563
+ props.renderLinkToRecord({
564
+ record: item,
565
+ children,
566
+ transformedMeta: node.meta ? (props.metaTransformer || defaultMetaTransformer)({
567
+ node,
568
+ meta: node.meta
569
+ }) : null
570
+ }),
571
+ key
572
+ );
573
+ }),
574
+ renderNodeRule(isBlock, ({ node, key }) => {
575
+ if (!props.renderBlock) {
576
+ throw new RenderError(
577
+ `The Structured Text document contains a 'block' node, but no 'renderBlock' prop is specified!`,
578
+ node
579
+ );
580
+ }
581
+ if (!isStructuredText(props.data) || !props.data.blocks) {
582
+ throw new RenderError(
583
+ `The Structured Text document contains a 'block' node, but .blocks is not present!`,
584
+ node
585
+ );
586
+ }
587
+ const item = props.data.blocks.find(
588
+ (item2) => item2.id === node.item
589
+ );
590
+ if (!item) {
591
+ throw new RenderError(
592
+ `The Structured Text document contains a 'block' node, but cannot find a record with ID ${node.item} inside .blocks!`,
593
+ node
594
+ );
595
+ }
596
+ return appendKeyToValidElement(
597
+ props.renderBlock({ record: item }),
598
+ key
599
+ );
600
+ }),
601
+ ...props.customNodeRules || props.customRules || []
602
+ ]
603
+ });
604
+ };
605
+ }
606
+ });
607
+ const DatocmsStructuredTextPlugin = {
608
+ install: (Vue) => {
609
+ Vue.component("DatocmsStructuredText", StructuredText);
610
+ }
611
+ };
612
+
613
+ var __defProp$1 = Object.defineProperty;
614
+ var __defProps$1 = Object.defineProperties;
615
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
616
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
617
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
618
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
619
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
620
+ var __spreadValues$1 = (a, b) => {
621
+ for (var prop in b || (b = {}))
622
+ if (__hasOwnProp$1.call(b, prop))
623
+ __defNormalProp$1(a, prop, b[prop]);
624
+ if (__getOwnPropSymbols$1)
625
+ for (var prop of __getOwnPropSymbols$1(b)) {
626
+ if (__propIsEnum$1.call(b, prop))
627
+ __defNormalProp$1(a, prop, b[prop]);
628
+ }
629
+ return a;
630
+ };
631
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
632
+ var __objRest = (source, exclude) => {
633
+ var target = {};
634
+ for (var prop in source)
635
+ if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)
636
+ target[prop] = source[prop];
637
+ if (source != null && __getOwnPropSymbols$1)
638
+ for (var prop of __getOwnPropSymbols$1(source)) {
639
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))
640
+ target[prop] = source[prop];
641
+ }
642
+ return target;
643
+ };
644
+ var __async$1 = (__this, __arguments, generator) => {
645
+ return new Promise((resolve, reject) => {
646
+ var fulfilled = (value) => {
647
+ try {
648
+ step(generator.next(value));
649
+ } catch (e) {
650
+ reject(e);
651
+ }
652
+ };
653
+ var rejected = (value) => {
654
+ try {
655
+ step(generator.throw(value));
656
+ } catch (e) {
657
+ reject(e);
658
+ }
659
+ };
660
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
661
+ step((generator = generator.apply(__this, __arguments)).next());
662
+ });
663
+ };
664
+ function useQuerySubscription(options) {
665
+ const _a = options, { enabled, initialData } = _a, other = __objRest(_a, ["enabled", "initialData"]);
666
+ const error = ref(null);
667
+ const data = ref(null);
668
+ const status = ref(
669
+ enabled ? "connecting" : "closed"
670
+ );
671
+ const subscribeToQueryOptions = other;
672
+ watchEffect((onCleanup) => {
673
+ if (enabled === false) {
674
+ status.value = "closed";
675
+ return () => {
676
+ };
677
+ }
678
+ let unsubscribe;
679
+ function subscribe() {
680
+ return __async$1(this, null, function* () {
681
+ unsubscribe = yield subscribeToQuery(__spreadProps$1(__spreadValues$1({}, subscribeToQueryOptions), {
682
+ onStatusChange: (connectionStatus) => {
683
+ status.value = connectionStatus;
684
+ },
685
+ onUpdate: (updateData) => {
686
+ error.value = null;
687
+ data.value = updateData.response.data;
688
+ },
689
+ onChannelError: (errorData) => {
690
+ data.value = null;
691
+ error.value = errorData;
692
+ }
693
+ }));
694
+ });
695
+ }
696
+ subscribe();
697
+ onCleanup(() => {
698
+ if (unsubscribe) {
699
+ unsubscribe();
700
+ }
701
+ });
702
+ });
703
+ return { error, status, data: data || initialData };
704
+ }
705
+
706
+ var __async = (__this, __arguments, generator) => {
707
+ return new Promise((resolve, reject) => {
708
+ var fulfilled = (value) => {
709
+ try {
710
+ step(generator.next(value));
711
+ } catch (e) {
712
+ reject(e);
713
+ }
714
+ };
715
+ var rejected = (value) => {
716
+ try {
717
+ step(generator.throw(value));
718
+ } catch (e) {
719
+ reject(e);
720
+ }
721
+ };
722
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
723
+ step((generator = generator.apply(__this, __arguments)).next());
724
+ });
725
+ };
726
+ const highlightPieces = (textWithHighlightMarker) => {
727
+ return textWithHighlightMarker.split(/\[h\](.+?)\[\/h\]/g).map((text, index) => ({
728
+ text,
729
+ isMatch: index % 2 === 1
730
+ }));
731
+ };
732
+ function useSiteSearch(config) {
733
+ var _a, _b, _c;
734
+ const state = reactive({
735
+ query: ((_a = config.initialState) == null ? void 0 : _a.query) || "",
736
+ page: ((_b = config.initialState) == null ? void 0 : _b.page) || 0,
737
+ locale: (_c = config.initialState) == null ? void 0 : _c.locale
738
+ });
739
+ const error = ref();
740
+ const response = reactive({
741
+ data: [],
742
+ meta: { total_count: 0 }
743
+ });
744
+ error.value = void 0;
745
+ const resultsPerPage = config.resultsPerPage || 8;
746
+ watchEffect((onCleanup) => {
747
+ let isCancelled = false;
748
+ const run = () => __async(this, null, function* () {
749
+ try {
750
+ if (!state.query) {
751
+ response.data = [];
752
+ response.meta = { total_count: 0 };
753
+ return;
754
+ }
755
+ const request = {
756
+ filter: {
757
+ query: state.query,
758
+ locale: state.locale,
759
+ build_trigger_id: config.buildTriggerId
760
+ },
761
+ page: {
762
+ limit: resultsPerPage,
763
+ offset: resultsPerPage * state.page
764
+ }
765
+ };
766
+ if (config.fuzzySearch) {
767
+ request.fuzzy = "true";
768
+ }
769
+ const results = yield config.client.searchResults.rawList(request);
770
+ if (!isCancelled) {
771
+ response.data = results.data;
772
+ response.meta.total_count = results.meta.total_count;
773
+ }
774
+ } catch (e) {
775
+ if (isCancelled) {
776
+ return;
777
+ }
778
+ if (e instanceof Error) {
779
+ error.value = e.message;
780
+ } else {
781
+ error.value = "Unknown error!";
782
+ }
783
+ }
784
+ });
785
+ run();
786
+ onCleanup(() => {
787
+ isCancelled = true;
788
+ });
789
+ });
790
+ const data = computed(() => {
791
+ return state.query && response.data.length > 0 ? {
792
+ pageResults: response.data.map((rawSearchResult) => ({
793
+ id: rawSearchResult.id,
794
+ url: rawSearchResult.attributes.url,
795
+ title: rawSearchResult.attributes.title,
796
+ titleHighlights: rawSearchResult.attributes.highlight.title ? rawSearchResult.attributes.highlight.title.map(highlightPieces) : [],
797
+ bodyExcerpt: rawSearchResult.attributes.body_excerpt,
798
+ bodyHighlights: rawSearchResult.attributes.highlight.body ? rawSearchResult.attributes.highlight.body.map(highlightPieces) : [],
799
+ raw: toRaw(rawSearchResult)
800
+ })),
801
+ totalResults: response.meta.total_count,
802
+ totalPages: Math.ceil(response.meta.total_count / resultsPerPage)
803
+ } : {
804
+ pageResults: [],
805
+ totalResults: 0,
806
+ totalPages: 0
807
+ };
808
+ });
809
+ return {
810
+ state,
811
+ error,
812
+ data
813
+ };
814
+ }
815
+
816
+ var __defProp = Object.defineProperty;
817
+ var __defProps = Object.defineProperties;
818
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
819
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
820
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
821
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
822
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
823
+ var __spreadValues = (a, b) => {
824
+ for (var prop in b || (b = {}))
825
+ if (__hasOwnProp.call(b, prop))
826
+ __defNormalProp(a, prop, b[prop]);
827
+ if (__getOwnPropSymbols)
828
+ for (var prop of __getOwnPropSymbols(b)) {
829
+ if (__propIsEnum.call(b, prop))
830
+ __defNormalProp(a, prop, b[prop]);
831
+ }
832
+ return a;
833
+ };
834
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
835
+ const toHead = (...args) => {
836
+ const tags = [].concat(...args);
837
+ const titleTag = tags && tags.find((t) => t.tag === "title");
838
+ const metaTags = tags ? tags.filter((t) => t.tag === "meta") : [];
839
+ const linkTags = tags ? tags.filter((t) => t.tag === "link") : [];
840
+ return {
841
+ title: titleTag && titleTag.content,
842
+ meta: metaTags.map((tag) => {
843
+ var _a, _b, _c, _d;
844
+ return __spreadProps(__spreadValues({}, tag.attributes), {
845
+ hid: ((_a = tag.attributes) == null ? void 0 : _a.name) || ((_b = tag.attributes) == null ? void 0 : _b.property),
846
+ vmid: ((_c = tag.attributes) == null ? void 0 : _c.name) || ((_d = tag.attributes) == null ? void 0 : _d.property)
847
+ });
848
+ }),
849
+ link: linkTags.map((tag) => {
850
+ var _a, _b, _c, _d, _e, _f;
851
+ return __spreadProps(__spreadValues({}, tag.attributes), {
852
+ hid: ((_a = tag.attributes) == null ? void 0 : _a.name) || `${(_b = tag.attributes) == null ? void 0 : _b.rel}-${(_c = tag.attributes) == null ? void 0 : _c.sizes}`,
853
+ vmid: ((_d = tag.attributes) == null ? void 0 : _d.name) || `${(_e = tag.attributes) == null ? void 0 : _e.rel}-${(_f = tag.attributes) == null ? void 0 : _f.sizes}`
854
+ });
855
+ })
856
+ };
857
+ };
858
+
859
+ export { DatocmsImagePlugin, DatocmsStructuredTextPlugin, Image, StructuredText, appendKeyToValidElement, defaultAdapter, toHead, useQuerySubscription, useSiteSearch };