next-cloudinary 0.3.0 → 0.4.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,900 +0,0 @@
1
- import Image from 'next/image';
2
- import { Cloudinary } from '@cloudinary/url-gen';
3
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
- import Head from 'next/head';
5
- import { useRef } from 'react';
6
- import Script from 'next/script';
7
-
8
- function _extends() {
9
- _extends = Object.assign ? Object.assign.bind() : function (target) {
10
- for (var i = 1; i < arguments.length; i++) {
11
- var source = arguments[i];
12
-
13
- for (var key in source) {
14
- if (Object.prototype.hasOwnProperty.call(source, key)) {
15
- target[key] = source[key];
16
- }
17
- }
18
- }
19
-
20
- return target;
21
- };
22
- return _extends.apply(this, arguments);
23
- }
24
-
25
- function _objectWithoutPropertiesLoose(source, excluded) {
26
- if (source == null) return {};
27
- var target = {};
28
- var sourceKeys = Object.keys(source);
29
- var key, i;
30
-
31
- for (i = 0; i < sourceKeys.length; i++) {
32
- key = sourceKeys[i];
33
- if (excluded.indexOf(key) >= 0) continue;
34
- target[key] = source[key];
35
- }
36
-
37
- return target;
38
- }
39
-
40
- const cropsGravityAuto = ['crop', 'fill', 'lfill', 'fill_pad', 'thumb'];
41
- const props$6 = ['crop', 'gravity'];
42
- function plugin$6({
43
- cldImage,
44
- options
45
- } = {}) {
46
- const {
47
- width,
48
- height,
49
- crop = 'limit'
50
- } = options;
51
- let transformationString = `c_${crop},w_${width}`;
52
-
53
- if (!options.gravity && cropsGravityAuto.includes(crop)) {
54
- options.gravity = 'auto';
55
- }
56
-
57
- if (!['limit'].includes(crop)) {
58
- transformationString = `${transformationString},h_${height}`;
59
- }
60
-
61
- if (options.gravity) {
62
- if (options.gravity === 'auto' && !cropsGravityAuto.includes(crop)) {
63
- console.warn('Auto gravity can only be used with crop, fill, lfill, fill_pad or thumb. Not applying gravity.');
64
- } else {
65
- transformationString = `${transformationString},g_${options.gravity}`;
66
- }
67
- }
68
-
69
- cldImage.resize(transformationString);
70
- }
71
-
72
- var croppingPlugin = {
73
- __proto__: null,
74
- props: props$6,
75
- plugin: plugin$6
76
- };
77
-
78
- const params = ['art', {
79
- prop: 'autoBrightness',
80
- effect: 'auto_brightness'
81
- }, {
82
- prop: 'autoColor',
83
- effect: 'auto_color'
84
- }, {
85
- prop: 'autoContrast',
86
- effect: 'auto_contrast'
87
- }, {
88
- prop: 'assistColorblind',
89
- effect: 'assist_colorblind'
90
- }, 'blackwhite', 'blur', {
91
- prop: 'blurFaces',
92
- effect: 'blur_faces'
93
- }, {
94
- prop: 'blurRegion',
95
- effect: 'blur_region'
96
- }, 'brightness', {
97
- prop: 'brightnessHSB',
98
- effect: 'brightness_hsb'
99
- }, 'cartoonify', 'colorize', 'contrast', 'distort', {
100
- prop: 'fillLight',
101
- effect: 'fill_light'
102
- }, 'gamma', {
103
- prop: 'gradientFade',
104
- effect: 'gradient_fade'
105
- }, 'grayscale', 'improve', 'negate', {
106
- prop: 'oilPaint',
107
- effect: 'oil_paint'
108
- }, 'outline', 'pixelate', {
109
- prop: 'pixelateFaces',
110
- effect: 'pixelate_faces'
111
- }, {
112
- prop: 'pixelateRegion',
113
- effect: 'pixelate_region'
114
- }, 'redeye', {
115
- prop: 'replaceColor',
116
- effect: 'replace_color'
117
- }, 'saturation', 'sepia', 'shadow', 'sharpen', 'shear', {
118
- prop: 'simulateColorblind',
119
- effect: 'simulate_colorblind'
120
- }, 'tint', {
121
- prop: 'unsharpMask',
122
- effect: 'unsharp_mask'
123
- }, 'vectorize', 'vibrance', 'vignette'];
124
- const props$5 = params.map(param => param.prop || param);
125
- function plugin$5({
126
- cldImage,
127
- options
128
- } = {}) {
129
- params.forEach(key => {
130
- const prop = key.prop || key;
131
- const effect = key.effect || key;
132
-
133
- if (options[prop] === true) {
134
- cldImage.effect(`e_${effect}`);
135
- } else if (typeof options[prop] === 'string') {
136
- cldImage.effect(`e_${effect}:${options[prop]}`);
137
- }
138
- });
139
- }
140
-
141
- var effectsPlugin = {
142
- __proto__: null,
143
- props: props$5,
144
- plugin: plugin$5
145
- };
146
-
147
- // aspectRatio
148
- const primary = {
149
- aspectRatio: {
150
- qualifier: 'ar'
151
- },
152
- crop: {
153
- qualifier: 'c'
154
- },
155
- gravity: {
156
- qualifier: 'g'
157
- },
158
- height: {
159
- qualifier: 'h'
160
- },
161
- width: {
162
- qualifier: 'w'
163
- }
164
- };
165
- const position = {
166
- angle: {
167
- qualifier: 'a'
168
- },
169
- gravity: {
170
- qualifier: 'g'
171
- },
172
- x: {
173
- qualifier: 'x'
174
- },
175
- y: {
176
- qualifier: 'y'
177
- }
178
- };
179
- const text = {
180
- color: {
181
- qualifier: 'co',
182
- location: 'primary'
183
- },
184
- fontFamily: {
185
- qualifier: false
186
- },
187
- fontSize: {
188
- qualifier: false
189
- },
190
- fontWeight: {
191
- qualifier: false
192
- },
193
- letterSpacing: {
194
- qualifier: 'letter_spacing'
195
- },
196
- textDecoration: {
197
- qualifier: false
198
- }
199
- };
200
-
201
- const _excluded$3 = ["publicId", "position", "text", "effects"];
202
- const props$4 = ['text', 'overlays'];
203
- const DEFAULT_TEXT_OPTIONS = {
204
- color: 'black',
205
- fontFamily: 'Arial',
206
- fontSize: 200,
207
- fontWeight: 'bold'
208
- };
209
- function plugin$4({
210
- cldImage,
211
- options
212
- } = {}) {
213
- const {
214
- text: text$1,
215
- overlays = []
216
- } = options;
217
- const type = 'overlay';
218
- const typeQualifier = 'l';
219
-
220
- if (Array.isArray(overlays)) {
221
- overlays.forEach(applyOverlay);
222
- }
223
-
224
- if (typeof text$1 === 'string') {
225
- applyOverlay({
226
- text: _extends({}, DEFAULT_TEXT_OPTIONS, {
227
- text: text$1
228
- })
229
- });
230
- } else if (typeof text$1 === 'object') {
231
- applyOverlay({
232
- text: _extends({}, DEFAULT_TEXT_OPTIONS, text$1)
233
- });
234
- }
235
- /**
236
- * applyOverlay
237
- */
238
-
239
-
240
- function applyOverlay(_ref) {
241
- let {
242
- publicId,
243
- position: position$1,
244
- text: text$1,
245
- effects: layerEffects = []
246
- } = _ref,
247
- options = _objectWithoutPropertiesLoose(_ref, _excluded$3);
248
-
249
- const hasPublicId = typeof publicId === 'string';
250
- const hasText = typeof text$1 === 'object' || typeof text$1 === 'string';
251
- const hasPosition = typeof position$1 === 'object';
252
-
253
- if (!hasPublicId && !hasText) {
254
- console.warn(`An ${type} is missing Public ID or Text`);
255
- return;
256
- } // Start to construct the transformation string using text or the public ID
257
- // if it's image-based
258
-
259
-
260
- let layerTransformation;
261
-
262
- if (hasText) {
263
- layerTransformation = `${typeQualifier}_text`;
264
- } else {
265
- layerTransformation = `${typeQualifier}_${publicId.replace(/\//g, ':')}`;
266
- } // Begin organizing transformations based on what it is and the location
267
- // it needs to be placed in the URL
268
-
269
-
270
- const primary$1 = [];
271
- const applied = []; // Gemeral options
272
-
273
- Object.keys(options).forEach(key => {
274
- if (!primary[key]) return;
275
- const {
276
- qualifier
277
- } = primary[key];
278
- primary$1.push(`${qualifier}_${options[key]}`);
279
- }); // Layer effects
280
-
281
- layerEffects.forEach(effect => {
282
- Object.keys(effect).forEach(key => {
283
- if (!primary[key]) return;
284
- const {
285
- qualifier
286
- } = primary[key];
287
- primary$1.push(`${qualifier}_${effect[key]}`);
288
- });
289
- }); // Text styling
290
-
291
- if (hasText) {
292
- if (typeof text$1 === 'string') {
293
- text$1 = _extends({}, DEFAULT_TEXT_OPTIONS, {
294
- text: text$1
295
- });
296
- }
297
-
298
- const textTransformations = [];
299
- Object.keys(text$1).forEach(key => {
300
- if (!text[key]) return;
301
- const {
302
- qualifier,
303
- location
304
- } = text[key];
305
-
306
- if (location === 'primary') {
307
- primary$1.push(`${qualifier}_${text$1[key]}`);
308
- } else {
309
- textTransformations.push(text$1[key]);
310
- }
311
- });
312
- layerTransformation = `${layerTransformation}:${textTransformations.join('_')}:${text$1.text}`;
313
- } // Positioning
314
-
315
-
316
- if (hasPosition) {
317
- Object.keys(position$1).forEach(key => {
318
- if (!position[key]) return;
319
- const {
320
- qualifier
321
- } = position[key];
322
- applied.push(`${qualifier}_${position$1[key]}`);
323
- });
324
- } // Add all primary transformations
325
-
326
-
327
- layerTransformation = `${layerTransformation},${primary$1.join(',')}`; // Add all applied transformations
328
-
329
- layerTransformation = `${layerTransformation}/fl_layer_apply,fl_no_overflow`;
330
-
331
- if (applied.length > 0) {
332
- layerTransformation = `${layerTransformation},${applied.join(',')}`;
333
- } // Finally add it to the image
334
-
335
-
336
- cldImage.addTransformation(layerTransformation);
337
- }
338
- }
339
-
340
- var overlaysPlugin = {
341
- __proto__: null,
342
- props: props$4,
343
- DEFAULT_TEXT_OPTIONS: DEFAULT_TEXT_OPTIONS,
344
- plugin: plugin$4
345
- };
346
-
347
- const props$3 = ['rawTransformations'];
348
- function plugin$3({
349
- cldImage,
350
- options
351
- } = {}) {
352
- const {
353
- rawTransformations = []
354
- } = options;
355
- rawTransformations.forEach(transformation => {
356
- cldImage.addTransformation(transformation);
357
- });
358
- }
359
-
360
- var rawTransformationsPlugin = {
361
- __proto__: null,
362
- props: props$3,
363
- plugin: plugin$3
364
- };
365
-
366
- const props$2 = ['removeBackground'];
367
- function plugin$2({
368
- cldImage,
369
- options
370
- } = {}) {
371
- const {
372
- removeBackground = false
373
- } = options;
374
-
375
- if (removeBackground) {
376
- cldImage.effect('e_background_removal');
377
- }
378
- }
379
-
380
- var removeBackgroundPlugin = {
381
- __proto__: null,
382
- props: props$2,
383
- plugin: plugin$2
384
- };
385
-
386
- const _excluded$2 = ["publicId", "type", "position", "text", "effects"];
387
- const props$1 = ['underlay', 'underlays'];
388
- function plugin$1({
389
- cldImage,
390
- options
391
- } = {}) {
392
- const {
393
- underlay,
394
- underlays = []
395
- } = options;
396
- const typeQualifier = 'u';
397
-
398
- if (Array.isArray(underlays)) {
399
- underlays.forEach(applyUnderlay);
400
- }
401
-
402
- if (typeof underlay === 'string') {
403
- const underlayOptions = {
404
- publicId: underlay,
405
- crop: 'fill'
406
- };
407
-
408
- if (options.width) {
409
- underlayOptions.width = options.width;
410
- }
411
-
412
- if (options.height) {
413
- underlayOptions.height = options.height;
414
- }
415
-
416
- applyUnderlay(underlayOptions);
417
- }
418
- /**
419
- * applyUnderlay
420
- */
421
-
422
-
423
- function applyUnderlay(_ref) {
424
- let {
425
- publicId,
426
- type,
427
- position: position$1,
428
- effects: layerEffects = []
429
- } = _ref,
430
- options = _objectWithoutPropertiesLoose(_ref, _excluded$2);
431
-
432
- const hasPublicId = typeof publicId === 'string';
433
- const hasPosition = typeof position$1 === 'object';
434
-
435
- if (!hasPublicId) {
436
- console.warn(`An ${type} is missing a Public ID`);
437
- return;
438
- } // Start to construct the transformation string using text or the public ID
439
- // if it's image-based
440
-
441
-
442
- let layerTransformation = `${typeQualifier}_${publicId.replace(/\//g, ':')}`; // Begin organizing transformations based on what it is and the location
443
- // it needs to be placed in the URL
444
-
445
- const primary$1 = [];
446
- const applied = []; // Gemeral options
447
-
448
- Object.keys(options).forEach(key => {
449
- if (!primary[key]) return;
450
- const {
451
- qualifier
452
- } = primary[key];
453
- primary$1.push(`${qualifier}_${options[key]}`);
454
- }); // Layer effects
455
-
456
- layerEffects.forEach(effect => {
457
- Object.keys(effect).forEach(key => {
458
- if (!primary[key]) return;
459
- const {
460
- qualifier
461
- } = primary[key];
462
- primary$1.push(`${qualifier}_${effect[key]}`);
463
- });
464
- }); // Positioning
465
-
466
- if (hasPosition) {
467
- Object.keys(position$1).forEach(key => {
468
- if (!position[key]) return;
469
- const {
470
- qualifier
471
- } = position[key];
472
- applied.push(`${qualifier}_${position$1[key]}`);
473
- });
474
- } // Add all primary transformations
475
-
476
-
477
- layerTransformation = `${layerTransformation},${primary$1.join(',')}`; // Add all applied transformations
478
-
479
- layerTransformation = `${layerTransformation}/fl_layer_apply,fl_no_overflow`;
480
-
481
- if (applied.length > 0) {
482
- layerTransformation = `${layerTransformation},${applied.join(',')}`;
483
- } // Finally add it to the image
484
-
485
-
486
- cldImage.addTransformation(layerTransformation);
487
- }
488
- }
489
-
490
- var underlaysPlugin = {
491
- __proto__: null,
492
- props: props$1,
493
- plugin: plugin$1
494
- };
495
-
496
- const props = ['zoompan'];
497
- function plugin({
498
- cldImage,
499
- options
500
- } = {}) {
501
- const {
502
- zoompan = false
503
- } = options;
504
- const overrides = {};
505
-
506
- if (zoompan === true) {
507
- cldImage.effect('e_zoompan');
508
- } else if (typeof zoompan === 'string') {
509
- if (zoompan === 'loop') {
510
- cldImage.effect('e_zoompan');
511
- cldImage.effect('e_loop');
512
- } else {
513
- cldImage.effect(`e_zoompan:${zoompan}`);
514
- }
515
- } else if (typeof zoompan === 'object') {
516
- let zoompanEffect = 'e_zoompan';
517
-
518
- if (typeof zoompan.options === 'string') {
519
- zoompanEffect = `${zoompanEffect}${zoompan.options}`;
520
- }
521
-
522
- cldImage.effect(zoompanEffect);
523
- let loopEffect;
524
-
525
- if (zoompan.loop === true) {
526
- loopEffect = 'e_loop';
527
- } else if (typeof zoompan.loop === 'string') {
528
- loopEffect = `e_loop${zoompan.loop}`;
529
- }
530
-
531
- if (loopEffect) {
532
- cldImage.effect(loopEffect);
533
- }
534
- }
535
-
536
- if (zoompan !== false) {
537
- overrides.format = 'gif';
538
- }
539
-
540
- return {
541
- options: overrides
542
- };
543
- }
544
-
545
- var zoompanPlugin = {
546
- __proto__: null,
547
- props: props,
548
- plugin: plugin
549
- };
550
-
551
- const transformationPlugins = [// Background Removal must always come first
552
- removeBackgroundPlugin, croppingPlugin, effectsPlugin, overlaysPlugin, underlaysPlugin, zoompanPlugin, // Raw transformations needs to be last simply to make sure
553
- // it's always expected to applied the same way
554
- rawTransformationsPlugin];
555
- let cld;
556
- /**
557
- * constructCloudinaryUrl
558
- */
559
-
560
- function constructCloudinaryUrl({
561
- options,
562
- config
563
- }) {
564
- if (!cld) {
565
- cld = new Cloudinary(_extends({
566
- cloud: {
567
- cloudName: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME
568
- },
569
- url: {
570
- // Used to avoid issues with SSR particularly for the blurred placeholder
571
- analytics: false
572
- }
573
- }, config));
574
- }
575
-
576
- const publicId = getPublicId(options.src);
577
- const cldImage = cld.image(publicId);
578
- transformationPlugins.forEach(({
579
- plugin
580
- }) => {
581
- const {
582
- options: pluginOptions
583
- } = plugin({
584
- cldImage,
585
- options
586
- }) || {};
587
-
588
- if (pluginOptions != null && pluginOptions.format) {
589
- options.format = pluginOptions.format;
590
- }
591
- });
592
- return cldImage.setDeliveryType(options.deliveryType || 'upload').format(options.format || 'auto').delivery(`q_${options.quality || 'auto'}`).toURL();
593
- }
594
- /**
595
- * Retrieves the public id of a cloudiary image url. If no url is recognized it returns the parameter it self.
596
- * If it's recognized that is a url and it's not possible to get the public id, it warns the user.
597
- *
598
- * @param {string} src The cloudiary url or public id.
599
- *
600
- * @return {string} The images public id
601
- */
602
-
603
- function getPublicId(src) {
604
- if (typeof src !== 'string') {
605
- throw new Error(`Invalid src of type ${typeof src}`);
606
- }
607
-
608
- if (src.includes('res.cloudinary.com')) {
609
- const regexWithTransformations = /(https?)\:\/\/(res.cloudinary.com)\/([^\/]+)\/(image|video|raw)\/(upload|authenticated)\/(.*)\/(v[0-9]+)\/(.+)(?:\.[a-z]{3})?/;
610
- const regexWithoutTransformations = /(https?)\:\/\/(res.cloudinary.com)\/([^\/]+)\/(image|video|raw)\/(upload|authenticated)\/(v[0-9]+)\/(.+)(?:\.[a-z]{3})?/;
611
- const withTransformations = src.match(regexWithTransformations);
612
- const withoutTransformations = src.match(regexWithoutTransformations);
613
-
614
- if (withTransformations) {
615
- return withTransformations[withTransformations.length - 1];
616
- } else if (withoutTransformations) {
617
- return withoutTransformations[withoutTransformations.length - 1];
618
- } else {
619
- console.warn(`Not possible to retrieve the publicUrl from ${src}, make sure it's a valid cloudinary image url.`);
620
- }
621
- }
622
-
623
- return src;
624
- }
625
- /**
626
- * createPlaceholderUrl
627
- */
628
-
629
- function createPlaceholderUrl({
630
- src,
631
- placeholder = true,
632
- config
633
- }) {
634
- const rawTransformations = [];
635
-
636
- if (placeholder === 'grayscale') {
637
- rawTransformations.push('e_grayscale');
638
- }
639
-
640
- if (typeof placeholder === 'string' && placeholder.includes('color:')) {
641
- const color = placeholder.split(':').splice(1).join(':');
642
- rawTransformations.push('e_grayscale');
643
- rawTransformations.push(`e_colorize:60,co_${color}`);
644
- }
645
-
646
- return constructCloudinaryUrl({
647
- options: {
648
- src,
649
- width: 100,
650
- quality: 1,
651
- rawTransformations
652
- },
653
- config
654
- });
655
- }
656
-
657
- function cloudinaryLoader(defaultOptions, cldOptions, cldConfig = {}) {
658
- return constructCloudinaryUrl({
659
- options: _extends({}, defaultOptions, cldOptions),
660
- config: cldConfig
661
- });
662
- }
663
-
664
- const CldImage = props => {
665
- const CLD_OPTIONS = [];
666
- transformationPlugins.forEach(({
667
- props: _props = []
668
- }) => {
669
- _props.forEach(prop => {
670
- if (CLD_OPTIONS.includes(prop)) {
671
- throw new Error(`Option ${prop} already exists!`);
672
- }
673
-
674
- CLD_OPTIONS.push(prop);
675
- });
676
- }); // Construct the base Image component props by filtering out Cloudinary-specific props
677
-
678
- const imageProps = {};
679
- Object.keys(props).filter(key => !CLD_OPTIONS.includes(key)).forEach(key => imageProps[key] = props[key]); // Construct Cloudinary-specific props by looking for values for any of the supported prop keys
680
-
681
- const cldOptions = {};
682
- CLD_OPTIONS.forEach(key => {
683
- if (props[key]) {
684
- cldOptions[key] = props[key];
685
- }
686
- }); // If we see a placeholder option, configure a Cloudinary-based URL.
687
- // The resulting image will always be blurred per Next.js, so we're
688
- // limited on options for placeholders.
689
- //
690
- // We need to do this logic here as we potentially need to mutate
691
- // an Image component prop as opposed to simply the URL
692
- //
693
- // https://nextjs.org/docs/api-reference/next/image#blurdataurl
694
-
695
- if (imageProps.placeholder) {
696
- const publicId = getPublicId(props.src);
697
- imageProps.blurDataURL = createPlaceholderUrl({
698
- src: publicId,
699
- placeholder: props.placeholder
700
- });
701
-
702
- if (imageProps.placeholder !== 'blur') {
703
- imageProps.placeholder = 'blur';
704
- }
705
- }
706
-
707
- return /*#__PURE__*/jsx(Image, _extends({}, imageProps, {
708
- loader: options => cloudinaryLoader(_extends({}, imageProps, {
709
- options
710
- }), cldOptions)
711
- }));
712
- };
713
-
714
- const _excluded$1 = ["excludeTags", "twitterTitle"];
715
- const IMAGE_WIDTH = 2400;
716
- const IMAGE_HEIGHT = 1200;
717
- const TWITTER_CARD = 'summary_large_image';
718
-
719
- const CldOgImage = _ref => {
720
- let {
721
- excludeTags = [],
722
- twitterTitle
723
- } = _ref,
724
- props = _objectWithoutPropertiesLoose(_ref, _excluded$1);
725
-
726
- const options = _extends({}, props, {
727
- width: props.width || IMAGE_WIDTH,
728
- height: props.height || IMAGE_HEIGHT,
729
- crop: props.crop || 'fill',
730
- gravity: props.gravity || 'center'
731
- });
732
-
733
- const ogImageUrl = constructCloudinaryUrl({
734
- options
735
- }); // We need to include the tags within the Next.js Head component rather than
736
- // direcly adding them inside of the Head otherwise we get unexpected results
737
-
738
- return /*#__PURE__*/jsxs(Head, {
739
- children: [/*#__PURE__*/jsx("meta", {
740
- property: "og:image",
741
- content: ogImageUrl
742
- }), /*#__PURE__*/jsx("meta", {
743
- property: "og:image:secure_url",
744
- content: ogImageUrl
745
- }), /*#__PURE__*/jsx("meta", {
746
- property: "og:image:width",
747
- content: options.width
748
- }), /*#__PURE__*/jsx("meta", {
749
- property: "og:image:height",
750
- content: options.height
751
- }), options.alt && /*#__PURE__*/jsx("meta", {
752
- property: "og:image:alt",
753
- content: options.alt
754
- }), !excludeTags.includes('twitter:title') && /*#__PURE__*/jsx("meta", {
755
- property: "twitter:title",
756
- content: twitterTitle || ' '
757
- }), /*#__PURE__*/jsx("meta", {
758
- property: "twitter:card",
759
- content: TWITTER_CARD
760
- }), /*#__PURE__*/jsx("meta", {
761
- property: "twitter:image",
762
- content: ogImageUrl
763
- })]
764
- });
765
- };
766
-
767
- const CldUploadWidget = ({
768
- children,
769
- onUpload,
770
- options,
771
- signed,
772
- signatureEndpoint
773
- }) => {
774
- const cloudinary = useRef();
775
- const widget = useRef();
776
- /**
777
- * generateSignature
778
- * @description Makes a request to an endpoint to sign Cloudinary parameters as part of widget creation
779
- */
780
-
781
- function generateSignature(callback, paramsToSign) {
782
- fetch(signatureEndpoint, {
783
- method: "POST",
784
- body: JSON.stringify({
785
- paramsToSign
786
- })
787
- }).then(r => r.json()).then(({
788
- signature
789
- }) => {
790
- callback(signature);
791
- });
792
- }
793
- /**
794
- * createWidget
795
- * @description Creates a new instance of the Cloudinary widget and stores in a ref
796
- */
797
-
798
-
799
- function createWidget() {
800
- var _cloudinary$current;
801
-
802
- // When creating a signed upload, you need to provide both your Cloudinary API Key
803
- // as well as a signature generator function that will sign any paramters
804
- // either on page load or during the upload process. Read more about signed uploads at:
805
- // https://cloudinary.com/documentation/upload_widget#signed_uploads
806
- const totalOptions = _extends({}, options, !!signed && {
807
- uploadSignature: generateSignature
808
- }); // no need for apiSecret because of api/sign-cloudinary-params
809
-
810
-
811
- if (signed && !totalOptions.apiKey) {
812
- return new Error("Signed Upload needs apiKey!");
813
- }
814
-
815
- return (_cloudinary$current = cloudinary.current) == null ? void 0 : _cloudinary$current.createUploadWidget(totalOptions, function (error, result) {
816
- // The callback is a bit more chatty than failed or success so
817
- // only trigger when one of those are the case. You can additionally
818
- // create a separate handler such as onEvent and trigger it on
819
- // ever occurance
820
- if (error || result.event === "success") {
821
- onUpload(error, result, widget == null ? void 0 : widget.current);
822
- }
823
- });
824
- }
825
- /**
826
- * open
827
- * @description When triggered, uses the current widget instance to open the upload modal
828
- */
829
-
830
-
831
- function open() {
832
- if (!(widget != null && widget.current)) {
833
- widget.current = createWidget();
834
- }
835
-
836
- (widget == null ? void 0 : widget.current) && widget.current.open();
837
- }
838
- /**
839
- * handleOnLoad
840
- * @description Stores the Cloudinary window instance to a ref when the widget script loads
841
- */
842
-
843
-
844
- function handleOnLoad() {
845
- cloudinary.current = window.cloudinary;
846
- }
847
-
848
- return /*#__PURE__*/jsxs(Fragment, {
849
- children: [children({
850
- cloudinary: cloudinary.current,
851
- widget: widget.current,
852
- open
853
- }), /*#__PURE__*/jsx(Script, {
854
- id: `cloudinary-${Math.floor(Math.random() * 100)}`,
855
- src: "https://widget.cloudinary.com/v2.0/global/all.js",
856
- onLoad: handleOnLoad,
857
- onError: e => {
858
- console.error("Script failed to load", e);
859
- }
860
- })]
861
- });
862
- };
863
-
864
- const _excluded = ["onUpload", "options", "signed", "label", "children"];
865
-
866
- const CldUploadButton = _ref => {
867
- let {
868
- onUpload,
869
- options,
870
- signed,
871
- children
872
- } = _ref,
873
- props = _objectWithoutPropertiesLoose(_ref, _excluded);
874
-
875
- return /*#__PURE__*/jsx(Fragment, {
876
- children: /*#__PURE__*/jsx(CldUploadWidget, {
877
- signed: signed,
878
- options: options,
879
- onUpload: onUpload,
880
- signatureEndpoint: signed != null ? signed : props.signatureEndpoint,
881
- children: ({
882
- open
883
- }) => {
884
- function handleOnClick(e) {
885
- e.preventDefault();
886
- open();
887
- }
888
-
889
- return /*#__PURE__*/jsx("button", _extends({
890
- onClick: handleOnClick
891
- }, props, {
892
- children: children
893
- }));
894
- }
895
- })
896
- });
897
- };
898
-
899
- export { CldImage, CldOgImage, CldUploadButton, CldUploadWidget, cloudinaryLoader, position, primary, text };
900
- //# sourceMappingURL=next-cloudinary.modern.mjs.map