@canva/cli 1.11.0 → 1.13.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +13 -0
  3. package/cli.js +593 -580
  4. package/lib/cjs/index.cjs +3 -3
  5. package/lib/esm/index.mjs +4 -4
  6. package/package.json +7 -2
  7. package/templates/base/package.json +7 -7
  8. package/templates/base/webpack.config.ts +0 -1
  9. package/templates/common/jest.config.mjs +1 -1
  10. package/templates/dam/backend/server.ts +8 -0
  11. package/templates/dam/canva-app.json +4 -0
  12. package/templates/dam/package.json +7 -7
  13. package/templates/dam/webpack.config.ts +0 -1
  14. package/templates/data_connector/README.md +1 -1
  15. package/templates/data_connector/package.json +7 -7
  16. package/templates/data_connector/webpack.config.ts +0 -1
  17. package/templates/gen_ai/backend/server.ts +17 -0
  18. package/templates/gen_ai/package.json +7 -7
  19. package/templates/gen_ai/src/api/api.ts +4 -0
  20. package/templates/gen_ai/webpack.config.ts +0 -1
  21. package/templates/hello_world/package.json +7 -7
  22. package/templates/hello_world/webpack.config.ts +0 -1
  23. package/templates/mls/README.md +81 -0
  24. package/templates/mls/canva-app.json +25 -0
  25. package/templates/mls/declarations/declarations.d.ts +29 -0
  26. package/templates/mls/eslint.config.mjs +14 -0
  27. package/templates/mls/jest.config.mjs +36 -0
  28. package/templates/mls/jest.setup.ts +37 -0
  29. package/templates/mls/package.json +117 -0
  30. package/templates/mls/scripts/copy_env.ts +13 -0
  31. package/templates/mls/scripts/ssl/ssl.ts +131 -0
  32. package/templates/mls/scripts/start/app_runner.ts +223 -0
  33. package/templates/mls/scripts/start/context.ts +171 -0
  34. package/templates/mls/scripts/start/start.ts +46 -0
  35. package/templates/mls/src/__tests__/app.tests.tsx +11 -0
  36. package/templates/mls/src/__tests__/office_selection_page.tests.tsx +72 -0
  37. package/templates/mls/src/__tests__/utils.tsx +19 -0
  38. package/templates/mls/src/adapter.ts +126 -0
  39. package/templates/mls/src/components/agent/agent_card.tsx +57 -0
  40. package/templates/mls/src/components/agent/agent_grid.tsx +37 -0
  41. package/templates/mls/src/components/agent/agent_list.tsx +17 -0
  42. package/templates/mls/src/components/agent/agent_search_filters.tsx +88 -0
  43. package/templates/mls/src/components/breadcrumb/breadcrumb.tsx +40 -0
  44. package/templates/mls/src/components/listing/listing_card.tsx +64 -0
  45. package/templates/mls/src/components/listing/listing_grid.tsx +37 -0
  46. package/templates/mls/src/components/listing/listing_list.tsx +21 -0
  47. package/templates/mls/src/components/listing/listing_search_filters.tsx +145 -0
  48. package/templates/mls/src/components/placeholders/placeholders.tsx +65 -0
  49. package/templates/mls/src/data.ts +359 -0
  50. package/templates/mls/src/index.tsx +4 -0
  51. package/templates/mls/src/intents/design_editor/app.tsx +44 -0
  52. package/templates/mls/src/intents/design_editor/index.tsx +25 -0
  53. package/templates/mls/src/pages/agent_details_page/agent_details_page.tsx +175 -0
  54. package/templates/mls/src/pages/list_page/agent_tab_panel.tsx +126 -0
  55. package/templates/mls/src/pages/list_page/list_page.tsx +67 -0
  56. package/templates/mls/src/pages/list_page/listing_tab_panel.tsx +135 -0
  57. package/templates/mls/src/pages/listing_details_page/listing_details_page.tsx +418 -0
  58. package/templates/mls/src/pages/loading_page/loading_page.tsx +152 -0
  59. package/templates/mls/src/pages/office_selection_page/office_selection_page.tsx +144 -0
  60. package/templates/mls/src/real_estate.type.ts +44 -0
  61. package/templates/mls/src/util/use_add_element.tsx +62 -0
  62. package/templates/mls/src/util/use_drag_element.tsx +68 -0
  63. package/templates/mls/styles/components.css +56 -0
  64. package/templates/mls/tsconfig.json +55 -0
  65. package/templates/mls/webpack.config.ts +253 -0
  66. package/templates/base/backend/routers/oauth.ts +0 -393
  67. package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +0 -99
  68. package/templates/base/utils/backend/bearer_middleware/index.ts +0 -1
  69. package/templates/base/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +0 -192
  70. package/templates/common/utils/backend/base_backend/create.ts +0 -104
  71. package/templates/gen_ai/backend/database/database.ts +0 -42
  72. package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +0 -99
  73. package/templates/gen_ai/utils/backend/bearer_middleware/index.ts +0 -1
  74. /package/templates/base/{utils/backend → backend}/base_backend/create.ts +0 -0
  75. /package/templates/base/{utils/backend → backend}/jwt_middleware/index.ts +0 -0
  76. /package/templates/base/{utils/backend → backend}/jwt_middleware/jwt_middleware.ts +0 -0
  77. /package/templates/{common → gen_ai}/utils/backend/jwt_middleware/index.ts +0 -0
  78. /package/templates/{common → gen_ai}/utils/backend/jwt_middleware/jwt_middleware.ts +0 -0
