@dtwojs/cloudinary 2.7.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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Dtwo Community
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # @dtwojs/cloudinary
2
+
3
+ [Cloudinary](https://cloudinary.com) integration with for [Dtwo](https://dtwojs.web.app)
4
+
5
+ > This is a module for version 3.X of Dtwo.
6
+
7
+ ## Features
8
+
9
+ - Dtwo 3 ready
10
+ - Useful `CldImage`, `CldOgImage` & `CldVideoPlayer` components
11
+ - Handy `useCldImageUrl` composable
12
+ - Automatically optimize images and deliver in modern formats
13
+ - Remove backgrounds from images
14
+ - Dynamically add image and text overlays to images
15
+
16
+ ## Quick Setup
17
+
18
+ 1. Add `@dtwojs/cloudinary` dependency to your project
19
+
20
+ ```bash
21
+ yarn add @dtwojs/cloudinary
22
+ npm install @dtwojs/cloudinary
23
+ ```
24
+
25
+ 2. Add `@dtwojs/cloudinary` to the `modules` section of `dtwo.config.ts`
26
+
27
+ ```js
28
+ export default defineDtwoConfig({
29
+ modules: ['@dtwojs/cloudinary'],
30
+ })
31
+ ```
32
+
33
+ 3. Create .env file with following `CLOUDINARY_CLOUD_NAME` variable:
34
+
35
+ ```bash
36
+ CLOUDINARY_CLOUD_NAME=<YOUR_CLOUDINARY_CLOUD_NAME>
37
+ ```
38
+
39
+ And that's it! You can now use Cloudinary in Dtwo ✨
40
+
41
+ ```html
42
+ <template>
43
+ <CldImage
44
+ src="cld-sample-5"
45
+ width="987"
46
+ height="987"
47
+ alt="My Awesome Image"
48
+ />
49
+ </template>
50
+ ```
51
+
52
+ ## License
53
+
54
+ [MIT License](./LICENSE)
@@ -0,0 +1,5 @@
1
+ module.exports = function(...args) {
2
+ return import('./module.mjs').then(m => m.default.call(this, ...args))
3
+ }
4
+ const _meta = module.exports.meta = require('./module.json')
5
+ module.exports.getMeta = () => Promise.resolve(_meta)
@@ -0,0 +1,14 @@
1
+ import * as _dtwo_schema from '@dtwo/schema';
2
+ import { ConfigOptions } from '@cloudinary-util/url-loader';
3
+
4
+ type ModuleOptions = {
5
+ cloudName?: string;
6
+ uploadPreset?: string;
7
+ apiKey?: string;
8
+ analytics?: boolean;
9
+ cloud?: ConfigOptions["cloud"];
10
+ url?: ConfigOptions["url"];
11
+ };
12
+ declare const _default: _dtwo_schema.DtwoModule<ModuleOptions>;
13
+
14
+ export { ModuleOptions, _default as default };
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "@dtwojs/cloudinary",
3
+ "configKey": "cloudinary",
4
+ "version": "2.7.0"
5
+ }
@@ -0,0 +1,45 @@
1
+ import { defineDtwoModule, createResolver, addImportsDir, addComponentsDir } from '@dtwo/kit';
2
+ import { fileURLToPath } from 'url';
3
+ import { defu } from 'defu';
4
+
5
+ const module = defineDtwoModule({
6
+ meta: {
7
+ name: "@dtwojs/cloudinary",
8
+ configKey: "cloudinary"
9
+ },
10
+ defaults: {
11
+ cloudName: process.env.CLOUDINARY_CLOUD_NAME,
12
+ analytics: true
13
+ },
14
+ setup(options, dtwo) {
15
+ const resolver = createResolver(import.meta.url);
16
+ dtwo.options.runtimeConfig.public.cloudinary = defu(
17
+ dtwo.options.runtimeConfig.public.cloudinary,
18
+ {
19
+ cloudName: process.env.CLOUDINARY_CLOUD_NAME || options.cloudName,
20
+ uploadPreset: process.env.CLOUDINARY_UPLOAD_PRESET || options.uploadPreset,
21
+ apiKey: process.env.CLOUDINARY_API_KEY || options.apiKey,
22
+ analytics: options.analytics,
23
+ cloud: options.cloud,
24
+ url: options.url
25
+ }
26
+ );
27
+ if (!dtwo.options.runtimeConfig.public.cloudinary?.cloudName)
28
+ console.warn(
29
+ "`[@dtwojs/cloudinary]` Environment variable `CLOUDINARY_CLOUD_NAME` or property `cloudinary.cloudName` missing"
30
+ );
31
+ const runtimeDir = fileURLToPath(new URL("./runtime", import.meta.url));
32
+ dtwo.options.build.transpile.push(runtimeDir);
33
+ addImportsDir(resolver.resolve(runtimeDir, "composables"));
34
+ addComponentsDir({
35
+ path: resolver.resolve(runtimeDir, "components"),
36
+ pathPrefix: false,
37
+ prefix: "",
38
+ // @ts-ignore
39
+ level: 999,
40
+ global: true
41
+ });
42
+ }
43
+ });
44
+
45
+ export { module as default };
@@ -0,0 +1,202 @@
1
+ <script setup lang="ts">
2
+ // This is working in dev playground but does not work in the published package
3
+
4
+ // import type { AssetOptions } from "@cloudinary-util/url-loader";
5
+ // import type { ConfigOptions } from "@cloudinary-util/url-loader";
6
+ import { useCldImageUrl } from "../composables/useCldImageUrl";
7
+ import { ref } from "kdu";
8
+ import { Image } from "unpic-kdu";
9
+
10
+ interface AssetOptionsResize {
11
+ crop?: string;
12
+ width?: number | string;
13
+ }
14
+
15
+ interface ImageOptionsFillBackground {
16
+ crop?: string;
17
+ gravity?: string;
18
+ prompt?: string;
19
+ }
20
+
21
+ interface AssetOptions {
22
+ assetType?: string;
23
+ crop?: string;
24
+ deliveryType?: string;
25
+ effects?: Array<any>;
26
+ flags?: Array<string> | object;
27
+ format?: string;
28
+ gravity?: string;
29
+ height?: string | number;
30
+ overlays?: Array<any>;
31
+ quality?: number | string;
32
+ rawTransformations?: string[];
33
+ removeBackground?: boolean;
34
+ sanitize?: boolean;
35
+ resize?: AssetOptionsResize;
36
+ seoSuffix?: string;
37
+ src: string;
38
+ text?: any;
39
+ transformations?: Array<string>;
40
+ underlay?: string;
41
+ underlays?: Array<any>;
42
+ version?: number | string;
43
+ width?: string | number;
44
+ widthResize?: string | number;
45
+ zoom?: string;
46
+ }
47
+
48
+ type ImageOptionsRecolorPrompt = string | Array<string>;
49
+
50
+ interface ImageOptionsRecolor {
51
+ prompt?: ImageOptionsRecolorPrompt;
52
+ to?: string;
53
+ multiple?: boolean;
54
+ }
55
+
56
+ interface ImageOptionsZoomPan {
57
+ loop: string | boolean;
58
+ options: string;
59
+ }
60
+
61
+ type ImageOptionsRemovePrompt = string | Array<string>;
62
+
63
+ interface ImageOptionsRemove {
64
+ prompt?: ImageOptionsRemovePrompt;
65
+ region?: [300, 200, 1900, 3500];
66
+ multiple?: boolean;
67
+ removeShadow?: boolean;
68
+ }
69
+
70
+ interface ImageOptionsGenerativeReplace {
71
+ to: string;
72
+ from: string;
73
+ preserveGeometry?: boolean;
74
+ }
75
+ interface ImageOptions extends AssetOptions {
76
+ zoompan?: string | boolean | ImageOptionsZoomPan;
77
+ fillBackground?: boolean | ImageOptionsFillBackground;
78
+ recolor?: ImageOptionsRecolorPrompt | ImageOptionsRecolor;
79
+ remove?: ImageOptionsRemovePrompt | ImageOptionsRemove;
80
+ replace?: Array<string | boolean> | ImageOptionsGenerativeReplace;
81
+ restore?: boolean;
82
+ }
83
+
84
+ export interface CldImageProps extends ImageOptions {
85
+ loading?: "eager" | "lazy";
86
+ fetchPriority?: "high" | "low" | "auto";
87
+ // Adding below as required props to promote good patterns in developing images
88
+ alt: string;
89
+ width: string | number;
90
+ height: string | number;
91
+ // Cloudinary URL Loader props
92
+ // Cannot use `ConfigOptions` due to the same issue as mentioned at the top
93
+ config?: any;
94
+ // Unpic props
95
+ layout?: "constrained" | "fullWidth" | "fixed";
96
+ priority?: boolean;
97
+ background?: "auto" | string;
98
+ // Cloudinary missing effect props
99
+ blur?: string | number;
100
+ pixelate?: boolean;
101
+ grayscale?: boolean;
102
+ tint?: string | number;
103
+ opacity?: string | number;
104
+ shear?: string;
105
+ border?: string;
106
+ loaderOptions?: {
107
+ width: number | string;
108
+ };
109
+ }
110
+
111
+ const props = defineProps<CldImageProps>();
112
+
113
+ // eslint-disable-next-line kdu/no-setup-props-destructure
114
+ const { config, loaderOptions, ...options } = props;
115
+
116
+ const { url } = useCldImageUrl({ options, config });
117
+
118
+ const transformUrl = () => {
119
+ const options = {
120
+ ...props,
121
+ };
122
+
123
+ options.width =
124
+ typeof options.width === "string" ? parseInt(options.width) : options.width;
125
+ options.height =
126
+ typeof options.height === "string"
127
+ ? parseInt(options.height)
128
+ : options.height;
129
+
130
+ let widthResize;
131
+
132
+ if (
133
+ typeof loaderOptions?.width === "number" &&
134
+ typeof options.width === "number" &&
135
+ loaderOptions.width !== options.width
136
+ ) {
137
+ widthResize = loaderOptions.width;
138
+ } else if (
139
+ typeof loaderOptions?.width === "number" &&
140
+ typeof options?.width !== "number"
141
+ ) {
142
+ widthResize = loaderOptions.width;
143
+ options.width = widthResize;
144
+ }
145
+
146
+ // If we have a resize width that's smaller than the user-defined width, we want to give the
147
+ // ability to perform a final resize on the image without impacting any of the effects like text
148
+ // overlays that may depend on the size to work properly
149
+
150
+ if (options.width && widthResize && widthResize < options.width) {
151
+ options.widthResize = loaderOptions?.width;
152
+ }
153
+
154
+ const { url } = useCldImageUrl({ options, config });
155
+
156
+ return url;
157
+ };
158
+
159
+ const imgKey = ref("image-key");
160
+
161
+ const handleError = async (payload: Event) => {
162
+ const result = await pollForProcessingImage(payload);
163
+
164
+ if (result) imgKey.value = `${imgKey.value}-${Math.random()}`;
165
+ };
166
+
167
+ const pollForProcessingImage = async (options: Event): Promise<boolean> => {
168
+ const { src } = options.target as EventTarget & { src: string };
169
+ try {
170
+ await new Promise((resolve, reject) => {
171
+ fetch(src).then((res) => {
172
+ if (!res.ok) {
173
+ reject(res);
174
+ return;
175
+ }
176
+ resolve(res);
177
+ });
178
+ });
179
+ } catch (e: any) {
180
+ if (e.status === 423) {
181
+ return await pollForProcessingImage(options);
182
+ }
183
+ return false;
184
+ }
185
+ return true;
186
+ };
187
+ </script>
188
+
189
+ <template>
190
+ <Image
191
+ :key="imgKey"
192
+ :src="url"
193
+ :layout="layout || 'constrained'"
194
+ :width="width"
195
+ :height="height"
196
+ k-bind="$attrs"
197
+ :priority="priority"
198
+ cdn="cloudinary"
199
+ :transformer="transformUrl"
200
+ @error="handleError"
201
+ />
202
+ </template>
@@ -0,0 +1,65 @@
1
+ <script setup lang="ts">
2
+ import { useHead } from "@kdhead/kdu";
3
+ import { useRuntimeConfig } from "#imports";
4
+ import { ref } from "kdu";
5
+
6
+ const cloudinaryRef = ref();
7
+
8
+ type MediaLibraryProps = {
9
+ cloudName?: string;
10
+ apiKey: string;
11
+ username?: string;
12
+ useSaml?: boolean;
13
+ buttonId: string;
14
+ params?: Record<string, any>;
15
+ };
16
+
17
+ const props = defineProps<MediaLibraryProps>();
18
+
19
+ const emit = defineEmits(["onInsert"]);
20
+
21
+ const handleOnLoad = () => {
22
+ if ("cloudinary" in window) {
23
+ cloudinaryRef.value = window.cloudinary;
24
+
25
+ const options = Object.fromEntries(
26
+ Object.entries(props).filter((elem) => Boolean(elem[1]))
27
+ );
28
+
29
+ cloudinaryRef.value.createMediaLibrary(
30
+ {
31
+ inline_container: "#widget_container",
32
+ cloud_name:
33
+ props.cloudName || useRuntimeConfig().public.cloudinary.cloudName,
34
+ api_key: props.apiKey || useRuntimeConfig().public.cloudinary.apiKey,
35
+ ...options,
36
+ ...props.params,
37
+ },
38
+ {
39
+ insertHandler: function (data: unknown) {
40
+ emit("onInsert", data);
41
+ },
42
+ },
43
+ document.getElementById(props.buttonId)
44
+ );
45
+ }
46
+ };
47
+
48
+ useHead({
49
+ script: [
50
+ {
51
+ id: `cloudinary-media-library-${Math.floor(Math.random() * 100)}`,
52
+ src: `https://media-library.cloudinary.com/global/all.js`,
53
+ onload: handleOnLoad,
54
+ onerror: (e) =>
55
+ console.error(
56
+ `Failed to load Cloudinary Media Library: ${(e as any).message}`
57
+ ),
58
+ },
59
+ ],
60
+ });
61
+ </script>
62
+
63
+ <template>
64
+ <div id="widget_container" />
65
+ </template>
@@ -0,0 +1,174 @@
1
+ <script setup lang="ts">
2
+ import { useCldImageUrl } from "../composables/useCldImageUrl";
3
+ import { computed } from "kdu";
4
+ import { useRouter } from "#imports";
5
+
6
+ const TWITTER_CARD = "summary_large_image";
7
+ const OG_IMAGE_WIDTH = 2400;
8
+ const OG_IMAGE_WIDTH_RESIZE = 1200;
9
+ const OG_IMAGE_HEIGHT = 1254;
10
+
11
+ const { currentRoute } = useRouter();
12
+
13
+ // Same story as with CldImage.kdu component. Cannot use imported types for props
14
+
15
+ interface AssetOptionsResize {
16
+ crop?: string;
17
+ width?: number | string;
18
+ }
19
+
20
+ interface AssetOptions {
21
+ assetType?: string;
22
+ crop?: string;
23
+ deliveryType?: string;
24
+ effects?: Array<any>;
25
+ flags?: Array<string> | object;
26
+ format?: string;
27
+ gravity?: string;
28
+ height?: string | number;
29
+ overlays?: Array<any>;
30
+ quality?: number | string;
31
+ rawTransformations?: string[];
32
+ removeBackground?: boolean;
33
+ sanitize?: boolean;
34
+ resize?: AssetOptionsResize;
35
+ seoSuffix?: string;
36
+ src: string;
37
+ text?: any;
38
+ transformations?: Array<string>;
39
+ underlay?: string;
40
+ underlays?: Array<any>;
41
+ version?: number | string;
42
+ width?: string | number;
43
+ widthResize?: string | number;
44
+ zoom?: string;
45
+ }
46
+
47
+ interface ImageOptionsZoomPan {
48
+ loop: string | boolean;
49
+ options: string;
50
+ }
51
+ interface ImageOptions extends AssetOptions {
52
+ zoompan?: string | boolean | ImageOptionsZoomPan;
53
+ }
54
+
55
+ export interface CldImageProps extends ImageOptions {
56
+ loading?: "eager" | "lazy";
57
+ fetchPriority?: "high" | "low" | "auto";
58
+ // Adding below as required props to promote good patterns in developing images
59
+ alt: string;
60
+ width: string | number;
61
+ height: string | number;
62
+ // Cloudinary URL Loader props
63
+ // Cannot use `ConfigOptions` due to the same issue as mentioned at the top
64
+ config?: any;
65
+ // Unpic props
66
+ layout?: "constrained" | "fullWidth" | "fixed";
67
+ priority?: boolean;
68
+ background?: "auto" | string;
69
+ }
70
+
71
+ export type CldOgImageProps = CldImageProps & {
72
+ excludeTags?: Array<string>;
73
+ twitterTitle?: string;
74
+ alt?: string;
75
+ width?: string | number;
76
+ height?: string | number;
77
+ };
78
+
79
+ const props = defineProps<CldOgImageProps>();
80
+
81
+ const options = {
82
+ ...props,
83
+ crop: props.crop || "fill",
84
+ gravity: props.gravity || "center",
85
+ height: props.height || OG_IMAGE_HEIGHT,
86
+ src: props.src,
87
+ width: props.width || OG_IMAGE_WIDTH,
88
+ widthResize: props.width || OG_IMAGE_WIDTH_RESIZE,
89
+ };
90
+
91
+ let width =
92
+ typeof options.width === "string" ? parseInt(options.width) : options.width;
93
+ let height =
94
+ typeof options.height === "string"
95
+ ? parseInt(options.height)
96
+ : options.height;
97
+
98
+ // Resize the height based on the widthResize property
99
+
100
+ if (typeof height === "number" && typeof width === "number") {
101
+ height = (OG_IMAGE_WIDTH_RESIZE / width) * height;
102
+ }
103
+
104
+ width = OG_IMAGE_WIDTH_RESIZE;
105
+
106
+ // Render the final URLs. We use two different format versions to deliver
107
+ // webp for Twitter as it supports it (and we can control with tags) where
108
+ // other platforms may not support webp, so we deliver jpg
109
+
110
+ const { url: ogImageUrl } = useCldImageUrl({
111
+ options: {
112
+ ...options,
113
+ format: props.format || "jpg",
114
+ },
115
+ });
116
+
117
+ const { url: twitterImageUrl } = useCldImageUrl({
118
+ options: {
119
+ ...options,
120
+ format: props.format || "webp",
121
+ },
122
+ });
123
+
124
+ const computedTwitterTitle = computed(
125
+ () => props.twitterTitle || currentRoute.value.meta?.title as string || " "
126
+ );
127
+ </script>
128
+
129
+ <template>
130
+ <Head>
131
+ <Meta
132
+ key="og-image"
133
+ property="og:image"
134
+ :content="ogImageUrl"
135
+ />
136
+ <Meta
137
+ key="og-image-secureurl"
138
+ property="og:image:secure_url"
139
+ :content="ogImageUrl"
140
+ />
141
+ <Meta
142
+ key="og-image-width"
143
+ property="og:image:width"
144
+ :content="width.toString()"
145
+ />
146
+ <Meta
147
+ key="og-image-height"
148
+ property="og:image:height"
149
+ :content="height.toString()"
150
+ />
151
+ <Meta
152
+ k-if="alt"
153
+ key="og-image-alt"
154
+ property="og:image:alt"
155
+ :content="alt"
156
+ />
157
+ <Meta
158
+ k-if="!excludeTags?.includes('twitter:title')"
159
+ key="twitter-title"
160
+ property="twitter:title"
161
+ :content="computedTwitterTitle"
162
+ />
163
+ <Meta
164
+ key="twitter-card"
165
+ property="twitter:card"
166
+ :content="TWITTER_CARD"
167
+ />
168
+ <Meta
169
+ key="twitter-image"
170
+ property="twitter:image"
171
+ :content="twitterImageUrl"
172
+ />
173
+ </Head>
174
+ </template>
@@ -0,0 +1,80 @@
1
+ <script setup lang="ts">
2
+ import { useHead } from "@kdhead/kdu";
3
+ import { useRuntimeConfig } from "#imports";
4
+ import { ref } from "kdu";
5
+
6
+ const cloudinaryRef = ref();
7
+
8
+ type MediaType = "image" | "video" | "spin";
9
+
10
+ type ProductGalleryProps = {
11
+ cloudName?: string;
12
+ mediaAssets: {
13
+ tag: string;
14
+ mediaType?: MediaType;
15
+ }[];
16
+ displayProps?: {
17
+ mode: string;
18
+ columns: number;
19
+ }[];
20
+ aspectRatio?: string;
21
+ imageBreakpoint?: number;
22
+ carouselStyle?: string;
23
+ indicatorProps?: {
24
+ color?: string;
25
+ };
26
+ carouselLocation?: string;
27
+ borderColor?: string;
28
+ borderWidth?: number;
29
+ transition?: string;
30
+ zoom?: boolean;
31
+ // Other params listed https://cloudinary.com/documentation/product_gallery_reference#widget_parameters
32
+ params?: Record<string, any>;
33
+ };
34
+
35
+ const props = defineProps<ProductGalleryProps>();
36
+
37
+ const handleOnLoad = () => {
38
+ if ("cloudinary" in window) {
39
+ cloudinaryRef.value = window.cloudinary;
40
+
41
+ const options = Object.fromEntries(
42
+ Object.entries(props).filter((elem) => {
43
+ if (typeof elem[1] === "object") {
44
+ return Object.keys(elem[1]).length ? elem : false;
45
+ }
46
+
47
+ return Boolean(elem[1]);
48
+ })
49
+ );
50
+
51
+ const myGallery = cloudinaryRef.value.galleryWidget({
52
+ container: "#product-gallery",
53
+ cloudName:
54
+ props.cloudName || useRuntimeConfig().public.cloudinary.cloudName,
55
+ ...options,
56
+ ...props.params,
57
+ });
58
+
59
+ myGallery.render();
60
+ }
61
+ };
62
+
63
+ useHead({
64
+ script: [
65
+ {
66
+ id: `cloudinary-product-gallery-${Math.floor(Math.random() * 100)}`,
67
+ src: `https://product-gallery.cloudinary.com/all.js`,
68
+ onload: handleOnLoad,
69
+ onerror: (e) =>
70
+ console.error(
71
+ `Failed to load Cloudinary Product Gallery: ${(e as any).message}`
72
+ ),
73
+ },
74
+ ],
75
+ });
76
+ </script>
77
+
78
+ <template>
79
+ <div id="product-gallery" />
80
+ </template>