@canva/cli 0.0.1-beta.1

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.
Files changed (109) hide show
  1. package/LICENSE.md +48 -0
  2. package/README.md +206 -0
  3. package/cli.js +566 -0
  4. package/package.json +30 -0
  5. package/templates/base/backend/database/database.ts +42 -0
  6. package/templates/base/backend/routers/auth.ts +285 -0
  7. package/templates/base/declarations/declarations.d.ts +29 -0
  8. package/templates/base/eslint.config.mjs +309 -0
  9. package/templates/base/package.json +83 -0
  10. package/templates/base/scripts/ssl/ssl.ts +131 -0
  11. package/templates/base/scripts/start/app_runner.ts +164 -0
  12. package/templates/base/scripts/start/context.ts +165 -0
  13. package/templates/base/scripts/start/start.ts +35 -0
  14. package/templates/base/styles/components.css +38 -0
  15. package/templates/base/tsconfig.json +54 -0
  16. package/templates/base/utils/backend/base_backend/create.ts +104 -0
  17. package/templates/base/utils/backend/jwt_middleware/index.ts +1 -0
  18. package/templates/base/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  19. package/templates/base/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  20. package/templates/base/webpack.config.cjs +270 -0
  21. package/templates/common/.env.template +6 -0
  22. package/templates/common/.gitignore.template +9 -0
  23. package/templates/common/LICENSE.md +48 -0
  24. package/templates/common/README.md +250 -0
  25. package/templates/common/jest.config.mjs +8 -0
  26. package/templates/dam/backend/database/database.ts +42 -0
  27. package/templates/dam/backend/routers/auth.ts +285 -0
  28. package/templates/dam/backend/routers/dam.ts +86 -0
  29. package/templates/dam/backend/server.ts +65 -0
  30. package/templates/dam/declarations/declarations.d.ts +29 -0
  31. package/templates/dam/eslint.config.mjs +309 -0
  32. package/templates/dam/package.json +90 -0
  33. package/templates/dam/scripts/ssl/ssl.ts +131 -0
  34. package/templates/dam/scripts/start/app_runner.ts +164 -0
  35. package/templates/dam/scripts/start/context.ts +165 -0
  36. package/templates/dam/scripts/start/start.ts +35 -0
  37. package/templates/dam/src/adapter.ts +44 -0
  38. package/templates/dam/src/app.tsx +147 -0
  39. package/templates/dam/src/config.ts +95 -0
  40. package/templates/dam/src/index.css +10 -0
  41. package/templates/dam/src/index.tsx +22 -0
  42. package/templates/dam/tsconfig.json +54 -0
  43. package/templates/dam/utils/backend/base_backend/create.ts +104 -0
  44. package/templates/dam/utils/backend/jwt_middleware/index.ts +1 -0
  45. package/templates/dam/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  46. package/templates/dam/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  47. package/templates/dam/webpack.config.cjs +270 -0
  48. package/templates/gen_ai/README.md +27 -0
  49. package/templates/gen_ai/backend/database/database.ts +42 -0
  50. package/templates/gen_ai/backend/routers/auth.ts +285 -0
  51. package/templates/gen_ai/backend/routers/image.ts +234 -0
  52. package/templates/gen_ai/backend/server.ts +56 -0
  53. package/templates/gen_ai/declarations/declarations.d.ts +29 -0
  54. package/templates/gen_ai/eslint.config.mjs +309 -0
  55. package/templates/gen_ai/package.json +92 -0
  56. package/templates/gen_ai/scripts/ssl/ssl.ts +131 -0
  57. package/templates/gen_ai/scripts/start/app_runner.ts +164 -0
  58. package/templates/gen_ai/scripts/start/context.ts +165 -0
  59. package/templates/gen_ai/scripts/start/start.ts +35 -0
  60. package/templates/gen_ai/src/api/api.ts +228 -0
  61. package/templates/gen_ai/src/api/index.ts +1 -0
  62. package/templates/gen_ai/src/app.tsx +13 -0
  63. package/templates/gen_ai/src/components/app_error.tsx +18 -0
  64. package/templates/gen_ai/src/components/footer.messages.ts +53 -0
  65. package/templates/gen_ai/src/components/footer.tsx +157 -0
  66. package/templates/gen_ai/src/components/image_grid.tsx +96 -0
  67. package/templates/gen_ai/src/components/index.ts +8 -0
  68. package/templates/gen_ai/src/components/loading_results.tsx +169 -0
  69. package/templates/gen_ai/src/components/logged_in_status.tsx +44 -0
  70. package/templates/gen_ai/src/components/prompt_input.messages.ts +14 -0
  71. package/templates/gen_ai/src/components/prompt_input.tsx +149 -0
  72. package/templates/gen_ai/src/components/remaining_credits.tsx +75 -0
  73. package/templates/gen_ai/src/components/report_box.tsx +53 -0
  74. package/templates/gen_ai/src/config.ts +21 -0
  75. package/templates/gen_ai/src/context/app_context.tsx +174 -0
  76. package/templates/gen_ai/src/context/context.messages.ts +41 -0
  77. package/templates/gen_ai/src/context/index.ts +2 -0
  78. package/templates/gen_ai/src/context/use_app_context.ts +17 -0
  79. package/templates/gen_ai/src/index.tsx +31 -0
  80. package/templates/gen_ai/src/pages/error.tsx +41 -0
  81. package/templates/gen_ai/src/pages/generate.tsx +9 -0
  82. package/templates/gen_ai/src/pages/index.ts +3 -0
  83. package/templates/gen_ai/src/pages/results.tsx +31 -0
  84. package/templates/gen_ai/src/routes/index.ts +1 -0
  85. package/templates/gen_ai/src/routes/routes.tsx +26 -0
  86. package/templates/gen_ai/src/services/auth.tsx +31 -0
  87. package/templates/gen_ai/src/services/index.ts +1 -0
  88. package/templates/gen_ai/src/utils/index.ts +1 -0
  89. package/templates/gen_ai/src/utils/obscenity_filter.ts +33 -0
  90. package/templates/gen_ai/styles/components.css +38 -0
  91. package/templates/gen_ai/styles/utils.css +3 -0
  92. package/templates/gen_ai/tsconfig.json +54 -0
  93. package/templates/gen_ai/utils/backend/base_backend/create.ts +104 -0
  94. package/templates/gen_ai/utils/backend/jwt_middleware/index.ts +1 -0
  95. package/templates/gen_ai/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  96. package/templates/gen_ai/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  97. package/templates/gen_ai/webpack.config.cjs +270 -0
  98. package/templates/hello_world/declarations/declarations.d.ts +29 -0
  99. package/templates/hello_world/eslint.config.mjs +309 -0
  100. package/templates/hello_world/package.json +73 -0
  101. package/templates/hello_world/scripts/ssl/ssl.ts +131 -0
  102. package/templates/hello_world/scripts/start/app_runner.ts +164 -0
  103. package/templates/hello_world/scripts/start/context.ts +165 -0
  104. package/templates/hello_world/scripts/start/start.ts +35 -0
  105. package/templates/hello_world/src/app.tsx +41 -0
  106. package/templates/hello_world/src/index.tsx +22 -0
  107. package/templates/hello_world/styles/components.css +38 -0
  108. package/templates/hello_world/tsconfig.json +54 -0
  109. package/templates/hello_world/webpack.config.cjs +270 -0
