@canva/cli 0.0.1-beta.2 → 0.0.1-beta.4
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/README.md +177 -109
- package/cli.js +267 -267
- package/package.json +1 -1
- package/templates/base/backend/routers/oauth.ts +393 -0
- package/templates/base/eslint.config.mjs +0 -2
- package/templates/base/package.json +22 -19
- package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
- package/templates/base/utils/backend/bearer_middleware/index.ts +1 -0
- package/templates/base/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
- package/templates/base/utils/use_add_element.ts +48 -0
- package/templates/base/utils/use_feature_support.ts +28 -0
- package/templates/common/.gitignore.template +5 -6
- package/templates/common/README.md +4 -74
- package/templates/common/conf/eslint-general.mjs +26 -0
- package/templates/common/conf/eslint-i18n.mjs +18 -3
- package/templates/dam/backend/server.ts +0 -7
- package/templates/dam/package.json +27 -27
- package/templates/dam/src/app.tsx +2 -135
- package/templates/gen_ai/README.md +1 -1
- package/templates/gen_ai/backend/routers/image.ts +3 -3
- package/templates/gen_ai/backend/server.ts +0 -7
- package/templates/gen_ai/eslint.config.mjs +0 -2
- package/templates/gen_ai/package.json +28 -28
- package/templates/gen_ai/src/api/api.ts +1 -39
- package/templates/gen_ai/src/components/footer.messages.ts +0 -5
- package/templates/gen_ai/src/components/footer.tsx +2 -16
- package/templates/gen_ai/src/components/image_grid.tsx +8 -6
- package/templates/gen_ai/src/components/index.ts +0 -1
- package/templates/gen_ai/src/context/app_context.tsx +4 -26
- package/templates/gen_ai/src/context/context.messages.ts +1 -12
- package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
- package/templates/gen_ai/utils/backend/bearer_middleware/index.ts +1 -0
- package/templates/gen_ai/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
- package/templates/hello_world/eslint.config.mjs +0 -2
- package/templates/hello_world/package.json +20 -19
- package/templates/hello_world/src/app.tsx +4 -2
- package/templates/hello_world/utils/use_add_element.ts +48 -0
- package/templates/hello_world/utils/use_feature_support.ts +28 -0
- package/templates/dam/backend/database/database.ts +0 -42
- package/templates/dam/backend/routers/auth.ts +0 -285
- package/templates/gen_ai/backend/routers/auth.ts +0 -285
- package/templates/gen_ai/src/components/logged_in_status.tsx +0 -44
- package/templates/gen_ai/src/services/auth.tsx +0 -31
- package/templates/gen_ai/src/services/index.ts +0 -1
- package/templates/gen_ai/utils/backend/jwt_middleware/index.ts +0 -1
- package/templates/gen_ai/utils/backend/jwt_middleware/jwt_middleware.ts +0 -229
- package/templates/gen_ai/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +0 -630
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/* eslint-disable no-console */
|
|
2
|
+
import * as debug from "debug";
|
|
3
|
+
import type { Request, Response, NextFunction } from "express";
|
|
4
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
5
|
+
import Express from "express-serve-static-core";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Prefix your start command with `DEBUG=express:middleware:bearer` to enable debug logging
|
|
9
|
+
* for this middleware
|
|
10
|
+
*/
|
|
11
|
+
const debugLogger = debug("express:middleware:bearer");
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Augment the Express request context to include the appId/userId/brandId fields decoded
|
|
15
|
+
* from the JWT.
|
|
16
|
+
*/
|
|
17
|
+
declare module "express-serve-static-core" {
|
|
18
|
+
export interface Request {
|
|
19
|
+
user_id: string;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const sendUnauthorizedResponse = (res: Response, message?: string) =>
|
|
24
|
+
res.status(401).json({ error: "unauthorized", message });
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* An Express.js middleware verifying a Bearer token.
|
|
28
|
+
* This middleware extracts the token from the `Authorization` header.
|
|
29
|
+
*
|
|
30
|
+
* @param getTokenFromRequest - A function that extracts a token from the request. If a token isn't found, throw a `JWTAuthorizationError`.
|
|
31
|
+
* @returns An Express.js middleware for verifying and decoding JWTs.
|
|
32
|
+
*/
|
|
33
|
+
export function createBearerMiddleware(
|
|
34
|
+
tokenToUser: (access_token: string) => Promise<string | undefined>,
|
|
35
|
+
getTokenFromRequest: GetTokenFromRequest = getTokenFromHttpHeader,
|
|
36
|
+
): (req: Request, res: Response, next: NextFunction) => void {
|
|
37
|
+
return async (req, res, next) => {
|
|
38
|
+
try {
|
|
39
|
+
debugLogger(`processing token for '${req.url}'`);
|
|
40
|
+
|
|
41
|
+
const token = await getTokenFromRequest(req);
|
|
42
|
+
const user = await tokenToUser(token);
|
|
43
|
+
|
|
44
|
+
if (!user) {
|
|
45
|
+
throw new AuthorizationError("Token is invalid");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
req.user_id = user;
|
|
49
|
+
|
|
50
|
+
next();
|
|
51
|
+
} catch (e) {
|
|
52
|
+
if (e instanceof AuthorizationError) {
|
|
53
|
+
return sendUnauthorizedResponse(res, e.message);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
next(e);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type GetTokenFromRequest = (req: Request) => Promise<string> | string;
|
|
62
|
+
|
|
63
|
+
export const getTokenFromHttpHeader: GetTokenFromRequest = (
|
|
64
|
+
req: Request,
|
|
65
|
+
): string => {
|
|
66
|
+
// The names of a HTTP header bearing the JWT, and a scheme
|
|
67
|
+
const headerName = "Authorization";
|
|
68
|
+
const schemeName = "Bearer";
|
|
69
|
+
|
|
70
|
+
const header = req.header(headerName);
|
|
71
|
+
if (!header) {
|
|
72
|
+
throw new AuthorizationError(`Missing the "${headerName}" header`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (!header.match(new RegExp(`^${schemeName}\\s+[^\\s]+$`, "i"))) {
|
|
76
|
+
console.trace(
|
|
77
|
+
`jwtMiddleware: failed to match token in "${headerName}" header`,
|
|
78
|
+
);
|
|
79
|
+
throw new AuthorizationError(
|
|
80
|
+
`Missing a "${schemeName}" token in the "${headerName}" header`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const token = header.replace(new RegExp(`^${schemeName}\\s+`, "i"), "");
|
|
85
|
+
|
|
86
|
+
return token;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A class representing JWT validation errors in the JWT middleware.
|
|
91
|
+
* The error message provided to the constructor will be forwarded to the
|
|
92
|
+
* API consumer trying to access a JWT-protected endpoint.
|
|
93
|
+
* @private
|
|
94
|
+
*/
|
|
95
|
+
export class AuthorizationError extends Error {
|
|
96
|
+
constructor(message: string) {
|
|
97
|
+
super(message);
|
|
98
|
+
|
|
99
|
+
Object.setPrototypeOf(this, AuthorizationError.prototype);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createBearerMiddleware } from "./bearer_middleware";
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-require-imports */
|
|
2
|
+
import type { NextFunction, Request, Response } from "express";
|
|
3
|
+
import type {
|
|
4
|
+
createBearerMiddleware,
|
|
5
|
+
GetTokenFromRequest,
|
|
6
|
+
} from "../bearer_middleware";
|
|
7
|
+
|
|
8
|
+
type Middleware = (req: Request, res: Response, next: NextFunction) => void;
|
|
9
|
+
|
|
10
|
+
describe("createBearerMiddleware", () => {
|
|
11
|
+
let fakeGetTokenFromRequest: jest.MockedFn<GetTokenFromRequest>;
|
|
12
|
+
let verify: jest.MockedFn<(token: string) => Promise<string | undefined>>;
|
|
13
|
+
|
|
14
|
+
let req: Request;
|
|
15
|
+
let res: Response;
|
|
16
|
+
let next: jest.MockedFn<() => void>;
|
|
17
|
+
|
|
18
|
+
let AuthorizationError: typeof Error;
|
|
19
|
+
let createBearerMiddlewareFn: typeof createBearerMiddleware;
|
|
20
|
+
let bearerMiddleware: Middleware;
|
|
21
|
+
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
jest.resetAllMocks();
|
|
24
|
+
jest.resetModules();
|
|
25
|
+
|
|
26
|
+
fakeGetTokenFromRequest = jest.fn();
|
|
27
|
+
verify = jest.fn();
|
|
28
|
+
|
|
29
|
+
const middlewareModule = require("../bearer_middleware");
|
|
30
|
+
createBearerMiddlewareFn = middlewareModule.createBearerMiddleware;
|
|
31
|
+
AuthorizationError = middlewareModule.AuthorizationError;
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
describe("When called", () => {
|
|
35
|
+
beforeEach(() => {
|
|
36
|
+
req = {
|
|
37
|
+
header: (_name: string) => undefined,
|
|
38
|
+
} as Request;
|
|
39
|
+
|
|
40
|
+
res = {
|
|
41
|
+
status: jest.fn().mockReturnThis(),
|
|
42
|
+
json: jest.fn().mockReturnThis(),
|
|
43
|
+
send: jest.fn().mockReturnThis(),
|
|
44
|
+
} as unknown as Response;
|
|
45
|
+
|
|
46
|
+
next = jest.fn();
|
|
47
|
+
|
|
48
|
+
bearerMiddleware = createBearerMiddlewareFn(
|
|
49
|
+
verify,
|
|
50
|
+
fakeGetTokenFromRequest,
|
|
51
|
+
);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
describe("When `getTokenFromRequest` throws an exception ('Fake error')", () => {
|
|
55
|
+
beforeEach(() => {
|
|
56
|
+
fakeGetTokenFromRequest.mockRejectedValue(
|
|
57
|
+
new AuthorizationError("Fake error"),
|
|
58
|
+
);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it(`Does not call next() and returns HTTP 401 with error = "unauthorized" and message = "Fake error"`, async () => {
|
|
62
|
+
expect.assertions(8);
|
|
63
|
+
|
|
64
|
+
expect(fakeGetTokenFromRequest).not.toHaveBeenCalled();
|
|
65
|
+
await bearerMiddleware(req, res, next);
|
|
66
|
+
|
|
67
|
+
expect(fakeGetTokenFromRequest).toHaveBeenCalledTimes(1);
|
|
68
|
+
expect(fakeGetTokenFromRequest).toHaveBeenLastCalledWith(req);
|
|
69
|
+
|
|
70
|
+
expect(res.status).toHaveBeenCalledTimes(1);
|
|
71
|
+
expect(res.status).toHaveBeenLastCalledWith(401);
|
|
72
|
+
|
|
73
|
+
expect(res.json).toHaveBeenCalledTimes(1);
|
|
74
|
+
expect(res.json).toHaveBeenLastCalledWith({
|
|
75
|
+
error: "unauthorized",
|
|
76
|
+
message: "Fake error",
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
expect(next).not.toHaveBeenCalled();
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe("When the middleware cannot verify the token", () => {
|
|
84
|
+
beforeEach(() => {
|
|
85
|
+
fakeGetTokenFromRequest.mockReturnValue("TOKEN");
|
|
86
|
+
|
|
87
|
+
verify.mockImplementation(() => Promise.resolve(undefined));
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it(`Does not call next() and returns HTTP 401 with error = "unauthorized" and message = "Token is invalid"`, async () => {
|
|
91
|
+
expect.assertions(5);
|
|
92
|
+
|
|
93
|
+
await bearerMiddleware(req, res, next);
|
|
94
|
+
|
|
95
|
+
expect(res.status).toHaveBeenCalledTimes(1);
|
|
96
|
+
expect(res.status).toHaveBeenLastCalledWith(401);
|
|
97
|
+
|
|
98
|
+
expect(res.json).toHaveBeenCalledTimes(1);
|
|
99
|
+
expect(res.json).toHaveBeenLastCalledWith({
|
|
100
|
+
error: "unauthorized",
|
|
101
|
+
message: "Token is invalid",
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
expect(next).not.toHaveBeenCalled();
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe("getTokenFromHttpHeader", () => {
|
|
111
|
+
let getHeader: jest.MockedFn<(name: string) => string | undefined>;
|
|
112
|
+
let req: Request;
|
|
113
|
+
let getTokenFromHttpHeader: (req: Request) => string;
|
|
114
|
+
let AuthorizationError: typeof Error;
|
|
115
|
+
|
|
116
|
+
beforeEach(() => {
|
|
117
|
+
getHeader = jest.fn();
|
|
118
|
+
req = {
|
|
119
|
+
header: (name: string) => getHeader(name),
|
|
120
|
+
} as Request;
|
|
121
|
+
|
|
122
|
+
const bearerMiddlewareModule = require("../bearer_middleware");
|
|
123
|
+
getTokenFromHttpHeader = bearerMiddlewareModule.getTokenFromHttpHeader;
|
|
124
|
+
AuthorizationError = bearerMiddlewareModule.AuthorizationError;
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
describe("When the 'Authorization' header is missing", () => {
|
|
128
|
+
beforeEach(() => {
|
|
129
|
+
getHeader.mockReturnValue(undefined);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it(`Throws a AuthorizationError with message = 'Missing the "Authorization" header'`, async () => {
|
|
133
|
+
expect.assertions(3);
|
|
134
|
+
|
|
135
|
+
expect(() => getTokenFromHttpHeader(req)).toThrow(
|
|
136
|
+
new AuthorizationError('Missing the "Authorization" header'),
|
|
137
|
+
);
|
|
138
|
+
expect(getHeader).toHaveBeenCalledTimes(1);
|
|
139
|
+
expect(getHeader).toHaveBeenLastCalledWith("Authorization");
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
describe("When the 'Authorization' header doesn't have a Bearer scheme", () => {
|
|
144
|
+
beforeEach(() => {
|
|
145
|
+
getHeader.mockReturnValue("Beerer FAKE_TOKEN");
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it(`Throws a AuthorizationError with message = 'Missing a "Bearer" token in the "Authorization" header''`, async () => {
|
|
149
|
+
expect.assertions(3);
|
|
150
|
+
|
|
151
|
+
expect(() => getTokenFromHttpHeader(req)).toThrow(
|
|
152
|
+
new AuthorizationError(
|
|
153
|
+
'Missing a "Bearer" token in the "Authorization" header',
|
|
154
|
+
),
|
|
155
|
+
);
|
|
156
|
+
expect(getHeader).toHaveBeenCalledTimes(1);
|
|
157
|
+
expect(getHeader).toHaveBeenLastCalledWith("Authorization");
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
describe("When the 'Authorization' Bearer scheme header doesn't have a token", () => {
|
|
162
|
+
beforeEach(() => {
|
|
163
|
+
getHeader.mockReturnValue("Bearer ");
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it(`Throws a AuthorizationError with message = 'Missing a "Bearer" token in the "Authorization" header'`, async () => {
|
|
167
|
+
expect.assertions(3);
|
|
168
|
+
|
|
169
|
+
expect(() => getTokenFromHttpHeader(req)).toThrow(
|
|
170
|
+
new AuthorizationError(
|
|
171
|
+
'Missing a "Bearer" token in the "Authorization" header',
|
|
172
|
+
),
|
|
173
|
+
);
|
|
174
|
+
expect(getHeader).toHaveBeenCalledTimes(1);
|
|
175
|
+
expect(getHeader).toHaveBeenLastCalledWith("Authorization");
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe("When the 'Authorization' Bearer scheme header has a token", () => {
|
|
180
|
+
beforeEach(() => {
|
|
181
|
+
getHeader.mockReturnValue("Bearer TOKEN");
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it(`Returns the token`, async () => {
|
|
185
|
+
expect.assertions(3);
|
|
186
|
+
|
|
187
|
+
expect(getTokenFromHttpHeader(req)).toEqual("TOKEN");
|
|
188
|
+
expect(getHeader).toHaveBeenCalledTimes(1);
|
|
189
|
+
expect(getHeader).toHaveBeenLastCalledWith("Authorization");
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
});
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "empty-template",
|
|
4
4
|
"description": "An empty Canva App",
|
|
5
5
|
"scripts": {
|
|
6
|
-
"extract": "formatjs extract
|
|
6
|
+
"extract": "formatjs extract src/**/*.{ts,tsx} --out-file dist/messages_en.json",
|
|
7
7
|
"build": "webpack --config webpack.config.cjs --mode production && npm run extract",
|
|
8
8
|
"format": "prettier '**/*.{css,ts,tsx}' --no-config --write",
|
|
9
9
|
"format:check": "prettier '**/*.{css,ts,tsx}' --no-config --check --ignore-path",
|
|
@@ -16,9 +16,10 @@
|
|
|
16
16
|
"test:watch": "jest --watchAll"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@canva/app-ui-kit": "^
|
|
20
|
-
"@canva/app-i18n-kit": "^0.0
|
|
21
|
-
"@canva/design": "^2.
|
|
19
|
+
"@canva/app-ui-kit": "^4.1.0",
|
|
20
|
+
"@canva/app-i18n-kit": "^1.0.0",
|
|
21
|
+
"@canva/design": "^2.1.0",
|
|
22
|
+
"@canva/platform": "^2.0.0",
|
|
22
23
|
"@canva/error": "^2.0.0",
|
|
23
24
|
"react": "18.3.1",
|
|
24
25
|
"react-dom": "18.3.1",
|
|
@@ -26,32 +27,32 @@
|
|
|
26
27
|
},
|
|
27
28
|
"devDependencies": {
|
|
28
29
|
"@eslint/eslintrc": "3.1.0",
|
|
29
|
-
"@eslint/js": "9.
|
|
30
|
+
"@eslint/js": "9.12.0",
|
|
30
31
|
"@formatjs/cli": "6.2.12",
|
|
31
32
|
"@formatjs/ts-transformer": "3.13.14",
|
|
32
33
|
"@ngrok/ngrok": "1.4.1",
|
|
33
34
|
"@svgr/webpack": "8.1.0",
|
|
34
|
-
"@types/jest": "29.5.
|
|
35
|
+
"@types/jest": "29.5.13",
|
|
35
36
|
"@types/node": "20.10.0",
|
|
36
37
|
"@types/node-fetch": "2.6.11",
|
|
37
38
|
"@types/node-forge": "1.3.11",
|
|
38
39
|
"@types/nodemon": "1.19.6",
|
|
39
|
-
"@types/react": "18.3.
|
|
40
|
-
"@types/react-dom": "18.3.
|
|
40
|
+
"@types/react": "18.3.11",
|
|
41
|
+
"@types/react-dom": "18.3.1",
|
|
41
42
|
"@types/webpack-env": "1.18.5",
|
|
42
|
-
"@typescript-eslint/eslint-plugin": "8.
|
|
43
|
-
"@typescript-eslint/parser": "8.
|
|
43
|
+
"@typescript-eslint/eslint-plugin": "8.9.0",
|
|
44
|
+
"@typescript-eslint/parser": "8.9.0",
|
|
44
45
|
"chalk": "4.1.2",
|
|
45
46
|
"cli-table3": "0.6.5",
|
|
46
47
|
"css-loader": "7.1.2",
|
|
47
48
|
"css-modules-typescript-loader": "4.0.1",
|
|
48
|
-
"cssnano": "7.0.
|
|
49
|
-
"debug": "4.3.
|
|
49
|
+
"cssnano": "7.0.6",
|
|
50
|
+
"debug": "4.3.7",
|
|
50
51
|
"dotenv": "16.4.5",
|
|
51
|
-
"eslint": "
|
|
52
|
-
"eslint-plugin-formatjs": "
|
|
53
|
-
"eslint-plugin-jest": "28.8.
|
|
54
|
-
"eslint-plugin-react": "7.
|
|
52
|
+
"eslint": "9.12.0",
|
|
53
|
+
"eslint-plugin-formatjs": "5.0.0",
|
|
54
|
+
"eslint-plugin-jest": "28.8.3",
|
|
55
|
+
"eslint-plugin-react": "7.37.1",
|
|
55
56
|
"jest": "29.7.0",
|
|
56
57
|
"mini-css-extract-plugin": "2.9.1",
|
|
57
58
|
"node-fetch": "3.3.2",
|
|
@@ -61,14 +62,14 @@
|
|
|
61
62
|
"prettier": "3.3.3",
|
|
62
63
|
"style-loader": "4.0.0",
|
|
63
64
|
"terser-webpack-plugin": "5.3.10",
|
|
64
|
-
"ts-jest": "29.2.
|
|
65
|
+
"ts-jest": "29.2.5",
|
|
65
66
|
"ts-loader": "9.5.1",
|
|
66
67
|
"ts-node": "10.9.2",
|
|
67
68
|
"typescript": "5.5.4",
|
|
68
69
|
"url-loader": "4.1.1",
|
|
69
|
-
"webpack": "5.
|
|
70
|
+
"webpack": "5.95.0",
|
|
70
71
|
"webpack-cli": "5.1.4",
|
|
71
|
-
"webpack-dev-server": "5.0
|
|
72
|
+
"webpack-dev-server": "5.1.0",
|
|
72
73
|
"yargs": "17.7.2"
|
|
73
74
|
}
|
|
74
75
|
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { Button, Rows, Text } from "@canva/app-ui-kit";
|
|
2
|
-
import { addElementAtPoint } from "@canva/design";
|
|
3
2
|
import { FormattedMessage, useIntl } from "react-intl";
|
|
4
3
|
import * as styles from "styles/components.css";
|
|
4
|
+
import { useAddElement } from "utils/use_add_element";
|
|
5
5
|
|
|
6
6
|
export const App = () => {
|
|
7
|
+
const addElement = useAddElement();
|
|
8
|
+
|
|
7
9
|
const onClick = () => {
|
|
8
|
-
|
|
10
|
+
addElement({
|
|
9
11
|
type: "text",
|
|
10
12
|
children: ["Hello world!"],
|
|
11
13
|
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
EmbedElement,
|
|
3
|
+
ImageElement,
|
|
4
|
+
RichtextElement,
|
|
5
|
+
TableElement,
|
|
6
|
+
TextElement,
|
|
7
|
+
VideoElement,
|
|
8
|
+
} from "@canva/design";
|
|
9
|
+
import { addElementAtCursor, addElementAtPoint } from "@canva/design";
|
|
10
|
+
import { useFeatureSupport } from "./use_feature_support";
|
|
11
|
+
import { features } from "@canva/platform";
|
|
12
|
+
import { useEffect, useState } from "react";
|
|
13
|
+
|
|
14
|
+
type AddElementParams =
|
|
15
|
+
| ImageElement
|
|
16
|
+
| VideoElement
|
|
17
|
+
| EmbedElement
|
|
18
|
+
| TextElement
|
|
19
|
+
| RichtextElement
|
|
20
|
+
| TableElement;
|
|
21
|
+
|
|
22
|
+
export const useAddElement = () => {
|
|
23
|
+
const isSupported = useFeatureSupport();
|
|
24
|
+
|
|
25
|
+
// Store a wrapped addElement function that checks feature support
|
|
26
|
+
const [addElement, setAddElement] = useState(() => {
|
|
27
|
+
return (element: AddElementParams) => {
|
|
28
|
+
if (features.isSupported(addElementAtPoint)) {
|
|
29
|
+
return addElementAtPoint(element);
|
|
30
|
+
} else if (features.isSupported(addElementAtCursor)) {
|
|
31
|
+
return addElementAtCursor(element);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
useEffect(() => {
|
|
37
|
+
const addElement = (element: AddElementParams) => {
|
|
38
|
+
if (isSupported(addElementAtPoint)) {
|
|
39
|
+
return addElementAtPoint(element);
|
|
40
|
+
} else if (isSupported(addElementAtCursor)) {
|
|
41
|
+
return addElementAtCursor(element);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
setAddElement(() => addElement);
|
|
45
|
+
}, [isSupported]);
|
|
46
|
+
|
|
47
|
+
return addElement;
|
|
48
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { features } from "@canva/platform";
|
|
2
|
+
import type { Feature } from "@canva/platform";
|
|
3
|
+
import { useState, useEffect } from "react";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* This hook allows re-rendering of a React component whenever
|
|
7
|
+
* the state of feature support changes in Canva.
|
|
8
|
+
*
|
|
9
|
+
* @returns isSupported - callback to inspect a Canva SDK method.
|
|
10
|
+
**/
|
|
11
|
+
export function useFeatureSupport() {
|
|
12
|
+
// Store a wrapped function that checks feature support
|
|
13
|
+
const [isSupported, setIsSupported] = useState(() => {
|
|
14
|
+
return (...args: Feature[]) => features.isSupported(...args);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
useEffect(() => {
|
|
18
|
+
// create new function ref when feature support changes to trigger
|
|
19
|
+
// re-render
|
|
20
|
+
return features.registerOnSupportChange(() => {
|
|
21
|
+
setIsSupported(() => {
|
|
22
|
+
return (...args: Feature[]) => features.isSupported(...args);
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
}, []);
|
|
26
|
+
|
|
27
|
+
return isSupported;
|
|
28
|
+
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import * as fs from "fs/promises";
|
|
2
|
-
import * as path from "path";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* This file creates a "database" out of a JSON file. It's only for
|
|
6
|
-
* demonstration purposes. A real app should use a real database.
|
|
7
|
-
*/
|
|
8
|
-
const DATABASE_FILE_PATH = path.join(__dirname, "db.json");
|
|
9
|
-
|
|
10
|
-
interface Database<T> {
|
|
11
|
-
read(): Promise<T>;
|
|
12
|
-
write(data: T): Promise<void>;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export class JSONFileDatabase<T> implements Database<T> {
|
|
16
|
-
constructor(private readonly seedData: T) {}
|
|
17
|
-
|
|
18
|
-
// Creates a database file if one doesn't already exist
|
|
19
|
-
private async init(): Promise<void> {
|
|
20
|
-
try {
|
|
21
|
-
// Do nothing, since the database is initialized
|
|
22
|
-
await fs.stat(DATABASE_FILE_PATH);
|
|
23
|
-
} catch {
|
|
24
|
-
const file = JSON.stringify(this.seedData);
|
|
25
|
-
await fs.writeFile(DATABASE_FILE_PATH, file);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// Loads and parses the database file
|
|
30
|
-
async read(): Promise<T> {
|
|
31
|
-
await this.init();
|
|
32
|
-
const file = await fs.readFile(DATABASE_FILE_PATH, "utf8");
|
|
33
|
-
return JSON.parse(file);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// Overwrites the database file with provided data
|
|
37
|
-
async write(data: T): Promise<void> {
|
|
38
|
-
await this.init();
|
|
39
|
-
const file = JSON.stringify(data);
|
|
40
|
-
await fs.writeFile(DATABASE_FILE_PATH, file);
|
|
41
|
-
}
|
|
42
|
-
}
|