@@ -0,0 +1,223 @@
1
+ /* eslint-disable no-console */
2
+ import { generatePreviewUrl } from "@canva/cli";
3
+ import ngrok from "@ngrok/ngrok";
4
+ import chalk from "chalk";
5
+ import Table from "cli-table3";
6
+ import nodemon from "nodemon";
7
+ import open from "open";
8
+ import os from "os";
9
+ import webpack from "webpack";
10
+ import WebpackDevServer from "webpack-dev-server";
11
+ import { buildConfig } from "../../webpack.config";
12
+ import type { Certificate } from "../ssl/ssl";
13
+ import { createOrRetrieveCertificate } from "../ssl/ssl";
14
+ import type { Context } from "./context";
15
+
16
+ export const infoChalk = chalk.blue.bold;
17
+ export const warnChalk = chalk.bgYellow.bold;
18
+ export const errorChalk = chalk.bgRed.bold;
19
+ export const highlightChalk = chalk.greenBright.bold;
20
+ export const linkChalk = chalk.cyan;
21
+
22
+ /**
23
+ * Returns the appropriate modifier key text based on the user's operating system.
24
+ * @returns "cmd" for macOS, "ctrl" for Windows and Linux
25
+ */
26
+ export function getModifierKey(): string {
27
+ const platform = os.platform();
28
+ switch (platform) {
29
+ case "darwin": // macOS
30
+ return "cmd";
31
+ case "win32": // Windows
32
+ return "ctrl";
33
+ default: // Linux and others
34
+ return "ctrl";
35
+ }
36
+ }
37
+
38
+ export class AppRunner {
39
+ async run(ctx: Context) {
40
+ console.log(
41
+ infoChalk("Info:"),
42
+ `Starting development server for ${highlightChalk(ctx.entryDir)}\n`,
43
+ );
44
+
45
+ if (!ctx.hmrEnabled) {
46
+ console.log(
47
+ `${infoChalk(
48
+ "Note:",
49
+ )} Hot Module Replacement (HMR) not enabled. To enable it, please refer to the instructions in the ${highlightChalk(
50
+ "README.md",
51
+ )}\n`,
52
+ );
53
+ }
54
+
55
+ let cert: Certificate | undefined;
56
+ if (ctx.httpsEnabled) {
57
+ try {
58
+ cert = await createOrRetrieveCertificate();
59
+ } catch (err) {
60
+ console.log(
61
+ errorChalk("Error:"),
62
+ "Unable to generate SSL certificate.",
63
+ );
64
+ throw err;
65
+ }
66
+ }
67
+
68
+ const table = new Table({
69
+ colWidths: [30, 80],
70
+ wordWrap: true,
71
+ wrapOnWordBoundary: true,
72
+ });
73
+
74
+ const server = await this.runWebpackDevServer(ctx, table, cert);
75
+
76
+ await this.maybeRunBackendServer(ctx, table, cert, server);
77
+
78
+ await this.generateAndOpenPreviewUrl(ctx.openPreview, table);
79
+
80
+ console.log(table.toString(), "\n");
81
+
82
+ console.log(
83
+ `${infoChalk(
84
+ "Note:",
85
+ )} For instructions on how to set up the app via the Developer Portal, see the ${highlightChalk(
86
+ "README.md",
87
+ )}.\n`,
88
+ );
89
+ }
90
+
91
+ private readonly maybeRunBackendServer = async (
92
+ ctx: Context,
93
+ table: Table.Table,
94
+ cert: Certificate | undefined,
95
+ webpackDevServer: WebpackDevServer,
96
+ ) => {
97
+ if (!ctx.developerBackendEntryPath) {
98
+ return;
99
+ }
100
+
101
+ // App ID must be set when running a backend example
102
+ if (!ctx.appId) {
103
+ console.log(
104
+ errorChalk("Error:"),
105
+ `'CANVA_APP_ID' environment variable is undefined. Refer to the instructions in the ${highlightChalk(
106
+ "README.md",
107
+ )} on starting a backend example.`,
108
+ );
109
+ throw new Error("'CANVA_APP_ID' env variable not set.");
110
+ }
111
+
112
+ await new Promise((resolve) => {
113
+ const nodemonServer = nodemon({
114
+ script: ctx.developerBackendEntryPath,
115
+ ext: "ts",
116
+ env: {
117
+ SHOULD_ENABLE_HTTPS: ctx.httpsEnabled,
118
+ HTTPS_CERT_FILE: cert?.certFile || "",
119
+ HTTPS_KEY_FILE: cert?.keyFile || "",
120
+ },
121
+ });
122
+
123
+ nodemonServer.on("start", resolve);
124
+
125
+ nodemonServer.on("crash", async () => {
126
+ console.log(errorChalk("Shutting down local server.\n"));
127
+
128
+ await webpackDevServer.stop();
129
+ process.exit(1);
130
+ });
131
+ });
132
+
133
+ if (ctx.ngrokEnabled) {
134
+ console.log(
135
+ warnChalk("Warning:"),
136
+ `ngrok exposes a local port via a public URL. Be mindful of what's exposed and shut down the server when it's not in use.\n`,
137
+ );
138
+ }
139
+
140
+ let url = ctx.backendUrl;
141
+ if (ctx.ngrokEnabled) {
142
+ try {
143
+ const ngrokListener = await ngrok.forward({
144
+ addr: ctx.backendPort,
145
+ // requires an `NGROK_AUTHTOKEN` env var to be set
146
+ authtoken_from_env: true,
147
+ });
148
+ url = ngrokListener.url() ?? url;
149
+ } catch (err) {
150
+ console.log(
151
+ errorChalk("Error:"),
152
+ `Unable to start ngrok server: ${err}`,
153
+ );
154
+ }
155
+ }
156
+
157
+ table.push(["Base URL (Backend)", linkChalk(url)]);
158
+ };
159
+
160
+ private readonly runWebpackDevServer = async (
161
+ ctx: Context,
162
+ table: Table.Table,
163
+ cert: Certificate | undefined,
164
+ ): Promise<WebpackDevServer> => {
165
+ const runtimeWebpackConfig = buildConfig({
166
+ appEntry: ctx.frontendEntryPath,
167
+ backendHost: ctx.backendHost,
168
+ devConfig: {
169
+ port: ctx.frontendPort,
170
+ enableHmr: ctx.hmrEnabled,
171
+ appId: ctx.appId,
172
+ appOrigin: ctx.appOrigin,
173
+ enableHttps: ctx.httpsEnabled,
174
+ ...cert,
175
+ },
176
+ });
177
+
178
+ const compiler = webpack(runtimeWebpackConfig);
179
+ const server = new WebpackDevServer(
180
+ runtimeWebpackConfig.devServer,
181
+ compiler,
182
+ );
183
+ await server.start();
184
+
185
+ table.push(["Development URL (Frontend)", linkChalk(ctx.frontendUrl)]);
186
+
187
+ return server;
188
+ };
189
+
190
+ /**
191
+ * Calls the Canva CLI to generate a preview URL for the app
192
+ */
193
+ private readonly generateAndOpenPreviewUrl = async (
194
+ openPreview: boolean,
195
+ table: Table.Table,
196
+ ) => {
197
+ const previewCellHeader = { content: "Preview your app in Canva" };
198
+
199
+ const generatePreviewResult = await generatePreviewUrl();
200
+
201
+ if (!generatePreviewResult.success) {
202
+ table.push([
203
+ previewCellHeader,
204
+ { content: warnChalk(generatePreviewResult.message) },
205
+ ]);
206
+ return;
207
+ }
208
+
209
+ const modifierKey = getModifierKey();
210
+
211
+ table.push([
212
+ previewCellHeader,
213
+ {
214
+ content: `Preview URL (${modifierKey} + click)`,
215
+ href: generatePreviewResult.data,
216
+ },
217
+ ]);
218
+
219
+ if (openPreview) {
220
+ open(generatePreviewResult.data);
221
+ }
222
+ };
223
+ }
@@ -0,0 +1,171 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+
4
+ interface CliArgs {
5
+ example?: string;
6
+ useHttps: boolean;
7
+ ngrok: boolean;
8
+ preview: boolean;
9
+ overrideFrontendPort?: number;
10
+ }
11
+
12
+ interface EnvVars {
13
+ frontendPort: number;
14
+ backendPort: number;
15
+ hmrEnabled: boolean;
16
+ appId?: string;
17
+ appOrigin?: string;
18
+ backendHost?: string;
19
+ }
20
+
21
+ export class Context {
22
+ private readonly envVars: EnvVars;
23
+
24
+ constructor(
25
+ private env: NodeJS.ProcessEnv = process.env,
26
+ private readonly args: CliArgs,
27
+ ) {
28
+ this.envVars = this.parseAndValidateEnvironmentVariables();
29
+ }
30
+
31
+ static get srcDir() {
32
+ const src = path.join(Context.rootDir, "src");
33
+
34
+ if (!fs.existsSync(src)) {
35
+ throw new Error(`Directory does not exist: ${src}`);
36
+ }
37
+
38
+ return src;
39
+ }
40
+
41
+ static get readmeDir() {
42
+ return path.join(Context.rootDir, "README.md");
43
+ }
44
+
45
+ get entryDir() {
46
+ return Context.srcDir;
47
+ }
48
+
49
+ get ngrokEnabled() {
50
+ return this.args.ngrok;
51
+ }
52
+
53
+ get hmrEnabled() {
54
+ return this.envVars.hmrEnabled;
55
+ }
56
+
57
+ get httpsEnabled() {
58
+ return this.args.useHttps;
59
+ }
60
+
61
+ get frontendEntryPath() {
62
+ const frontendEntryPath = path.join(this.entryDir, "index.tsx");
63
+
64
+ if (!fs.existsSync(frontendEntryPath)) {
65
+ throw new Error(
66
+ `Entry point for frontend does not exist: ${frontendEntryPath}`,
67
+ );
68
+ }
69
+
70
+ return frontendEntryPath;
71
+ }
72
+
73
+ get frontendUrl() {
74
+ return `${this.protocol}://localhost:${this.frontendPort}`;
75
+ }
76
+
77
+ get frontendPort() {
78
+ return this.args.overrideFrontendPort || this.envVars.frontendPort;
79
+ }
80
+
81
+ get developerBackendEntryPath(): string | undefined {
82
+ const developerBackendEntryPath = path.join(
83
+ Context.rootDir,
84
+ "backend",
85
+ "server.ts",
86
+ );
87
+
88
+ if (!fs.existsSync(developerBackendEntryPath)) {
89
+ return undefined;
90
+ }
91
+
92
+ return developerBackendEntryPath;
93
+ }
94
+
95
+ get backendUrl() {
96
+ return `${this.protocol}://localhost:${this.envVars.backendPort}`;
97
+ }
98
+
99
+ get backendHost() {
100
+ let backendHost = this.envVars.backendHost;
101
+
102
+ // if there's no custom URL provided by the developer, we fallback to our localhost backend
103
+ if (!backendHost || backendHost.trim() === "") {
104
+ backendHost = this.backendUrl;
105
+ }
106
+
107
+ return backendHost;
108
+ }
109
+
110
+ get backendPort() {
111
+ return this.envVars.backendPort;
112
+ }
113
+
114
+ get appOrigin(): string | undefined {
115
+ return this.envVars.appOrigin;
116
+ }
117
+
118
+ get appId(): string | undefined {
119
+ return this.envVars.appId;
120
+ }
121
+
122
+ get openPreview(): boolean {
123
+ return this.args.preview;
124
+ }
125
+
126
+ private get protocol(): "https" | "http" {
127
+ return this.httpsEnabled ? "https" : "http";
128
+ }
129
+
130
+ private static get rootDir() {
131
+ return path.join(process.cwd());
132
+ }
133
+
134
+ private parseAndValidateEnvironmentVariables(): EnvVars {
135
+ const {
136
+ CANVA_FRONTEND_PORT,
137
+ CANVA_BACKEND_PORT,
138
+ CANVA_BACKEND_HOST,
139
+ CANVA_APP_ID,
140
+ CANVA_APP_ORIGIN,
141
+ CANVA_HMR_ENABLED,
142
+ } = this.env;
143
+
144
+ if (!CANVA_FRONTEND_PORT) {
145
+ throw new Error(
146
+ "CANVA_FRONTEND_PORT environment variable is not defined",
147
+ );
148
+ }
149
+
150
+ if (!CANVA_BACKEND_PORT) {
151
+ throw new Error("CANVA_BACKEND_PORT environment variable is not defined");
152
+ }
153
+
154
+ const envVars: EnvVars = {
155
+ frontendPort: parseInt(CANVA_FRONTEND_PORT, 10),
156
+ backendPort: parseInt(CANVA_BACKEND_PORT, 10),
157
+ hmrEnabled: CANVA_HMR_ENABLED?.toLowerCase().trim() === "true",
158
+ appId: CANVA_APP_ID,
159
+ appOrigin: CANVA_APP_ORIGIN,
160
+ backendHost: CANVA_BACKEND_HOST,
161
+ };
162
+
163
+ if (envVars.hmrEnabled && envVars.appOrigin == null) {
164
+ throw new Error(
165
+ "CANVA_HMR_ENABLED environment variable is TRUE, but CANVA_APP_ORIGIN is not set. Refer to the instructions in the README.md on configuring HMR.",
166
+ );
167
+ }
168
+
169
+ return envVars;
170
+ }
171
+ }
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ import yargs from "yargs";
3
+ import { hideBin } from "yargs/helpers";
4
+ import { AppRunner } from "./app_runner";
5
+ import { Context } from "./context";
6
+
7
+ const appRunner = new AppRunner();
8
+
9
+ yargs(hideBin(process.argv))
10
+ .version(false)
11
+ .help()
12
+ .option("ngrok", {
13
+ description: "Run backend server via ngrok.",
14
+ type: "boolean",
15
+ // npm swallows command line args instead of forwarding to the script
16
+ default:
17
+ process.env.npm_config_ngrok?.toLocaleLowerCase().trim() === "true",
18
+ })
19
+ .option("use-https", {
20
+ description: "Start local development server on HTTPS.",
21
+ type: "boolean",
22
+ // npm swallows commands line args instead of forwarding to the script
23
+ default:
24
+ process.env.npm_config_use_https?.toLocaleLowerCase().trim() === "true",
25
+ })
26
+ .option("override-frontend-port", {
27
+ description:
28
+ "Port to run the local development server on. Overrides the frontend port set in the .env file.",
29
+ type: "number",
30
+ alias: "p",
31
+ })
32
+ .option("preview", {
33
+ description: "Open the app in Canva.",
34
+ type: "boolean",
35
+ default: false,
36
+ })
37
+ .command(
38
+ "$0",
39
+ "Starts local development",
40
+ () => {},
41
+ (args) => {
42
+ const ctx = new Context(process.env, args);
43
+ appRunner.run(ctx);
44
+ },
45
+ )
46
+ .parse();
@@ -0,0 +1,11 @@
1
+ import { screen } from "@testing-library/react";
2
+ import React from "react";
3
+ import { App } from "../intents/design_editor/app";
4
+ import { renderInTestProvider } from "./utils";
5
+
6
+ describe("App", () => {
7
+ it("should render the app and start at the office selection page", () => {
8
+ renderInTestProvider(<App />);
9
+ expect(screen.getByText(/select office/i)).toBeInTheDocument();
10
+ });
11
+ });
@@ -0,0 +1,72 @@
1
+ import { screen, waitFor } from "@testing-library/react";
2
+ import React from "react";
3
+ import { OfficeSelectionPage } from "../pages/office_selection_page/office_selection_page";
4
+ import { renderInTestProvider, renderWithUserEvent } from "./utils";
5
+ const mockNavigate = jest.fn();
6
+
7
+ jest.mock("react-router-dom", () => ({
8
+ ...jest.requireActual("react-router-dom"),
9
+ useNavigate: () => mockNavigate,
10
+ }));
11
+
12
+ const mockOffices = [
13
+ { id: "office1", name: "Murray Street" },
14
+ { id: "office2", name: "Jermaine Street" },
15
+ ];
16
+ // Mock the adapter module
17
+ jest.mock("../adapter.ts", () => ({
18
+ fetchOffices: jest.fn().mockResolvedValue(mockOffices),
19
+ }));
20
+
21
+ describe("Office selection page", () => {
22
+ beforeEach(() => {
23
+ jest.clearAllMocks();
24
+ });
25
+
26
+ it("should require a selection of office to continue", async () => {
27
+ const { user } = renderWithUserEvent(<OfficeSelectionPage />);
28
+
29
+ // Should start at office selection page
30
+ expect(screen.getByText(/select office/i)).toBeInTheDocument();
31
+
32
+ // Click the Continue button to submit the form (should show validation error first)
33
+ const continueButton = screen.getByText("Continue");
34
+ user.click(continueButton);
35
+
36
+ // Should show validation error
37
+ await waitFor(() => {
38
+ expect(screen.getByText(/please select an office/i)).toBeInTheDocument();
39
+ });
40
+ });
41
+
42
+ it("should render user account information", async () => {
43
+ renderInTestProvider(<OfficeSelectionPage />);
44
+
45
+ // Should show user account section
46
+ expect(screen.getByText("Account")).toBeInTheDocument();
47
+ expect(screen.getAllByText("Alex Chen")[0]).toBeInTheDocument();
48
+ expect(screen.getByText("alex.chen@example.com")).toBeInTheDocument();
49
+ });
50
+
51
+ it("should navigate to loading page once user selects an office", async () => {
52
+ const { user } = renderWithUserEvent(<OfficeSelectionPage />);
53
+ const office = mockOffices[0];
54
+
55
+ if (!office) {
56
+ throw new Error("No mock office found");
57
+ }
58
+
59
+ user.click(screen.getByText("Select office"));
60
+ await waitFor(() => {
61
+ expect(screen.getByText(office.name)).toBeInTheDocument();
62
+ });
63
+ user.click(screen.getByText(office.name));
64
+ user.click(screen.getByText("Continue"));
65
+ await waitFor(() => {
66
+ expect(mockNavigate).toHaveBeenCalledTimes(1);
67
+ expect(mockNavigate).toHaveBeenCalledWith("/loading", {
68
+ state: { office },
69
+ });
70
+ });
71
+ });
72
+ });
@@ -0,0 +1,19 @@
1
+ import { TestAppI18nProvider } from "@canva/app-i18n-kit";
2
+ import { TestAppUiProvider } from "@canva/app-ui-kit";
3
+ import { render } from "@testing-library/react";
4
+ import type { RenderResult } from "@testing-library/react";
5
+ import userEvent from "@testing-library/user-event";
6
+
7
+ export const renderWithUserEvent = (node: React.ReactNode) => {
8
+ const user = userEvent.setup();
9
+ renderInTestProvider(node);
10
+ return { user };
11
+ };
12
+
13
+ export function renderInTestProvider(node: React.ReactNode): RenderResult {
14
+ return render(
15
+ <TestAppI18nProvider>
16
+ <TestAppUiProvider>{node}</TestAppUiProvider>
17
+ </TestAppI18nProvider>,
18
+ );
19
+ }
@@ -0,0 +1,126 @@
1
+ import { agents, listings } from "./data";
2
+ import type { Agent, Office, Property } from "./real_estate.type";
3
+
4
+ // TODO (App Developer): replace with the real API call
5
+ export const fetchAgents = async (
6
+ office?: Office | null,
7
+ query?: string,
8
+ continuation?: string,
9
+ sortBy?: string,
10
+ ): Promise<{ agents: Agent[]; continuation?: string }> => {
11
+ // eslint-disable-next-line no-console
12
+ console.log("fetchingAgents", { query, continuation, office });
13
+
14
+ if (office?.id === "listings-only-office" || office?.id === "empty-office") {
15
+ return { agents: [], continuation: undefined };
16
+ }
17
+
18
+ if (office?.id === "error-office" || query === "error") {
19
+ throw new Error("Error fetching agents");
20
+ }
21
+ // Apply sorting
22
+ if (sortBy) {
23
+ const [field, direction] = sortBy.split("-");
24
+
25
+ if (field === "name") {
26
+ agents.sort((a, b) => {
27
+ const comparison = a.name.localeCompare(b.name);
28
+ return direction === "asc" ? comparison : -comparison;
29
+ });
30
+ }
31
+ }
32
+
33
+ // Simulate a delay
34
+ await new Promise((resolve) => setTimeout(resolve, 10));
35
+
36
+ let filteredAgents = agents;
37
+
38
+ // Apply search query
39
+ if (query) {
40
+ filteredAgents = filteredAgents.filter(
41
+ (agent) =>
42
+ agent.name.toLowerCase().includes(query.toLowerCase()) ||
43
+ (agent.officeId &&
44
+ agent.officeId.toLowerCase().includes(query.toLowerCase())),
45
+ );
46
+ }
47
+
48
+ if (filteredAgents.length === 0) {
49
+ return { agents: [], continuation: undefined };
50
+ }
51
+
52
+ return {
53
+ agents: filteredAgents,
54
+ continuation:
55
+ continuation && !query ? `${Number(continuation) + 1}` : undefined,
56
+ };
57
+ };
58
+
59
+ // TODO (App Developer): replace with real API calls
60
+ export const fetchListings = async (
61
+ office?: Office | null,
62
+ query?: string,
63
+ propertyType?: string | null,
64
+ sortBy?: string | null,
65
+ continuation?: string,
66
+ ): Promise<{ listings: Property[]; continuation?: string }> => {
67
+ // eslint-disable-next-line no-console
68
+ console.log("fetchingListings", {
69
+ query,
70
+ continuation,
71
+ propertyType,
72
+ sortBy,
73
+ });
74
+ // Simulate a delay
75
+ await new Promise((resolve) => setTimeout(resolve, 1000));
76
+
77
+ if (office?.id === "empty-office" || office?.id === "agents-only-office") {
78
+ return { listings: [], continuation: undefined };
79
+ }
80
+
81
+ if (office?.id === "error-office" || query === "error") {
82
+ throw new Error("Error fetching listings");
83
+ }
84
+
85
+ let filteredListings = listings;
86
+
87
+ // Example filters
88
+ // Apply property type filter
89
+ if (propertyType) {
90
+ filteredListings = filteredListings.filter(
91
+ (listing) =>
92
+ listing.listingType.toLowerCase() === propertyType.toLowerCase(),
93
+ );
94
+ }
95
+
96
+ // Apply sorting filter
97
+ if (sortBy) {
98
+ filteredListings = [...filteredListings].sort((a, b) => {
99
+ const aPrice = parseFloat(a.price.replace(/[$,]/g, ""));
100
+ const bPrice = parseFloat(b.price.replace(/[$,]/g, ""));
101
+ return sortBy === "price-asc" ? aPrice - bPrice : bPrice - aPrice;
102
+ });
103
+ }
104
+
105
+ // Apply search query
106
+ if (query) {
107
+ filteredListings = filteredListings.filter(
108
+ (listing) =>
109
+ listing.address.toLowerCase().includes(query.toLowerCase()) ||
110
+ listing.suburb.toLowerCase().includes(query.toLowerCase()) ||
111
+ listing.description.toLowerCase().includes(query.toLowerCase()) ||
112
+ listing.name.toLowerCase().includes(query.toLowerCase()) ||
113
+ listing.title.toLowerCase().includes(query.toLowerCase()),
114
+ );
115
+ }
116
+
117
+ if (filteredListings.length === 0) {
118
+ return { listings: [], continuation: undefined };
119
+ }
120
+
121
+ return {
122
+ listings: filteredListings,
123
+ continuation:
124
+ continuation && !query ? `${Number(continuation) + 1}` : undefined,
125
+ };
126
+ };