@@ -0,0 +1,228 @@
1
+ import { auth } from "@canva/user";
2
+ import { POLLING_INTERVAL_IN_SECONDS } from "src/config";
3
+
4
+ /**
5
+ * Represents the structure of an image.
6
+ */
7
+ export interface ImageType {
8
+ /** The label of the image. */
9
+ label: string;
10
+ /** Information about the full-size version of the image. */
11
+ fullsize: { width: number; height: number; url: string };
12
+ /** Information about the thumbnail version of the image. */
13
+ thumbnail: { width: number; height: number; url: string };
14
+ }
15
+
16
+ /**
17
+ * Represents the result of generating images.
18
+ */
19
+ interface ImageGenerationResult {
20
+ /** An array of generated images. */
21
+ images: ImageType[];
22
+ /** The remaining credits. */
23
+ credits: number;
24
+ }
25
+
26
+ interface ImageGenerationJobStatusResponse {
27
+ status: "completed" | "processing";
28
+ images: ImageType[];
29
+ credits: number;
30
+ }
31
+
32
+ interface QueueImageGenerationResponse {
33
+ jobId: string;
34
+ }
35
+
36
+ /**
37
+ * Represents the result of retrieving remaining credits.
38
+ */
39
+ interface RemainingCreditsResult {
40
+ /** The remaining credits. */
41
+ credits: number;
42
+ }
43
+
44
+ /**
45
+ * Represents the result of retrieving the logged in status of the user.
46
+ */
47
+ export type LoggedInState =
48
+ | "authenticated"
49
+ | "not_authenticated"
50
+ | "checking"
51
+ | "error";
52
+
53
+ const endpoints = {
54
+ queueImageGeneration: "/api/queue-image-generation",
55
+ getImageGenerationJobStatus: "/api/job-status",
56
+ cancelImageGenerationJob: "/api/job-status/cancel",
57
+ getRemainingCredits: "/api/credits",
58
+ purchaseCredits: "/api/purchase-credits",
59
+ getLoggedInStatus: "/api/authentication/status",
60
+ };
61
+
62
+ /**
63
+ * queues image generation based on the provided prompt and number of images.
64
+ * @param {Object} options - The options for generating images.
65
+ * @param {string} options.prompt - The prompt for generating images.
66
+ * @param {number} options.numberOfImages - The number of images to generate.
67
+ * @returns {Promise<QueueImageGenerationResponse>} A promise that resolves to the created job ID.
68
+ */
69
+ export const queueImageGeneration = async ({
70
+ prompt,
71
+ numberOfImages,
72
+ }: {
73
+ prompt: string;
74
+ numberOfImages: number;
75
+ }): Promise<QueueImageGenerationResponse> => {
76
+ const url = new URL(endpoints.queueImageGeneration, BACKEND_HOST);
77
+ url.searchParams.append("count", numberOfImages.toString());
78
+ url.searchParams.append("prompt", prompt);
79
+
80
+ const result: QueueImageGenerationResponse = await sendRequest(url);
81
+
82
+ return result;
83
+ };
84
+
85
+ /**
86
+ * Retrieves the status of an image generation job.
87
+ * @param {string} jobId - The ID of the job to retrieve status for.
88
+ * @returns {Promise<ImageGenerationResult>} A promise that resolves to the image generation result.
89
+ */
90
+ export const getImageGenerationJobStatus = async ({
91
+ jobId,
92
+ }: {
93
+ jobId: string;
94
+ }): Promise<ImageGenerationResult> => {
95
+ const url = new URL(endpoints.getImageGenerationJobStatus, BACKEND_HOST);
96
+ url.searchParams.append("jobId", jobId);
97
+
98
+ // Define a maximum number of polling attempts
99
+ const maxAttempts = 10;
100
+ let attempts = 0;
101
+
102
+ while (attempts < maxAttempts) {
103
+ try {
104
+ const response = (await sendRequest(
105
+ url,
106
+ )) as ImageGenerationJobStatusResponse;
107
+ if (response.status === "completed") {
108
+ return { images: response.images, credits: response.credits };
109
+ } else if (response.status === "processing") {
110
+ // Job is still processing, wait and continue polling
111
+ await new Promise((resolve) =>
112
+ setTimeout(resolve, POLLING_INTERVAL_IN_SECONDS * 1000),
113
+ );
114
+ attempts++;
115
+ } else if (response.status === "cancelled") {
116
+ throw new Error("Job not found");
117
+ }
118
+ } catch (error) {
119
+ // Handle errors here
120
+ throw new Error(`Error while polling job status ${error}`);
121
+ }
122
+ }
123
+
124
+ throw new Error("Maximum polling attempts reached");
125
+ };
126
+
127
+ /**
128
+ * Cancels an image generation job based on the provided job ID.
129
+ * @param {string} jobId - The ID of the job to cancel.
130
+ * @returns {Promise<void>} - A promise that resolves if the job is successfully cancelled, otherwise rejects with an error.
131
+ */
132
+ export const cancelImageGenerationJob = async (
133
+ jobId: string,
134
+ ): Promise<void> => {
135
+ const url = new URL(endpoints.cancelImageGenerationJob, BACKEND_HOST);
136
+ url.searchParams.append("jobId", jobId);
137
+
138
+ try {
139
+ await sendRequest(url, {
140
+ method: "POST",
141
+ });
142
+ } catch {
143
+ throw new Error("Failed to cancel job.");
144
+ }
145
+ };
146
+
147
+ /**
148
+ * Retrieves the remaining credits.
149
+ * @returns {Promise<RemainingCreditsResult>} - A promise that resolves to the remaining credits.
150
+ */
151
+ export const getRemainingCredits =
152
+ async (): Promise<RemainingCreditsResult> => {
153
+ const url = new URL(endpoints.getRemainingCredits, BACKEND_HOST);
154
+
155
+ const result: RemainingCreditsResult = await sendRequest(url);
156
+
157
+ return result;
158
+ };
159
+
160
+ /**
161
+ * Purchases credits for the user.
162
+ * @returns {Promise<RemainingCreditsResult>} - A promise that resolves to the remaining credits after purchasing.
163
+ */
164
+ export const purchaseCredits = async (): Promise<RemainingCreditsResult> => {
165
+ const url = new URL(endpoints.purchaseCredits, BACKEND_HOST);
166
+
167
+ const result: RemainingCreditsResult = await sendRequest(url, {
168
+ method: "POST",
169
+ });
170
+
171
+ return result;
172
+ };
173
+
174
+ /**
175
+ * Send a request to an endpoint that checks if the user is authenticated.
176
+ * This is example code, intended to convey the basic idea. When implementing this in your app, you might want more advanced checks.
177
+ *
178
+ * Note: You must register the provided endpoint via the Developer Portal.
179
+ */
180
+ export const checkAuthenticationStatus = async (): Promise<LoggedInState> => {
181
+ try {
182
+ const url = new URL(endpoints.getLoggedInStatus, BACKEND_HOST);
183
+ const result: { isAuthenticated: string } = await sendRequest(url, {
184
+ method: "POST",
185
+ });
186
+
187
+ if (result?.isAuthenticated) {
188
+ return "authenticated";
189
+ } else {
190
+ return "not_authenticated";
191
+ }
192
+ } catch (error) {
193
+ // eslint-disable-next-line no-console
194
+ console.error(error);
195
+ return "error";
196
+ }
197
+ };
198
+
199
+ /**
200
+ * Sends a request to the specified URL with authorization headers.
201
+ * @param {URL} url - The URL to send the request to.
202
+ * @param {RequestInit} [options] - Optional fetch options to be passed to the fetch function.
203
+ * @returns {Promise<Object>} - A promise that resolves to the response body.
204
+ */
205
+ const sendRequest = async <T>(url: URL, options?: RequestInit): Promise<T> => {
206
+ const token = await auth.getCanvaUserToken();
207
+ const res = await fetch(url, {
208
+ headers: {
209
+ ...options?.headers,
210
+ Authorization: `Bearer ${token}`,
211
+ },
212
+ ...options,
213
+ });
214
+
215
+ if (!res.ok) {
216
+ throw new Error(`Request failed with status ${res.status}`);
217
+ }
218
+
219
+ // Check Content-Type header to determine how to parse response body
220
+ const contentType = res.headers.get("content-type");
221
+ if (contentType && contentType.includes("application/json")) {
222
+ // Parse response body as JSON
223
+ return (await res.json()) as T;
224
+ } else {
225
+ // Parse response body as text
226
+ return (await res.text()) as unknown as T;
227
+ }
228
+ };
@@ -0,0 +1 @@
1
+ export * from "./api";
@@ -0,0 +1,13 @@
1
+ import { Outlet } from "react-router-dom";
2
+ import { Rows } from "@canva/app-ui-kit";
3
+ import { Footer } from "./components";
4
+ import * as styles from "styles/components.css";
5
+
6
+ export const App = () => (
7
+ <div className={styles.scrollContainer}>
8
+ <Rows spacing="3u">
9
+ <Outlet />
10
+ <Footer />
11
+ </Rows>
12
+ </div>
13
+ );
@@ -0,0 +1,18 @@
1
+ import { Alert } from "@canva/app-ui-kit";
2
+ import { useAppContext } from "src/context";
3
+
4
+ export const AppError = () => {
5
+ const { loadingApp, creditsError, appError, setAppError } = useAppContext();
6
+ if (loadingApp || (!appError && !creditsError)) {
7
+ return null;
8
+ }
9
+
10
+ return (
11
+ <Alert
12
+ tone="critical"
13
+ onDismiss={creditsError ? undefined : () => setAppError("")}
14
+ >
15
+ {creditsError || appError}
16
+ </Alert>
17
+ );
18
+ };
@@ -0,0 +1,53 @@
1
+ import { defineMessages } from "react-intl";
2
+
3
+ export const FooterMessages = defineMessages({
4
+ /** Indicates actions users can take or instructions provided to the user. */
5
+ generateAgain: {
6
+ defaultMessage: "Generate again",
7
+ description:
8
+ "A button label to generate another image based on the previous prompt",
9
+ },
10
+ generateImage: {
11
+ defaultMessage: "Generate image",
12
+ description: "A button label to generate an image from a prompt",
13
+ },
14
+ signUpOrLogin: {
15
+ defaultMessage: "Sign up or log in to generate",
16
+ description:
17
+ "A button label to sign up or log in, before the user is able to generate an image",
18
+ },
19
+ purchaseMoreCredits: {
20
+ defaultMessage: "Purchase more credits",
21
+ description:
22
+ "A button label to open a page where the user can purchase more credits",
23
+ },
24
+ startOver: {
25
+ defaultMessage: "Start over",
26
+ description: "A button label to start the image generation process over",
27
+ },
28
+
29
+ /** Messages related to handling errors that occur during operations. */
30
+ appErrorGeneratingImagesFailed: {
31
+ defaultMessage: "Generating images has failed, please try again.",
32
+ description:
33
+ "A message to indicate that generating images has failed, but the user is able to make another attempt",
34
+ },
35
+
36
+ /** Messages related to prompts and user input validation. */
37
+ promptMissingErrorMessage: {
38
+ defaultMessage: "Please describe what you want to create",
39
+ description:
40
+ "An error message to indicate that the user did not supply a prompt to generate an image, and this has to be provided before generating",
41
+ },
42
+ promptNoCreditsRemaining: {
43
+ defaultMessage: "No credits remaining.",
44
+ description:
45
+ "A message to indicate that the user has no credits remaining, and is unable to generate an image",
46
+ },
47
+ promptObscenityErrorMessage: {
48
+ defaultMessage:
49
+ "Something you typed may result in content that doesn’t meet our policies.",
50
+ description:
51
+ "An error message to indicate that the user typed something that may result in content that for example could be offensive or violent",
52
+ },
53
+ });
@@ -0,0 +1,157 @@
1
+ import { useNavigate, useLocation } from "react-router-dom";
2
+ import { Rows, Button } from "@canva/app-ui-kit";
3
+ import { queueImageGeneration, purchaseCredits } from "src/api";
4
+ import { LoggedInStatus, RemainingCredits } from "src/components";
5
+ import { NUMBER_OF_IMAGES_TO_GENERATE } from "src/config";
6
+ import { useAppContext } from "src/context";
7
+ import { Paths } from "src/routes";
8
+ import { useAuth } from "src/services";
9
+ import { getObsceneWords } from "src/utils";
10
+ import { useIntl } from "react-intl";
11
+ import { FooterMessages as Messages } from "./footer.messages";
12
+
13
+ export const Footer = () => {
14
+ const navigate = useNavigate();
15
+ const { pathname } = useLocation();
16
+ const { requestAuthentication } = useAuth();
17
+ const isRootRoute = pathname === Paths.HOME;
18
+ const {
19
+ loggedInState,
20
+ setAppError,
21
+ promptInput,
22
+ setPromptInput,
23
+ setPromptInputError,
24
+ loadingApp,
25
+ isLoadingImages,
26
+ setJobId,
27
+ setIsLoadingImages,
28
+ remainingCredits,
29
+ setRemainingCredits,
30
+ } = useAppContext();
31
+ const intl = useIntl();
32
+
33
+ const hasRemainingCredits = remainingCredits > 0;
34
+
35
+ const isCreditRemaining = () => {
36
+ if (!hasRemainingCredits) {
37
+ setPromptInputError(
38
+ intl.formatMessage(Messages.promptNoCreditsRemaining),
39
+ );
40
+ return false;
41
+ }
42
+ return true;
43
+ };
44
+
45
+ const isPromptInputFilled = () => {
46
+ if (!promptInput) {
47
+ setPromptInputError(
48
+ intl.formatMessage(Messages.promptMissingErrorMessage),
49
+ );
50
+ return false;
51
+ }
52
+ return true;
53
+ };
54
+
55
+ const isPromptInputClean = () => {
56
+ const obsceneWords = getObsceneWords(promptInput);
57
+ if (obsceneWords.length > 0) {
58
+ setPromptInputError(
59
+ intl.formatMessage(Messages.promptObscenityErrorMessage),
60
+ );
61
+ return false;
62
+ }
63
+ return true;
64
+ };
65
+
66
+ const onGenerateClick = async () => {
67
+ if (
68
+ !isCreditRemaining() ||
69
+ !isPromptInputFilled() ||
70
+ !isPromptInputClean()
71
+ ) {
72
+ return;
73
+ }
74
+
75
+ setIsLoadingImages(true);
76
+ try {
77
+ const { jobId } = await queueImageGeneration({
78
+ prompt: promptInput,
79
+ numberOfImages: NUMBER_OF_IMAGES_TO_GENERATE,
80
+ });
81
+
82
+ setJobId(jobId);
83
+ } catch {
84
+ setAppError(intl.formatMessage(Messages.appErrorGeneratingImagesFailed));
85
+ }
86
+ navigate(Paths.RESULTS);
87
+ };
88
+
89
+ const onSignUpOrLogInClick = async () => {
90
+ await requestAuthentication();
91
+ };
92
+
93
+ const onPurchaseMoreCredits = async () => {
94
+ const { credits } = await purchaseCredits();
95
+
96
+ setRemainingCredits(credits);
97
+ };
98
+
99
+ const reset = () => {
100
+ setPromptInput("");
101
+ navigate(Paths.HOME);
102
+ };
103
+
104
+ const footerButtons = [
105
+ {
106
+ variant: "primary" as const,
107
+ onClick: onGenerateClick,
108
+ value: isRootRoute
109
+ ? intl.formatMessage(Messages.generateImage)
110
+ : intl.formatMessage(Messages.generateAgain),
111
+ visible: hasRemainingCredits,
112
+ },
113
+ {
114
+ variant: "primary" as const,
115
+ onClick: onSignUpOrLogInClick,
116
+ value: intl.formatMessage(Messages.signUpOrLogin),
117
+ visible: loggedInState === "not_authenticated" && !hasRemainingCredits,
118
+ },
119
+ {
120
+ variant: "primary" as const,
121
+ onClick: onPurchaseMoreCredits,
122
+ value: intl.formatMessage(Messages.purchaseMoreCredits),
123
+ visible: loggedInState === "authenticated" && !hasRemainingCredits,
124
+ },
125
+ {
126
+ variant: "secondary" as const,
127
+ onClick: reset,
128
+ value: intl.formatMessage(Messages.startOver),
129
+ visible: !isRootRoute,
130
+ },
131
+ ];
132
+
133
+ if (isLoadingImages) {
134
+ return null;
135
+ }
136
+
137
+ return (
138
+ <Rows spacing="1u">
139
+ {footerButtons.map(
140
+ ({ visible, variant, onClick, value }) =>
141
+ visible && (
142
+ <Button
143
+ key={value}
144
+ variant={variant}
145
+ onClick={onClick}
146
+ loading={loadingApp}
147
+ stretch={true}
148
+ >
149
+ {value}
150
+ </Button>
151
+ ),
152
+ )}
153
+ <RemainingCredits />
154
+ <LoggedInStatus />
155
+ </Rows>
156
+ );
157
+ };
@@ -0,0 +1,96 @@
1
+ import { Grid, ImageCard, Rows, Text } from "@canva/app-ui-kit";
2
+ import type { QueuedImage } from "@canva/asset";
3
+ import { upload } from "@canva/asset";
4
+ import { addNativeElement, ui } from "@canva/design";
5
+ import type { ImageType } from "src/api";
6
+ import { useAppContext } from "src/context";
7
+ import * as styles from "styles/utils.css";
8
+ import { FormattedMessage } from "react-intl";
9
+
10
+ const THUMBNAIL_HEIGHT = 150;
11
+
12
+ const uploadImage = async (image: ImageType): Promise<QueuedImage> => {
13
+ // Upload the image using @canva/asset.
14
+ const queuedImage = await upload({
15
+ type: "IMAGE",
16
+ mimeType: "image/jpeg",
17
+ thumbnailUrl: image.thumbnail.url,
18
+ url: image.fullsize.url,
19
+ width: image.fullsize.width,
20
+ height: image.fullsize.height,
21
+ });
22
+
23
+ return queuedImage;
24
+ };
25
+
26
+ export const ImageGrid = () => {
27
+ const { generatedImages } = useAppContext();
28
+
29
+ const onDragStart = async (
30
+ event: React.DragEvent<HTMLElement>,
31
+ image: ImageType,
32
+ ) => {
33
+ const parentNode = event.currentTarget.parentElement;
34
+ try {
35
+ parentNode?.classList.add(styles.hidden);
36
+
37
+ await ui.startDrag(event, {
38
+ type: "IMAGE",
39
+ resolveImageRef: () => uploadImage(image),
40
+ previewUrl: image.thumbnail.url,
41
+ previewSize: {
42
+ width: image.thumbnail.width,
43
+ height: image.thumbnail.height,
44
+ },
45
+ fullSize: {
46
+ width: image.fullsize.width,
47
+ height: image.fullsize.height,
48
+ },
49
+ });
50
+ } finally {
51
+ parentNode?.classList.remove(styles.hidden);
52
+ }
53
+ };
54
+
55
+ const onImageClick = async (image: ImageType) => {
56
+ const queuedImage = await uploadImage(image);
57
+
58
+ await addNativeElement({
59
+ type: "IMAGE",
60
+ ref: queuedImage.ref,
61
+ });
62
+ };
63
+
64
+ const intl = useIntl();
65
+
66
+ return (
67
+ <Rows spacing="1u">
68
+ <Text size="medium" variant="bold">
69
+ <FormattedMessage
70
+ defaultMessage="Select or drag to add to design"
71
+ description="Instruction to the user on how they can add the generated image to their design"
72
+ />
73
+ </Text>
74
+ <Grid columns={2} spacing="2u">
75
+ {generatedImages.map((image, index) => (
76
+ <ImageCard
77
+ key={index}
78
+ thumbnailUrl={image.thumbnail.url}
79
+ onClick={() => onImageClick(image)}
80
+ ariaLabel={intl.formatMessage({
81
+ defaultMessage: "Add image to design",
82
+ description:
83
+ "Aria label for the image card. When the image card is pressed, it will add the image to the design",
84
+ })}
85
+ alt={image.label}
86
+ thumbnailHeight={THUMBNAIL_HEIGHT}
87
+ borderRadius="standard"
88
+ onDragStart={(event: React.DragEvent<HTMLElement>) =>
89
+ onDragStart(event, image)
90
+ }
91
+ />
92
+ ))}
93
+ </Grid>
94
+ </Rows>
95
+ );
96
+ };
@@ -0,0 +1,8 @@
1
+ export * from "./app_error";
2
+ export * from "./footer";
3
+ export * from "./image_grid";
4
+ export * from "./loading_results";
5
+ export * from "./logged_in_status";
6
+ export * from "./prompt_input";
7
+ export * from "./report_box";
8
+ export * from "./remaining_credits";