@canva/cli 0.0.1-beta.3 → 0.0.1-beta.30

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 (131) hide show
  1. package/README.md +218 -104
  2. package/cli.js +624 -394
  3. package/lib/cjs/index.cjs +5 -0
  4. package/lib/esm/index.mjs +5 -0
  5. package/package.json +19 -4
  6. package/templates/base/eslint.config.mjs +2 -27
  7. package/templates/base/package.json +31 -25
  8. package/templates/base/scripts/copy_env.ts +10 -0
  9. package/templates/base/scripts/start/app_runner.ts +39 -2
  10. package/templates/base/scripts/start/context.ts +12 -6
  11. package/templates/base/scripts/start/start.ts +11 -0
  12. package/templates/base/scripts/start/tests/start.tests.ts +61 -0
  13. package/templates/base/{webpack.config.cjs → webpack.config.ts} +46 -46
  14. package/templates/common/.cursor/mcp.json +8 -0
  15. package/templates/common/.gitignore.template +5 -6
  16. package/templates/common/.nvmrc +1 -0
  17. package/templates/common/.prettierrc +21 -0
  18. package/templates/common/.vscode/extensions.json +6 -0
  19. package/templates/common/.vscode/mcp.json +9 -0
  20. package/templates/common/README.md +4 -7
  21. package/templates/common/jest.config.mjs +29 -2
  22. package/templates/common/jest.setup.ts +20 -0
  23. package/templates/common/utils/backend/base_backend/create.ts +104 -0
  24. package/templates/common/utils/backend/jwt_middleware/index.ts +1 -0
  25. package/templates/common/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  26. package/templates/common/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  27. package/templates/common/utils/table_wrapper.ts +477 -0
  28. package/templates/common/utils/tests/table_wrapper.tests.ts +252 -0
  29. package/templates/common/utils/use_add_element.ts +48 -0
  30. package/templates/common/utils/use_feature_support.ts +28 -0
  31. package/templates/common/utils/use_overlay_hook.ts +74 -0
  32. package/templates/common/utils/use_selection_hook.ts +37 -0
  33. package/templates/dam/backend/routers/dam.ts +23 -19
  34. package/templates/dam/eslint.config.mjs +2 -28
  35. package/templates/dam/package.json +43 -39
  36. package/templates/dam/scripts/copy_env.ts +10 -0
  37. package/templates/dam/scripts/start/app_runner.ts +39 -2
  38. package/templates/dam/scripts/start/context.ts +12 -6
  39. package/templates/dam/scripts/start/start.ts +11 -0
  40. package/templates/dam/scripts/start/tests/start.tests.ts +61 -0
  41. package/templates/dam/src/app.tsx +24 -3
  42. package/templates/dam/src/config.ts +212 -87
  43. package/templates/{hello_world/webpack.config.cjs → dam/webpack.config.ts} +46 -46
  44. package/templates/data_connector/README.md +84 -0
  45. package/templates/data_connector/declarations/declarations.d.ts +29 -0
  46. package/templates/data_connector/eslint.config.mjs +14 -0
  47. package/templates/data_connector/package.json +91 -0
  48. package/templates/data_connector/scripts/copy_env.ts +10 -0
  49. package/templates/data_connector/scripts/ssl/ssl.ts +131 -0
  50. package/templates/data_connector/scripts/start/app_runner.ts +201 -0
  51. package/templates/data_connector/scripts/start/context.ts +171 -0
  52. package/templates/data_connector/scripts/start/start.ts +46 -0
  53. package/templates/data_connector/scripts/start/tests/start.tests.ts +61 -0
  54. package/templates/data_connector/src/api/connect_client.ts +6 -0
  55. package/templates/data_connector/src/api/data_source.ts +96 -0
  56. package/templates/data_connector/src/api/data_sources/designs.tsx +253 -0
  57. package/templates/data_connector/src/api/data_sources/index.ts +4 -0
  58. package/templates/data_connector/src/api/data_sources/templates.tsx +287 -0
  59. package/templates/data_connector/src/api/fetch_data_table.ts +51 -0
  60. package/templates/data_connector/src/api/index.ts +4 -0
  61. package/templates/data_connector/src/api/oauth.ts +8 -0
  62. package/templates/data_connector/src/api/tests/data_source.test.tsx +99 -0
  63. package/templates/data_connector/src/app.tsx +24 -0
  64. package/templates/data_connector/src/components/app_error.tsx +15 -0
  65. package/templates/data_connector/src/components/footer.tsx +26 -0
  66. package/templates/data_connector/src/components/header.tsx +40 -0
  67. package/templates/data_connector/src/components/index.ts +3 -0
  68. package/templates/data_connector/src/components/inputs/messages.tsx +80 -0
  69. package/templates/data_connector/src/components/inputs/select_field.tsx +26 -0
  70. package/templates/data_connector/src/context/app_context.tsx +124 -0
  71. package/templates/data_connector/src/context/index.ts +2 -0
  72. package/templates/data_connector/src/context/use_app_context.ts +17 -0
  73. package/templates/data_connector/src/entrypoint.tsx +73 -0
  74. package/templates/data_connector/src/home.tsx +21 -0
  75. package/templates/data_connector/src/index.tsx +69 -0
  76. package/templates/data_connector/src/pages/data_source_config.tsx +9 -0
  77. package/templates/data_connector/src/pages/error.tsx +37 -0
  78. package/templates/data_connector/src/pages/index.ts +4 -0
  79. package/templates/data_connector/src/pages/login.tsx +145 -0
  80. package/templates/data_connector/src/pages/select_source.tsx +24 -0
  81. package/templates/data_connector/src/routes/index.ts +2 -0
  82. package/templates/data_connector/src/routes/protected_route.tsx +25 -0
  83. package/templates/data_connector/src/routes/routes.tsx +46 -0
  84. package/templates/data_connector/src/utils/data_params.ts +17 -0
  85. package/templates/data_connector/src/utils/data_table.ts +100 -0
  86. package/templates/data_connector/src/utils/fetch_result.ts +36 -0
  87. package/templates/data_connector/src/utils/index.ts +2 -0
  88. package/templates/data_connector/src/utils/tests/data_table.test.ts +133 -0
  89. package/templates/data_connector/styles/components.css +38 -0
  90. package/templates/data_connector/tsconfig.json +54 -0
  91. package/templates/{gen_ai/webpack.config.cjs → data_connector/webpack.config.ts} +46 -46
  92. package/templates/gen_ai/README.md +1 -40
  93. package/templates/gen_ai/backend/routers/image.ts +11 -11
  94. package/templates/gen_ai/backend/server.ts +0 -7
  95. package/templates/gen_ai/eslint.config.mjs +2 -27
  96. package/templates/gen_ai/package.json +48 -42
  97. package/templates/gen_ai/scripts/copy_env.ts +10 -0
  98. package/templates/gen_ai/scripts/start/app_runner.ts +39 -2
  99. package/templates/gen_ai/scripts/start/context.ts +12 -6
  100. package/templates/gen_ai/scripts/start/start.ts +11 -0
  101. package/templates/gen_ai/scripts/start/tests/start.tests.ts +61 -0
  102. package/templates/gen_ai/src/api/api.ts +24 -79
  103. package/templates/gen_ai/src/app.tsx +16 -10
  104. package/templates/gen_ai/src/components/footer.messages.ts +0 -5
  105. package/templates/gen_ai/src/components/footer.tsx +7 -25
  106. package/templates/gen_ai/src/components/index.ts +0 -1
  107. package/templates/gen_ai/src/components/loading_results.tsx +4 -8
  108. package/templates/gen_ai/src/components/tests/remaining_credit.tests.tsx +43 -0
  109. package/templates/gen_ai/src/context/app_context.tsx +5 -33
  110. package/templates/gen_ai/src/context/context.messages.ts +1 -12
  111. package/templates/gen_ai/src/home.tsx +13 -0
  112. package/templates/gen_ai/src/index.tsx +2 -18
  113. package/templates/gen_ai/src/routes/routes.tsx +2 -2
  114. package/templates/{dam/webpack.config.cjs → gen_ai/webpack.config.ts} +46 -46
  115. package/templates/hello_world/eslint.config.mjs +2 -27
  116. package/templates/hello_world/package.json +47 -34
  117. package/templates/hello_world/scripts/copy_env.ts +10 -0
  118. package/templates/hello_world/scripts/start/app_runner.ts +39 -2
  119. package/templates/hello_world/scripts/start/context.ts +12 -6
  120. package/templates/hello_world/scripts/start/start.ts +11 -0
  121. package/templates/hello_world/scripts/start/tests/start.tests.ts +61 -0
  122. package/templates/hello_world/src/app.tsx +20 -0
  123. package/templates/hello_world/src/tests/__snapshots__/app.tests.tsx.snap +45 -0
  124. package/templates/hello_world/src/tests/app.tests.tsx +86 -0
  125. package/templates/hello_world/webpack.config.ts +270 -0
  126. package/templates/common/conf/eslint-general.mjs +0 -277
  127. package/templates/common/conf/eslint-i18n.mjs +0 -23
  128. package/templates/gen_ai/backend/routers/oauth.ts +0 -393
  129. package/templates/gen_ai/src/components/logged_in_status.tsx +0 -44
  130. package/templates/gen_ai/src/services/auth.tsx +0 -26
  131. package/templates/gen_ai/src/services/index.ts +0 -1
@@ -0,0 +1,96 @@
1
+ import type { DataTable } from "@canva/intents/data";
2
+ import { toDataTable, type DataTableColumn } from "src/utils";
3
+
4
+ /**
5
+ * This file defines types and classes related to data source configuration, fetching and outputting as a data table.
6
+ * When data is loaded, the app will save the data source config so that it can be queried again later to refresh the data.
7
+ * Strongly typed data sources are simple to reload and validate.
8
+ */
9
+
10
+ /**
11
+ * The data source configuration represents all parameters that are needed to represent the data source so that it can be queried again later.
12
+ * This includes the schema, any filters that are applied to the data source, and any other parameters that are needed to fetch the data.
13
+ */
14
+ export interface DataSourceConfig {
15
+ // a unique identifier for the data source that is used to associated the saved data source config with the data source handler
16
+ schema: string;
17
+ }
18
+
19
+ /**
20
+ * the API response item is a generic type that represents the data returned from the API
21
+ */
22
+ export interface APIResponseItem {
23
+ id: string;
24
+ }
25
+
26
+ export class DataAPIError extends Error {
27
+ constructor(message: string) {
28
+ super(message);
29
+ this.name = "APIError";
30
+ }
31
+ }
32
+
33
+ /**
34
+ * The data source handler class defines a particular data source and how to fetch data from it.
35
+ * In this template, the two data sources are brand templates and designs. Each data source has its own handler.
36
+ * The handler defines the schema for the data source configuration (what filters are applied to get the requested data), the columns to display, and how to fetch data from the API.
37
+ * It also defines the UI for how this source is represented on the data source selection page and how to render the data source configuration page where any filters can be set.
38
+ */
39
+ export class DataSourceHandler<
40
+ T extends DataSourceConfig,
41
+ R extends APIResponseItem,
42
+ > {
43
+ schema: string;
44
+ constructor(
45
+ // the configuration for this data source. The default values will be overridden by the user setting filters, or on app launch if the previous state is restored
46
+ public sourceConfig: T,
47
+ // the columns to display in the data table output. In this template they are fixed, but they could be dynamic based on the data source and configuration
48
+ public columns: DataTableColumn<R>[],
49
+ // the fetch logic for turning the data source configuration into an array of data items to turn into a data table
50
+ public fetchData: (
51
+ source: T,
52
+ authToken: string,
53
+ rowLimit: number,
54
+ signal: AbortSignal | undefined,
55
+ ) => Promise<R[]>,
56
+ // the UI for the data source selection page. This is where the user chooses which data source to use.
57
+ public selectionPage: () => JSX.Element,
58
+ // the UI for the data source configuration page. This is where the user sets any filters or other parameters for the data source.
59
+ public configPage: (sourceConfig: T) => JSX.Element,
60
+ ) {
61
+ this.schema = sourceConfig.schema;
62
+ }
63
+
64
+ /**
65
+ * A type guard / type predicate to check if the data source configuration matches the schema of this data source handler.
66
+ * @param source the data source configuration to match against
67
+ * @returns
68
+ */
69
+ matchSource(source: DataSourceConfig): source is T {
70
+ return source.schema === this.schema;
71
+ }
72
+
73
+ /**
74
+ * The buildTable function is called to fetch data from the API and return it as a data table.
75
+ * @param source the data source configuration
76
+ * @param authToken the auth token to use for the API request
77
+ * @param rowLimit the maximum number of rows to return
78
+ * @param signal an optional abort signal to cancel the request
79
+ * @returns a data table with the data from the API
80
+ */
81
+ async fetchAndBuildTable(
82
+ source: T,
83
+ authToken: string,
84
+ rowLimit: number,
85
+ signal: AbortSignal | undefined,
86
+ ): Promise<DataTable> {
87
+ let apiData: R[];
88
+ try {
89
+ apiData = await this.fetchData(source, authToken || "", rowLimit, signal);
90
+ } catch {
91
+ throw new DataAPIError("Failed to fetch data from API");
92
+ }
93
+ // the toDataTable utility takes the API data and the configured columns and turns it into a data table
94
+ return toDataTable(apiData, this.columns, rowLimit);
95
+ }
96
+ }
@@ -0,0 +1,253 @@
1
+ /* eslint-disable formatjs/no-literal-string-in-object */
2
+ import type { APIResponseItem, DataSourceConfig } from "../data_source";
3
+ import { DataAPIError, DataSourceHandler } from "../data_source";
4
+ import type { CanvaItemResponse } from "../connect_client";
5
+
6
+ import type { SelectOption } from "@canva/app-ui-kit";
7
+ import { Button, DatabaseIcon, HorizontalCard, Rows } from "@canva/app-ui-kit";
8
+ import { useAppContext } from "src/context";
9
+ import { Header } from "src/components";
10
+ import {
11
+ ownershipFilter,
12
+ sortOrderField,
13
+ } from "src/components/inputs/messages";
14
+ import { useIntl } from "react-intl";
15
+ import { SelectField } from "src/components/inputs/select_field";
16
+ import { dateCell, numberCell, stringCell } from "src/utils";
17
+ import { Paths } from "src/routes";
18
+ import { useNavigate } from "react-router-dom";
19
+ import { useState } from "react";
20
+
21
+ export interface DesignsDataSource extends DataSourceConfig {
22
+ ownership: "any" | "owned" | "shared";
23
+ sort_by:
24
+ | "relevance"
25
+ | "modified_descending"
26
+ | "modified_ascending"
27
+ | "title_descending"
28
+ | "title_ascending";
29
+ }
30
+
31
+ export interface CanvaDesign extends APIResponseItem {
32
+ title: string;
33
+ created_at: number;
34
+ updated_at: number;
35
+ page_count: number;
36
+ }
37
+
38
+ export const designsSource = new DataSourceHandler<
39
+ DesignsDataSource,
40
+ CanvaDesign
41
+ >(
42
+ {
43
+ schema: "designs/v1",
44
+ ownership: "any",
45
+ sort_by: "relevance",
46
+ },
47
+ [
48
+ {
49
+ label: "ID",
50
+ getValue: (design: CanvaDesign) => `ID ${design.id}`,
51
+ toCell: stringCell,
52
+ },
53
+ {
54
+ label: "Title",
55
+ getValue: "title",
56
+ toCell: stringCell,
57
+ },
58
+ {
59
+ label: "Created At",
60
+ getValue: "created_at",
61
+ toCell: dateCell,
62
+ },
63
+ {
64
+ label: "Updated At",
65
+ getValue: "updated_at",
66
+ toCell: dateCell,
67
+ },
68
+ {
69
+ label: "Page Count",
70
+ getValue: "page_count",
71
+ toCell: numberCell,
72
+ },
73
+ ],
74
+ (
75
+ source: DesignsDataSource,
76
+ authToken: string,
77
+ rowLimit: number,
78
+ signal: AbortSignal | undefined,
79
+ ) =>
80
+ getDesigns(authToken, rowLimit, signal, source.ownership, source.sort_by),
81
+ DesignSelection,
82
+ DesignsSourceConfig,
83
+ );
84
+
85
+ export async function getDesigns(
86
+ authToken: string,
87
+ rowLimit: number,
88
+ signal: AbortSignal | undefined,
89
+ ownership: string,
90
+ sort_by: string,
91
+ continuation?: string,
92
+ allItems: CanvaDesign[] = [],
93
+ ): Promise<CanvaDesign[]> {
94
+ const baseUrl = `https://api.canva.com/rest/v1/designs`;
95
+ const url = continuation
96
+ ? `${baseUrl}?continuation=${continuation}`
97
+ : `${baseUrl}?ownership=${ownership}&sort_by=${sort_by}`;
98
+
99
+ return fetch(url, {
100
+ headers: {
101
+ Authorization: `Bearer ${authToken}`,
102
+ },
103
+ signal,
104
+ })
105
+ .then((response) => {
106
+ if (!response.ok) {
107
+ throw new DataAPIError(
108
+ `Canva Connect response was not ok: ${response.statusText || response.status}`,
109
+ );
110
+ }
111
+ return response.json();
112
+ })
113
+ .then((data: CanvaItemResponse<CanvaDesign>) => {
114
+ const updatedItems = [...allItems, ...data.items];
115
+
116
+ if (data.continuation && updatedItems.length < rowLimit) {
117
+ return getDesigns(
118
+ authToken,
119
+ rowLimit,
120
+ signal,
121
+ ownership,
122
+ sort_by,
123
+ data.continuation,
124
+ updatedItems,
125
+ );
126
+ }
127
+
128
+ return updatedItems;
129
+ });
130
+ }
131
+
132
+ function DesignSelection() {
133
+ const intl = useIntl();
134
+ const { setDataSourceHandler } = useAppContext();
135
+ const navigate = useNavigate();
136
+
137
+ const title = intl.formatMessage({
138
+ defaultMessage: "Designs",
139
+ description:
140
+ "Main heading on the designs button displayed when selecting the import type.",
141
+ });
142
+
143
+ const description = intl.formatMessage({
144
+ defaultMessage: "Query designs",
145
+ description:
146
+ "Subtext on the designs selection button displayed when selecting the import type.",
147
+ });
148
+
149
+ const handleClick = () => {
150
+ setDataSourceHandler(
151
+ designsSource as unknown as DataSourceHandler<
152
+ DataSourceConfig,
153
+ APIResponseItem
154
+ >,
155
+ );
156
+ navigate(Paths.DATA_SOURCE_CONFIG);
157
+ };
158
+
159
+ return (
160
+ <HorizontalCard
161
+ key="designs"
162
+ title={title}
163
+ thumbnail={{ icon: () => <DatabaseIcon /> }}
164
+ onClick={handleClick}
165
+ description={description}
166
+ ariaLabel={description}
167
+ />
168
+ );
169
+ }
170
+
171
+ function DesignsSourceConfig(sourceConfig: DesignsDataSource) {
172
+ const intl = useIntl();
173
+ const { loadDataSource } = useAppContext();
174
+ const [ownership, setOwnership] = useState<string>(sourceConfig.ownership);
175
+ const [sortOrder, setSortOrder] = useState<string>(sourceConfig.sort_by);
176
+ const [isLoading, setIsLoading] = useState(false);
177
+
178
+ const loadDesigns = async () => {
179
+ setIsLoading(true);
180
+ loadDataSource("Canva Designs", {
181
+ schema: "designs/v1",
182
+ ownership,
183
+ sort_by: sortOrder,
184
+ } as DesignsDataSource).then(() => {
185
+ setIsLoading(false);
186
+ });
187
+ };
188
+
189
+ const ownershipOptions: SelectOption<string>[] = [
190
+ { value: "any", label: intl.formatMessage(ownershipFilter.any) },
191
+ { value: "owned", label: intl.formatMessage(ownershipFilter.owned) },
192
+ { value: "shared", label: intl.formatMessage(ownershipFilter.shared) },
193
+ ];
194
+
195
+ const sortOrderOptions: SelectOption<string>[] = [
196
+ { value: "relevance", label: intl.formatMessage(sortOrderField.relevance) },
197
+ {
198
+ value: "modified_descending",
199
+ label: intl.formatMessage(sortOrderField.modifiedDesc),
200
+ },
201
+ {
202
+ value: "modified_ascending",
203
+ label: intl.formatMessage(sortOrderField.modifiedAsc),
204
+ },
205
+ {
206
+ value: "title_descending",
207
+ label: intl.formatMessage(sortOrderField.titleDesc),
208
+ },
209
+ {
210
+ value: "title_ascending",
211
+ label: intl.formatMessage(sortOrderField.titleAsc),
212
+ },
213
+ ];
214
+
215
+ return (
216
+ <div>
217
+ <Rows spacing="2u">
218
+ <Header
219
+ title={intl.formatMessage({
220
+ defaultMessage: "Canva Designs",
221
+ description: "The header text for the designs data source",
222
+ })}
223
+ showBack={true}
224
+ />
225
+
226
+ <SelectField
227
+ label={intl.formatMessage(ownershipFilter.label)}
228
+ options={ownershipOptions}
229
+ value={ownership}
230
+ onChange={setOwnership}
231
+ />
232
+ <SelectField
233
+ label={intl.formatMessage(sortOrderField.label)}
234
+ options={sortOrderOptions}
235
+ value={sortOrder}
236
+ onChange={setSortOrder}
237
+ />
238
+ <Button
239
+ variant="primary"
240
+ loading={isLoading}
241
+ onClick={async () => {
242
+ loadDesigns();
243
+ }}
244
+ >
245
+ {intl.formatMessage({
246
+ defaultMessage: "Load Designs",
247
+ description: "Button for saving and applying the query filter",
248
+ })}
249
+ </Button>
250
+ </Rows>
251
+ </div>
252
+ );
253
+ }
@@ -0,0 +1,4 @@
1
+ import { designsSource } from "./designs";
2
+ import { brandTemplatesSource } from "./templates";
3
+
4
+ export const DATA_SOURCES = [designsSource, brandTemplatesSource];
@@ -0,0 +1,287 @@
1
+ /* eslint-disable formatjs/no-literal-string-in-object */
2
+ import { useAppContext } from "src/context";
3
+ import type { APIResponseItem, DataSourceConfig } from "../data_source";
4
+ import { DataAPIError, DataSourceHandler } from "../data_source";
5
+ import type { CanvaItemResponse } from "../connect_client";
6
+ import { dateCell, stringCell } from "src/utils";
7
+ import type { SelectOption } from "@canva/app-ui-kit";
8
+ import {
9
+ Button,
10
+ HorizontalCard,
11
+ Rows,
12
+ TableMergedHeaderCellsIcon,
13
+ } from "@canva/app-ui-kit";
14
+ import { useIntl } from "react-intl";
15
+ import {
16
+ datasetFilter,
17
+ ownershipFilter,
18
+ sortOrderField,
19
+ } from "src/components/inputs/messages";
20
+ import { SelectField } from "src/components/inputs/select_field";
21
+ import { Header } from "src/components";
22
+ import { useNavigate } from "react-router-dom";
23
+ import { Paths } from "src/routes";
24
+ import { useState } from "react";
25
+
26
+ export interface BrandTemplatesDataSource extends DataSourceConfig {
27
+ dataset: "any" | "non_empty" | "empty";
28
+ ownership: "any" | "owned" | "shared";
29
+ sort_by:
30
+ | "relevance"
31
+ | "modified_descending"
32
+ | "modified_ascending"
33
+ | "title_descending"
34
+ | "title_ascending";
35
+ }
36
+
37
+ export interface CanvaBrandTemplate extends APIResponseItem {
38
+ title: string;
39
+ created_at: number;
40
+ updated_at: number;
41
+ view_url: string;
42
+ create_url: string;
43
+ }
44
+
45
+ export const brandTemplatesSource = new DataSourceHandler<
46
+ BrandTemplatesDataSource,
47
+ CanvaBrandTemplate
48
+ >(
49
+ {
50
+ schema: "brand_templates/v1",
51
+ dataset: "any",
52
+ ownership: "any",
53
+ sort_by: "relevance",
54
+ },
55
+ [
56
+ {
57
+ label: "ID",
58
+ getValue: (template: CanvaBrandTemplate) => `ID ${template.id}`,
59
+ toCell: stringCell,
60
+ },
61
+ {
62
+ label: "Title",
63
+ getValue: "title",
64
+ toCell: stringCell,
65
+ },
66
+ {
67
+ label: "Created At",
68
+ getValue: "created_at",
69
+ toCell: dateCell,
70
+ },
71
+ {
72
+ label: "Updated At",
73
+ getValue: "updated_at",
74
+ toCell: dateCell,
75
+ },
76
+ {
77
+ label: "View URL",
78
+ getValue: "view_url",
79
+ toCell: stringCell,
80
+ },
81
+ {
82
+ label: "Create URL",
83
+ getValue: "create_url",
84
+ toCell: stringCell,
85
+ },
86
+ ],
87
+ (
88
+ source: BrandTemplatesDataSource,
89
+ authToken: string,
90
+ rowLimit: number,
91
+ signal: AbortSignal | undefined,
92
+ ) =>
93
+ getBrandTemplates(
94
+ authToken,
95
+ rowLimit,
96
+ signal,
97
+ source.dataset,
98
+ source.ownership,
99
+ source.sort_by,
100
+ ),
101
+ BrandTemplatesSelection,
102
+ BrandTemplatesSourceConfig,
103
+ );
104
+
105
+ export async function getBrandTemplates(
106
+ authToken: string,
107
+ rowLimit: number,
108
+ signal: AbortSignal | undefined,
109
+ ownership: string,
110
+ dataset: string,
111
+ sort_by: string,
112
+ continuation?: string,
113
+ allItems: CanvaBrandTemplate[] = [],
114
+ ): Promise<CanvaBrandTemplate[]> {
115
+ const baseUrl = `https://api.canva.com/rest/v1/brand-templates`;
116
+ const url = continuation
117
+ ? `${baseUrl}?continuation=${continuation}`
118
+ : `${baseUrl}?ownership=${ownership}&dataset=${dataset}&sort_by=${sort_by}`;
119
+
120
+ return fetch(url, {
121
+ headers: {
122
+ Authorization: `Bearer ${authToken}`,
123
+ },
124
+ signal,
125
+ })
126
+ .then((response) => {
127
+ if (!response.ok) {
128
+ throw new DataAPIError(
129
+ `Canva Connect response was not ok: ${response.statusText || response.status}`,
130
+ );
131
+ }
132
+ return response.json();
133
+ })
134
+ .then((data: CanvaItemResponse<CanvaBrandTemplate>) => {
135
+ const updatedItems = [...allItems, ...data.items];
136
+
137
+ if (data.continuation && updatedItems.length < rowLimit) {
138
+ return getBrandTemplates(
139
+ authToken,
140
+ rowLimit,
141
+ signal,
142
+ ownership,
143
+ dataset,
144
+ sort_by,
145
+ data.continuation,
146
+ updatedItems,
147
+ );
148
+ }
149
+
150
+ return updatedItems;
151
+ });
152
+ }
153
+
154
+ function BrandTemplatesSelection() {
155
+ const intl = useIntl();
156
+ const { setDataSourceHandler } = useAppContext();
157
+ const navigate = useNavigate();
158
+
159
+ const title = intl.formatMessage({
160
+ defaultMessage: "Brand Templates",
161
+ description:
162
+ "Main heading on the brand templates button displayed when selecting the import type.",
163
+ });
164
+
165
+ const description = intl.formatMessage({
166
+ defaultMessage: "Query brand templates",
167
+ description:
168
+ "Subtext on the brand templates button displayed when selecting the import type.",
169
+ });
170
+
171
+ const handleClick = () => {
172
+ setDataSourceHandler(
173
+ brandTemplatesSource as unknown as DataSourceHandler<
174
+ DataSourceConfig,
175
+ APIResponseItem
176
+ >,
177
+ );
178
+ navigate(Paths.DATA_SOURCE_CONFIG);
179
+ };
180
+
181
+ return (
182
+ <HorizontalCard
183
+ key="brand-templates"
184
+ title={title}
185
+ thumbnail={{ icon: () => <TableMergedHeaderCellsIcon /> }}
186
+ onClick={handleClick}
187
+ description={description}
188
+ ariaLabel={description}
189
+ />
190
+ );
191
+ }
192
+
193
+ function BrandTemplatesSourceConfig(sourceConfig: BrandTemplatesDataSource) {
194
+ const { loadDataSource } = useAppContext();
195
+ const [ownership, setOwnership] = useState<string>(sourceConfig.ownership);
196
+ const [sortOrder, setSortOrder] = useState<string>(sourceConfig.sort_by);
197
+ const [dataset, setDataset] = useState<string>(sourceConfig.dataset);
198
+ const [isLoading, setIsLoading] = useState(false);
199
+ const intl = useIntl();
200
+
201
+ const loadTemplates = async () => {
202
+ loadDataSource("Canva Brand Templates", {
203
+ schema: "brand_templates/v1",
204
+ ownership,
205
+ dataset,
206
+ sort_by: sortOrder,
207
+ } as BrandTemplatesDataSource).then(() => {
208
+ setIsLoading(false);
209
+ });
210
+ };
211
+
212
+ const ownershipOptions: SelectOption<string>[] = [
213
+ { value: "any", label: intl.formatMessage(ownershipFilter.any) },
214
+ { value: "owned", label: intl.formatMessage(ownershipFilter.owned) },
215
+ { value: "shared", label: intl.formatMessage(ownershipFilter.shared) },
216
+ ];
217
+
218
+ const sortOrderOptions: SelectOption<string>[] = [
219
+ { value: "relevance", label: intl.formatMessage(sortOrderField.relevance) },
220
+ {
221
+ value: "modified_descending",
222
+ label: intl.formatMessage(sortOrderField.modifiedDesc),
223
+ },
224
+ {
225
+ value: "modified_ascending",
226
+ label: intl.formatMessage(sortOrderField.modifiedAsc),
227
+ },
228
+ {
229
+ value: "title_descending",
230
+ label: intl.formatMessage(sortOrderField.titleDesc),
231
+ },
232
+ {
233
+ value: "title_ascending",
234
+ label: intl.formatMessage(sortOrderField.titleAsc),
235
+ },
236
+ ];
237
+
238
+ const datasetOptions: SelectOption<string>[] = [
239
+ { value: "any", label: intl.formatMessage(datasetFilter.any) },
240
+ { value: "non_empty", label: intl.formatMessage(datasetFilter.nonEmpty) },
241
+ { value: "empty", label: intl.formatMessage(datasetFilter.empty) },
242
+ ];
243
+
244
+ return (
245
+ <div>
246
+ <Header
247
+ title={intl.formatMessage({
248
+ defaultMessage: "Canva Brand Templates",
249
+ description: "The header text for the brand templates data source",
250
+ })}
251
+ showBack={true}
252
+ />
253
+ <Rows spacing="2u">
254
+ <SelectField
255
+ label={intl.formatMessage(ownershipFilter.label)}
256
+ options={ownershipOptions}
257
+ value={ownership}
258
+ onChange={setOwnership}
259
+ />
260
+ <SelectField
261
+ label={intl.formatMessage(datasetFilter.label)}
262
+ options={datasetOptions}
263
+ value={dataset}
264
+ onChange={setDataset}
265
+ />
266
+ <SelectField
267
+ label={intl.formatMessage(sortOrderField.label)}
268
+ options={sortOrderOptions}
269
+ value={sortOrder}
270
+ onChange={setSortOrder}
271
+ />
272
+ <Button
273
+ variant="primary"
274
+ loading={isLoading}
275
+ onClick={async () => {
276
+ loadTemplates();
277
+ }}
278
+ >
279
+ {intl.formatMessage({
280
+ defaultMessage: "Load Templates",
281
+ description: "Button for saving and applying the query filter",
282
+ })}
283
+ </Button>
284
+ </Rows>
285
+ </div>
286
+ );
287
+ }
@@ -0,0 +1,51 @@
1
+ import type {
2
+ FetchDataTableParams,
3
+ FetchDataTableResult,
4
+ } from "@canva/intents/data";
5
+ import { DATA_SOURCES } from "./data_sources";
6
+ import {
7
+ appError,
8
+ completeDataTable,
9
+ outdatedSourceRef,
10
+ remoteRequestFailed,
11
+ } from "src/utils/fetch_result";
12
+ import { DataAPIError } from ".";
13
+
14
+ /**
15
+ * This function handles parsing the data fetch parameters and calling the appropriate handler for the data source.
16
+ * @param fetchParams
17
+ * @param authToken
18
+ * @returns
19
+ */
20
+ export const buildDataTableResult = async (
21
+ fetchParams: FetchDataTableParams,
22
+ authToken?: string,
23
+ ): Promise<FetchDataTableResult> => {
24
+ const source = JSON.parse(fetchParams.dataSourceRef.source);
25
+ const rowLimit = fetchParams.limit.row - 1; // -1 for the header row
26
+
27
+ const dataHandler = DATA_SOURCES.find((handler) =>
28
+ handler.matchSource(source),
29
+ );
30
+ if (!dataHandler) {
31
+ // the configured source does not match the expected data source type
32
+ // return an error result which will prompt the user to reconfigure the data source
33
+ return outdatedSourceRef();
34
+ }
35
+ try {
36
+ const dataTable = await dataHandler.fetchAndBuildTable(
37
+ source,
38
+ authToken || "",
39
+ rowLimit,
40
+ fetchParams.signal,
41
+ );
42
+ return completeDataTable(dataTable);
43
+ } catch (error) {
44
+ if (error instanceof DataAPIError) {
45
+ return remoteRequestFailed();
46
+ }
47
+ return appError(
48
+ error instanceof Error ? error.message : "An unknown error occurred",
49
+ );
50
+ }
51
+ };
@@ -0,0 +1,4 @@
1
+ export * from "./connect_client";
2
+ export * from "./fetch_data_table";
3
+ export * from "./data_source";
4
+ export * from "./oauth";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The scopes to request as part of the OAuth flow.
3
+ * These scopes are required to read the user's designs and brand templates.
4
+ *
5
+ * @see https://www.canva.dev/docs/apps/authenticating-users/oauth/#overview - for more information about using the @canva/user package to support OAuth login.
6
+ * @see https://www.canva.dev/docs/connect/appendix/scopes/ - for a full list of Canva Connect API scopes.
7
+ */
8
+ export const scope = new Set(["design:meta:read", "brandtemplate:meta:read"]);