@canonical/summon-application 0.29.0 → 0.31.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 (126) hide show
  1. package/README.md +75 -13
  2. package/dist/esm/application/react/index.js +347 -0
  3. package/dist/esm/application/react/index.js.map +1 -0
  4. package/dist/esm/application/react/templates/.browserslistrc +2 -0
  5. package/dist/esm/application/react/templates/.storybook/main.ts.ejs +10 -0
  6. package/{src → dist/esm}/application/react/templates/README.md.ejs +54 -0
  7. package/dist/esm/application/react/templates/biome.json.ejs +6 -0
  8. package/dist/esm/application/react/templates/gitignore +25 -0
  9. package/{src → dist/esm}/application/react/templates/package.json.ejs +36 -2
  10. package/dist/esm/application/react/templates/patches/react-relay@18.2.0.patch +52 -0
  11. package/dist/esm/application/react/templates/patches/relay-runtime-network@0.1.0.patch +46 -0
  12. package/dist/esm/application/react/templates/relay.config.json +8 -0
  13. package/{src/application/react/templates/src/client/entry.tsx → dist/esm/application/react/templates/src/client/entry.tsx.ejs} +23 -0
  14. package/dist/esm/application/react/templates/src/domains/catalog/CatalogPage.tsx +50 -0
  15. package/dist/esm/application/react/templates/src/domains/catalog/ErrorBoundary.tests.tsx +56 -0
  16. package/dist/esm/application/react/templates/src/domains/catalog/ErrorBoundary.tsx +37 -0
  17. package/dist/esm/application/react/templates/src/domains/catalog/ProductCard.tsx +49 -0
  18. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.stories.tsx +103 -0
  19. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.tests.tsx +80 -0
  20. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.tsx +59 -0
  21. package/dist/esm/application/react/templates/src/domains/catalog/routes.ts +11 -0
  22. package/dist/esm/application/react/templates/src/lib/ClientOnly/ClientOnly.tests.tsx +35 -0
  23. package/dist/esm/application/react/templates/src/lib/ClientOnly/ClientOnly.tsx +31 -0
  24. package/dist/esm/application/react/templates/src/lib/ClientOnly/index.ts +1 -0
  25. package/{src → dist/esm}/application/react/templates/src/lib/Navigation/Navigation.tsx.ejs +3 -0
  26. package/{src/application/react/templates/src/lib/index.ts → dist/esm/application/react/templates/src/lib/index.ts.ejs} +3 -0
  27. package/dist/esm/application/react/templates/src/relay/__generated__/ProductCard_product.graphql.ts +82 -0
  28. package/dist/esm/application/react/templates/src/relay/__generated__/ProductListQuery.graphql.ts +272 -0
  29. package/dist/esm/application/react/templates/src/relay/environment.tests.ts +87 -0
  30. package/dist/esm/application/react/templates/src/relay/environment.ts +119 -0
  31. package/dist/esm/application/react/templates/src/relay/schema.graphql +111 -0
  32. package/dist/esm/application/react/templates/src/relay/schema.tests.ts +137 -0
  33. package/dist/esm/application/react/templates/src/relay/schema.ts +205 -0
  34. package/{src → dist/esm}/application/react/templates/src/routes.tsx.ejs +10 -0
  35. package/{src/application/react/templates/src/server/entry.tsx → dist/esm/application/react/templates/src/server/entry.tsx.ejs} +36 -0
  36. package/{src → dist/esm}/application/react/templates/src/sitemap/getSitemapItems.ts.ejs +3 -0
  37. package/{src/application/react/templates/tsconfig.json → dist/esm/application/react/templates/tsconfig.json.ejs} +3 -0
  38. package/dist/esm/application/react/templates/vite.config.ts.ejs +92 -0
  39. package/dist/esm/application/react/templates/vitest.setup.ts.ejs +22 -0
  40. package/dist/esm/domain/index.js +89 -0
  41. package/dist/esm/domain/index.js.map +1 -0
  42. package/{src/index.ts → dist/esm/index.js} +6 -8
  43. package/dist/esm/index.js.map +1 -0
  44. package/dist/esm/route/index.js +115 -0
  45. package/dist/esm/route/index.js.map +1 -0
  46. package/dist/esm/route/insertRoute.js +178 -0
  47. package/dist/esm/route/insertRoute.js.map +1 -0
  48. package/dist/esm/shared/casing.js +15 -0
  49. package/dist/esm/shared/casing.js.map +1 -0
  50. package/dist/esm/shared/packageManager.js +38 -0
  51. package/dist/esm/shared/packageManager.js.map +1 -0
  52. package/dist/esm/shared/versions.js +88 -0
  53. package/dist/esm/shared/versions.js.map +1 -0
  54. package/dist/esm/wrapper/index.js +72 -0
  55. package/dist/esm/wrapper/index.js.map +1 -0
  56. package/dist/types/application/react/index.d.ts +12 -0
  57. package/dist/types/application/react/index.d.ts.map +1 -0
  58. package/dist/types/domain/index.d.ts +7 -0
  59. package/dist/types/domain/index.d.ts.map +1 -0
  60. package/dist/types/index.d.ts +8 -0
  61. package/dist/types/index.d.ts.map +1 -0
  62. package/dist/types/route/index.d.ts +7 -0
  63. package/dist/types/route/index.d.ts.map +1 -0
  64. package/dist/types/route/insertRoute.d.ts +34 -0
  65. package/dist/types/route/insertRoute.d.ts.map +1 -0
  66. package/{src/shared/casing.ts → dist/types/shared/casing.d.ts} +2 -7
  67. package/dist/types/shared/casing.d.ts.map +1 -0
  68. package/dist/types/shared/packageManager.d.ts +19 -0
  69. package/dist/types/shared/packageManager.d.ts.map +1 -0
  70. package/dist/types/shared/versions.d.ts +15 -0
  71. package/dist/types/shared/versions.d.ts.map +1 -0
  72. package/dist/types/wrapper/index.d.ts +7 -0
  73. package/dist/types/wrapper/index.d.ts.map +1 -0
  74. package/package.json +16 -15
  75. package/src/application/react/index.ts +0 -294
  76. package/src/application/react/templates/.storybook/main.ts +0 -5
  77. package/src/application/react/templates/biome.json.ejs +0 -6
  78. package/src/application/react/templates/vite.config.ts +0 -45
  79. package/src/application/react/templates/vitest.setup.ts +0 -9
  80. package/src/domain/index.ts +0 -119
  81. package/src/index.test.ts +0 -398
  82. package/src/route/index.ts +0 -154
  83. package/src/route/insertRoute.test.ts +0 -98
  84. package/src/route/insertRoute.ts +0 -236
  85. package/src/shared/versions.ts +0 -48
  86. package/src/wrapper/index.ts +0 -100
  87. /package/{src → dist/esm}/application/react/templates/.storybook/decorators/index.ts +0 -0
  88. /package/{src → dist/esm}/application/react/templates/.storybook/decorators/withRouter.tsx +0 -0
  89. /package/{src → dist/esm}/application/react/templates/.storybook/preview.ts +0 -0
  90. /package/{src → dist/esm}/application/react/templates/index.html.ejs +0 -0
  91. /package/{src → dist/esm}/application/react/templates/public/.gitkeep +0 -0
  92. /package/{src → dist/esm}/application/react/templates/public/robots.txt +0 -0
  93. /package/{src → dist/esm}/application/react/templates/src/assets/.gitkeep +0 -0
  94. /package/{src → dist/esm}/application/react/templates/src/domains/account/AccountPage.tsx +0 -0
  95. /package/{src → dist/esm}/application/react/templates/src/domains/account/LoginPage.tsx +0 -0
  96. /package/{src → dist/esm}/application/react/templates/src/domains/account/routes.ts +0 -0
  97. /package/{src → dist/esm}/application/react/templates/src/domains/contact/ContactPage.tsx +0 -0
  98. /package/{src → dist/esm}/application/react/templates/src/domains/contact/routes.ts +0 -0
  99. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/GuidePage.tsx +0 -0
  100. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/HomePage.tsx +0 -0
  101. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/routes.ts +0 -0
  102. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.stories.tsx +0 -0
  103. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.tests.tsx +0 -0
  104. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.tsx +0 -0
  105. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/index.ts +0 -0
  106. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/styles.css +0 -0
  107. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/types.ts +0 -0
  108. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/LazyComponent.stories.tsx +0 -0
  109. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/LazyComponent.tsx +0 -0
  110. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/index.ts +0 -0
  111. /package/{src → dist/esm}/application/react/templates/src/lib/Navigation/index.ts +0 -0
  112. /package/{src → dist/esm}/application/react/templates/src/lib/ThemeSelector/ThemeSelector.tsx +0 -0
  113. /package/{src → dist/esm}/application/react/templates/src/lib/ThemeSelector/index.ts +0 -0
  114. /package/{src → dist/esm}/application/react/templates/src/server/preview.bun.ts +0 -0
  115. /package/{src → dist/esm}/application/react/templates/src/server/preview.express.ts +0 -0
  116. /package/{src → dist/esm}/application/react/templates/src/server/renderer.tsx +0 -0
  117. /package/{src → dist/esm}/application/react/templates/src/server/server.bun.ts +0 -0
  118. /package/{src → dist/esm}/application/react/templates/src/server/server.express.ts +0 -0
  119. /package/{src → dist/esm}/application/react/templates/src/sitemap/renderer.ts +0 -0
  120. /package/{src → dist/esm}/application/react/templates/src/styles/app.css +0 -0
  121. /package/{src → dist/esm}/application/react/templates/src/styles/index.css.ejs +0 -0
  122. /package/{src → dist/esm}/application/react/templates/src/vite-env.d.ts +0 -0
  123. /package/{src → dist/esm}/application/react/templates/test/e2e/serverHarness.ts +0 -0
  124. /package/{src → dist/esm}/application/react/templates/test/e2e/servers.e2e.ts +0 -0
  125. /package/{src → dist/esm}/application/react/templates/vitest.config.ts +0 -0
  126. /package/{src → dist/esm}/application/react/templates/vitest.e2e.config.ts +0 -0
@@ -7,6 +7,9 @@
7
7
  "imports": {
8
8
  "#lib/*": "./src/lib/*",
9
9
  "#domains/*": "./src/domains/*",
10
+ <% if (relay) { -%>
11
+ "#relay/*": "./src/relay/*",
12
+ <% } -%>
10
13
  "#styles/*": "./src/styles/*"
11
14
  },
12
15
  "scripts": {
@@ -26,6 +29,10 @@
26
29
  "check:biome": "biome check",
27
30
  "check:biome:fix": "biome check --write",
28
31
  "check:ts": "tsc --noEmit",
32
+ <% if (relay) { -%>
33
+ "relay": "relay-compiler",
34
+ "relay:watch": "relay-compiler --watch",
35
+ <% } -%>
29
36
  "test": "vitest run",
30
37
  "test:watch": "vitest",
31
38
  "test:coverage": "vitest run --coverage",
@@ -42,11 +49,20 @@
42
49
  "@canonical/react-ssr": "<%= pragmaVersion %>",
43
50
  "@canonical/router-core": "<%= pragmaVersion %>",
44
51
  "@canonical/router-react": "<%= pragmaVersion %>",
52
+ <% if (relay) { -%>
53
+ "@canonical/storybook-addon-relay": "<%= pragmaVersion %>",
54
+ <% } -%>
45
55
  "@canonical/storybook-config": "<%= pragmaVersion %>",
46
56
  "@canonical/styles": "<%= pragmaVersion %>",
47
57
  "express": "^5.2.1",
58
+ <% if (relay) { -%>
59
+ "graphql": "^16.11.0",
60
+ <% } -%>
48
61
  "react": "^19.2.4",
49
- "react-dom": "^19.2.4"
62
+ "react-dom": "^19.2.4"<% if (relay) { %>,
63
+ "react-relay": "^18.2.0",
64
+ "relay-runtime": "^18.2.0",
65
+ "relay-runtime-network": "^0.1.0"<% } %>
50
66
  },
51
67
  "devDependencies": {
52
68
  "@biomejs/biome": "2.4.9",
@@ -59,14 +75,32 @@
59
75
  "@types/node": "^24.12.0",
60
76
  "@types/react": "^19.2.14",
61
77
  "@types/react-dom": "^19.2.3",
78
+ <% if (relay) { -%>
79
+ "@types/react-relay": "^18.2.1",
80
+ "@types/relay-runtime": "^19.0.3",
81
+ "@types/relay-test-utils": "^18.0.0",
82
+ <% } -%>
62
83
  "@vitejs/plugin-react": "^6.0.0",
63
84
  "@vitest/coverage-v8": "^4.0.18",
85
+ "browserslist": "^4.28.1",
64
86
  "bun-types": "^1.3.9",
65
87
  "jsdom": "^28.1.0",
88
+ "lightningcss": "^1.32.0",
89
+ <% if (relay) { -%>
90
+ "relay-compiler": "^18.2.0",
91
+ "relay-test-utils": "^18.2.0",
92
+ <% } -%>
66
93
  "storybook": "^10.3.1",
67
94
  "tsx": "^4.19.0",
68
95
  "typescript": "^5.9.3",
69
96
  "vite": "^8.0.1",
97
+ <% if (relay) { -%>
98
+ "vite-plugin-relay-lite": "^0.12.0",
99
+ <% } -%>
70
100
  "vitest": "^4.0.18"
71
- }
101
+ }<% if (relay) { %>,
102
+ "patchedDependencies": {
103
+ "react-relay@18.2.0": "patches/react-relay@18.2.0.patch",
104
+ "relay-runtime-network@0.1.0": "patches/relay-runtime-network@0.1.0.patch"
105
+ }<% } %>
72
106
  }
@@ -0,0 +1,52 @@
1
+ diff --git a/index.js b/index.js
2
+ index 5fe5bc4a2adf6210e2dc5f84cc33382f47953384..407b9665ffa3b703f8fb2bfffa843a869b5c0957 100644
3
+ --- a/index.js
4
+ +++ b/index.js
5
+ @@ -8,3 +8,47 @@
6
+ */
7
+
8
+ module.exports = require('./lib/index.js');
9
+ +
10
+ +// Patch (pragma): cjs-module-lexer cannot statically detect the exports of
11
+ +// ./lib/index.js because they are member expressions inside an object
12
+ +// literal, so `import { useFragment } from "react-relay"` fails under Node
13
+ +// ESM (and under Vite's dev SSR module runner, which mirrors Node semantics).
14
+ +// The dead branch below is the esbuild-style lexer hint: never executed, but
15
+ +// statically registers the named exports.
16
+ +0 && (module.exports = {
17
+ + ConnectionHandler: null,
18
+ + QueryRenderer: null,
19
+ + LocalQueryRenderer: null,
20
+ + MutationTypes: null,
21
+ + RangeOperations: null,
22
+ + ReactRelayContext: null,
23
+ + applyOptimisticMutation: null,
24
+ + commitLocalUpdate: null,
25
+ + commitMutation: null,
26
+ + createFragmentContainer: null,
27
+ + createPaginationContainer: null,
28
+ + createRefetchContainer: null,
29
+ + fetchQuery_DEPRECATED: null,
30
+ + graphql: null,
31
+ + readInlineData: null,
32
+ + requestSubscription: null,
33
+ + EntryPointContainer: null,
34
+ + RelayEnvironmentProvider: null,
35
+ + ProfilerContext: null,
36
+ + fetchQuery: null,
37
+ + loadQuery: null,
38
+ + loadEntryPoint: null,
39
+ + useClientQuery: null,
40
+ + useFragment: null,
41
+ + useLazyLoadQuery: null,
42
+ + useEntryPointLoader: null,
43
+ + useQueryLoader: null,
44
+ + useMutation: null,
45
+ + usePaginationFragment: null,
46
+ + usePreloadedQuery: null,
47
+ + useRefetchableFragment: null,
48
+ + usePrefetchableForwardPaginationFragment_EXPERIMENTAL: null,
49
+ + useRelayEnvironment: null,
50
+ + useSubscribeToInvalidationState: null,
51
+ + useSubscription: null,
52
+ +});
@@ -0,0 +1,46 @@
1
+ diff --git a/package.json b/package.json
2
+ index e07d3e3d0a22b44df7eb9e0234b3d4e834ed02f2..361aaa655faf54fa13252696ffb248cc4f2694f7 100644
3
+ --- a/package.json
4
+ +++ b/package.json
5
+ @@ -24,13 +24,34 @@
6
+ "test:watch": "vitest"
7
+ },
8
+ "imports": {
9
+ - "#auth/*": "./src/lib/auth/*",
10
+ - "#errors/*": "./src/lib/errors/*",
11
+ - "#executors/*": "./src/lib/executors/*",
12
+ - "#middlewares/*": "./src/lib/middlewares/*",
13
+ - "#ssr/*": "./src/lib/ssr/*",
14
+ - "#testing/*": "./src/lib/testing/*",
15
+ - "#types/*": "./src/lib/types/*"
16
+ + "#auth/*": {
17
+ + "types": "./dist/types/lib/auth/*",
18
+ + "default": "./dist/esm/lib/auth/*"
19
+ + },
20
+ + "#errors/*": {
21
+ + "types": "./dist/types/lib/errors/*",
22
+ + "default": "./dist/esm/lib/errors/*"
23
+ + },
24
+ + "#executors/*": {
25
+ + "types": "./dist/types/lib/executors/*",
26
+ + "default": "./dist/esm/lib/executors/*"
27
+ + },
28
+ + "#middlewares/*": {
29
+ + "types": "./dist/types/lib/middlewares/*",
30
+ + "default": "./dist/esm/lib/middlewares/*"
31
+ + },
32
+ + "#ssr/*": {
33
+ + "types": "./dist/types/lib/ssr/*",
34
+ + "default": "./dist/esm/lib/ssr/*"
35
+ + },
36
+ + "#testing/*": {
37
+ + "types": "./dist/types/lib/testing/*",
38
+ + "default": "./dist/esm/lib/testing/*"
39
+ + },
40
+ + "#types/*": {
41
+ + "types": "./dist/types/lib/types/*",
42
+ + "default": "./dist/esm/lib/types/*"
43
+ + }
44
+ },
45
+ "peerDependencies": {
46
+ "relay-runtime": ">=16.0.0"
@@ -0,0 +1,8 @@
1
+ {
2
+ "src": "./src",
3
+ "schema": "./src/relay/schema.graphql",
4
+ "language": "typescript",
5
+ "eagerEsModules": true,
6
+ "artifactDirectory": "./src/relay/__generated__",
7
+ "excludes": ["**/node_modules/**", "**/__generated__/**", "**/dist/**"]
8
+ }
@@ -2,6 +2,10 @@ import { HeadProvider } from "@canonical/react-head";
2
2
  import { createBrowserRouter } from "@canonical/router-core";
3
3
  import { Outlet, RouterProvider } from "@canonical/router-react";
4
4
  import { hydrateRoot } from "react-dom/client";
5
+ <% if (relay) { -%>
6
+ import { RelayEnvironmentProvider } from "react-relay";
7
+ import { createEnvironment } from "#relay/environment.js";
8
+ <% } -%>
5
9
  import { appRoutes, middleware, notFoundRoute } from "../routes.js";
6
10
  import "#styles/index.css";
7
11
 
@@ -9,12 +13,30 @@ const router = createBrowserRouter(appRoutes, {
9
13
  middleware: [...middleware],
10
14
  notFound: notFoundRoute,
11
15
  });
16
+ <% if (relay) { -%>
17
+
18
+ // One Relay environment (network + normalized store) for the whole browser
19
+ // session — module scope, so client-side navigations share the cache.
20
+ const relayEnvironment = createEnvironment();
21
+ <% } -%>
12
22
 
13
23
  const root = document.getElementById("root");
14
24
  if (!root) {
15
25
  throw new Error('Root element "#root" not found');
16
26
  }
17
27
 
28
+ <% if (relay) { -%>
29
+ hydrateRoot(
30
+ root,
31
+ <HeadProvider>
32
+ <RelayEnvironmentProvider environment={relayEnvironment}>
33
+ <RouterProvider router={router}>
34
+ <Outlet fallback={<p>Loading…</p>} />
35
+ </RouterProvider>
36
+ </RelayEnvironmentProvider>
37
+ </HeadProvider>,
38
+ );
39
+ <% } else { -%>
18
40
  hydrateRoot(
19
41
  root,
20
42
  <HeadProvider>
@@ -23,3 +45,4 @@ hydrateRoot(
23
45
  </RouterProvider>
24
46
  </HeadProvider>,
25
47
  );
48
+ <% } -%>
@@ -0,0 +1,50 @@
1
+ import { useHead } from "@canonical/react-head";
2
+ import { type ReactElement, Suspense } from "react";
3
+ import { ClientOnly } from "#lib/index.js";
4
+ import ErrorBoundary from "./ErrorBoundary.js";
5
+ import ProductList from "./ProductList.js";
6
+
7
+ export default function CatalogPage(): ReactElement {
8
+ useHead({ title: "Catalog — Boilerplate" });
9
+
10
+ return (
11
+ <section aria-labelledby="catalog-title">
12
+ <h1 id="catalog-title">Catalog</h1>
13
+ <p>
14
+ This page demonstrates the Relay data layer. <code>ProductList</code>{" "}
15
+ issues a <code>useLazyLoadQuery</code>, each <code>ProductCard</code>{" "}
16
+ reads its own <code>useFragment</code>, and the environment resolves
17
+ operations against the local mock schema in{" "}
18
+ <code>src/relay/schema.ts</code> — set <code>VITE_GRAPHQL_URL</code> to
19
+ point it at a real endpoint instead.
20
+ </p>
21
+ {/*
22
+ SSR guard: `useLazyLoadQuery` fetches (and suspends) while rendering,
23
+ and the server has no way to serialize the fetched store for the
24
+ client yet — that lands in the follow-up SSR data-hydration PR. Until
25
+ then `ClientOnly` keeps the query off the server render path: the
26
+ server streams the fallback and the browser fetches after hydration.
27
+ */}
28
+ {/*
29
+ The canonical Relay pairing: Suspense renders the pending state while
30
+ `useLazyLoadQuery` is in flight, and the ErrorBoundary renders the
31
+ failure state when the query errors (e.g. an unreachable endpoint in
32
+ `VITE_GRAPHQL_URL` mode) — without it a thrown query error would
33
+ unmount the whole tree to a blank page.
34
+ */}
35
+ <ClientOnly fallback={<p>Loading catalog…</p>}>
36
+ <ErrorBoundary
37
+ fallback={
38
+ <p role="alert">
39
+ The catalog failed to load. Reload the page to try again.
40
+ </p>
41
+ }
42
+ >
43
+ <Suspense fallback={<p>Loading catalog…</p>}>
44
+ <ProductList />
45
+ </Suspense>
46
+ </ErrorBoundary>
47
+ </ClientOnly>
48
+ </section>
49
+ );
50
+ }
@@ -0,0 +1,56 @@
1
+ import { render, screen } from "@testing-library/react";
2
+ import { Suspense } from "react";
3
+ import { RelayEnvironmentProvider } from "react-relay";
4
+ import { createMockEnvironment } from "relay-test-utils";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import ErrorBoundary from "./ErrorBoundary.js";
7
+ import ProductList from "./ProductList.js";
8
+
9
+ describe("ErrorBoundary component", () => {
10
+ afterEach(() => {
11
+ vi.restoreAllMocks();
12
+ });
13
+
14
+ it("renders its children while nothing throws", () => {
15
+ render(
16
+ <ErrorBoundary fallback={<p role="alert">Failed.</p>}>
17
+ <p>Catalog content</p>
18
+ </ErrorBoundary>,
19
+ );
20
+
21
+ expect(screen.getByText("Catalog content")).toBeInTheDocument();
22
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
23
+ });
24
+
25
+ it("renders the fallback when the catalog query errors", async () => {
26
+ // React logs errors caught by boundaries; keep the test output clean.
27
+ vi.spyOn(console, "error").mockImplementation(() => {});
28
+
29
+ const environment = createMockEnvironment();
30
+ // Resolving an operation with an Error rejects it, which makes
31
+ // `useLazyLoadQuery` re-throw during render — exactly what happens when
32
+ // a real endpoint is unreachable. Queue it before rendering, as the
33
+ // query is issued during the initial render.
34
+ environment.mock.queueOperationResolver(
35
+ () => new Error("backend unreachable"),
36
+ );
37
+
38
+ render(
39
+ <RelayEnvironmentProvider environment={environment}>
40
+ <ErrorBoundary
41
+ fallback={<p role="alert">The catalog failed to load.</p>}
42
+ >
43
+ <Suspense fallback={<p>Loading catalog…</p>}>
44
+ <ProductList />
45
+ </Suspense>
46
+ </ErrorBoundary>
47
+ </RelayEnvironmentProvider>,
48
+ );
49
+
50
+ // The fallback replaces the subtree instead of white-screening.
51
+ expect(await screen.findByRole("alert")).toHaveTextContent(
52
+ "The catalog failed to load.",
53
+ );
54
+ expect(screen.queryByText(/products/)).not.toBeInTheDocument();
55
+ });
56
+ });
@@ -0,0 +1,37 @@
1
+ import { Component, type ReactNode } from "react";
2
+
3
+ export interface ErrorBoundaryProps {
4
+ /** Subtree whose render errors this boundary catches. */
5
+ readonly children: ReactNode;
6
+ /** Rendered in place of `children` after an error. */
7
+ readonly fallback: ReactNode;
8
+ }
9
+
10
+ interface ErrorBoundaryState {
11
+ readonly hasError: boolean;
12
+ }
13
+
14
+ /**
15
+ * Catches render errors below it and renders `fallback` instead of letting
16
+ * the error unmount the whole tree to a blank page.
17
+ *
18
+ * Relay's `useLazyLoadQuery` re-throws query errors during render — Suspense
19
+ * only handles the pending state — so a data-driven subtree needs both
20
+ * boundaries: Suspense for loading, this for failure (the canonical Relay
21
+ * pairing; see `CatalogPage`). A class component because error boundaries
22
+ * have no hook equivalent.
23
+ */
24
+ export default class ErrorBoundary extends Component<
25
+ ErrorBoundaryProps,
26
+ ErrorBoundaryState
27
+ > {
28
+ state: ErrorBoundaryState = { hasError: false };
29
+
30
+ static getDerivedStateFromError(): ErrorBoundaryState {
31
+ return { hasError: true };
32
+ }
33
+
34
+ render(): ReactNode {
35
+ return this.state.hasError ? this.props.fallback : this.props.children;
36
+ }
37
+ }
@@ -0,0 +1,49 @@
1
+ import type { ReactElement } from "react";
2
+ import { graphql, useFragment } from "react-relay";
3
+ import type { ProductCard_product$key } from "#relay/__generated__/ProductCard_product.graphql.js";
4
+
5
+ // Data this card needs, colocated with the component. The parent query
6
+ // spreads the fragment, so the card can evolve its field selection without
7
+ // touching `ProductList`.
8
+ const productCardFragment = graphql`
9
+ fragment ProductCard_product on Product {
10
+ name
11
+ tagline
12
+ priceCents
13
+ currency
14
+ rating
15
+ inStock
16
+ }
17
+ `;
18
+
19
+ /** Formats a minor-unit price deterministically (fixed locale, real currency). */
20
+ const formatPrice = (priceCents: number, currency: string): string =>
21
+ new Intl.NumberFormat("en-US", { style: "currency", currency }).format(
22
+ priceCents / 100,
23
+ );
24
+
25
+ export interface ProductCardProps {
26
+ /** Fragment reference to the product this card renders. */
27
+ readonly product: ProductCard_product$key;
28
+ }
29
+
30
+ /**
31
+ * Renders one catalog product from a Relay fragment reference.
32
+ */
33
+ export default function ProductCard({
34
+ product,
35
+ }: ProductCardProps): ReactElement {
36
+ const data = useFragment(productCardFragment, product);
37
+
38
+ return (
39
+ <article aria-label={data.name}>
40
+ <h3>{data.name}</h3>
41
+ <p>{data.tagline}</p>
42
+ <p>
43
+ <strong>{formatPrice(data.priceCents, data.currency)}</strong> · rated{" "}
44
+ {data.rating.toFixed(1)} / 5 ·{" "}
45
+ {data.inStock ? "in stock" : "out of stock"}
46
+ </p>
47
+ </article>
48
+ );
49
+ }
@@ -0,0 +1,103 @@
1
+ import type { RelayParameters } from "@canonical/storybook-addon-relay";
2
+ import type { Meta, StoryObj } from "@storybook/react-vite";
3
+ import { Suspense } from "react";
4
+ import { expect } from "storybook/test";
5
+ import Component from "./ProductList.js";
6
+
7
+ const meta = {
8
+ title: "Catalog/ProductList",
9
+ component: Component,
10
+ // `useLazyLoadQuery` suspends while the (mocked) query is in flight, so
11
+ // every story renders inside a Suspense boundary — the same shape the
12
+ // catalog page uses.
13
+ decorators: [
14
+ (Story) => (
15
+ <Suspense fallback={<p>Loading catalog…</p>}>
16
+ <Story />
17
+ </Suspense>
18
+ ),
19
+ ],
20
+ } satisfies Meta<typeof Component>;
21
+
22
+ export default meta;
23
+
24
+ type Story = StoryObj<typeof meta>;
25
+
26
+ /**
27
+ * `@canonical/storybook-addon-relay` reads `parameters.relay` and resolves
28
+ * the story's operations with `MockPayloadGenerator` + these resolvers.
29
+ * Every displayed field is resolved explicitly so the story is deterministic
30
+ * for visual regression testing.
31
+ */
32
+ export const Default: Story = {
33
+ parameters: {
34
+ relay: {
35
+ mockResolvers: {
36
+ Viewer: () => ({ name: "Ada Lovelace" }),
37
+ ProductConnection: () => ({
38
+ totalCount: 5,
39
+ pageInfo: { hasNextPage: true },
40
+ edges: [
41
+ {
42
+ node: {
43
+ id: "Product:story-1",
44
+ name: "Aurora Dev Board",
45
+ tagline: "A hackable single-board computer for prototyping",
46
+ priceCents: 14_900,
47
+ currency: "USD",
48
+ rating: 4.6,
49
+ inStock: true,
50
+ },
51
+ },
52
+ {
53
+ node: {
54
+ id: "Product:story-2",
55
+ name: "Polar Sensor Kit",
56
+ tagline: "Twelve calibrated sensors in a rugged case",
57
+ priceCents: 8_900,
58
+ currency: "USD",
59
+ rating: 4.2,
60
+ inStock: false,
61
+ },
62
+ },
63
+ ],
64
+ }),
65
+ },
66
+ } satisfies RelayParameters,
67
+ },
68
+ play: async ({ canvas }) => {
69
+ await expect(
70
+ await canvas.findByText("Aurora Dev Board"),
71
+ ).toBeInTheDocument();
72
+ await expect(canvas.getByText("Ada Lovelace")).toBeInTheDocument();
73
+ await expect(
74
+ canvas.getByText(/showing 2 of 5 products/),
75
+ ).toBeInTheDocument();
76
+ // The Polar Sensor Kit is the story's out-of-stock product.
77
+ await expect(canvas.getByText(/out of stock/)).toBeInTheDocument();
78
+ await expect(
79
+ canvas.getByText("More products are available."),
80
+ ).toBeInTheDocument();
81
+ },
82
+ };
83
+
84
+ export const EmptyCatalog: Story = {
85
+ parameters: {
86
+ relay: {
87
+ mockResolvers: {
88
+ Viewer: () => ({ name: "Ada Lovelace" }),
89
+ ProductConnection: () => ({
90
+ totalCount: 0,
91
+ pageInfo: { hasNextPage: false },
92
+ edges: [],
93
+ }),
94
+ },
95
+ } satisfies RelayParameters,
96
+ },
97
+ play: async ({ canvas }) => {
98
+ await expect(
99
+ await canvas.findByText(/showing 0 of 0 products/),
100
+ ).toBeInTheDocument();
101
+ await expect(canvas.queryByRole("article")).not.toBeInTheDocument();
102
+ },
103
+ };
@@ -0,0 +1,80 @@
1
+ import { render, screen } from "@testing-library/react";
2
+ import { Suspense } from "react";
3
+ import { RelayEnvironmentProvider } from "react-relay";
4
+ import type { IEnvironment } from "relay-runtime";
5
+ import { createMockEnvironment, MockPayloadGenerator } from "relay-test-utils";
6
+ import { describe, expect, it } from "vitest";
7
+ import { createEnvironment } from "#relay/environment.js";
8
+ import { CATALOG_PRODUCTS } from "#relay/schema.js";
9
+ import ProductList from "./ProductList.js";
10
+
11
+ const renderProductList = (environment: IEnvironment) =>
12
+ render(
13
+ <RelayEnvironmentProvider environment={environment}>
14
+ <Suspense fallback={<p>Loading catalog…</p>}>
15
+ <ProductList />
16
+ </Suspense>
17
+ </RelayEnvironmentProvider>,
18
+ );
19
+
20
+ describe("ProductList component", () => {
21
+ it("renders the first page from the app's local mock schema", async () => {
22
+ // Integration path: the real factory, whose local executor resolves the
23
+ // query against src/relay/schema.ts — no relay-test-utils involved.
24
+ renderProductList(createEnvironment());
25
+
26
+ const firstProduct = CATALOG_PRODUCTS[0];
27
+ expect(
28
+ await screen.findByRole("article", { name: firstProduct?.name }),
29
+ ).toBeInTheDocument();
30
+ expect(screen.getByText("Ada Lovelace")).toBeInTheDocument();
31
+ expect(
32
+ screen.getByText(new RegExp(`of ${CATALOG_PRODUCTS.length} products`)),
33
+ ).toBeInTheDocument();
34
+ // Product:3 (Beacon Micro Server) is the first page's out-of-stock,
35
+ // 4.2-rated product — pins the stock label and the rating formatting.
36
+ expect(screen.getByText(/out of stock/)).toBeInTheDocument();
37
+ expect(screen.getByText(/rated 4\.2 \/ 5/)).toBeInTheDocument();
38
+ expect(
39
+ screen.getByText("More products are available."),
40
+ ).toBeInTheDocument();
41
+ });
42
+
43
+ it("renders payloads resolved by a relay-test-utils mock environment", async () => {
44
+ const environment = createMockEnvironment();
45
+ // Queue the resolver before rendering: useLazyLoadQuery issues the
46
+ // request during render, and the queued resolver answers it immediately.
47
+ environment.mock.queueOperationResolver((operation) =>
48
+ MockPayloadGenerator.generate(operation, {
49
+ Viewer: () => ({ name: "Grace Hopper" }),
50
+ ProductConnection: () => ({
51
+ totalCount: 1,
52
+ pageInfo: { hasNextPage: false },
53
+ edges: [
54
+ {
55
+ node: {
56
+ id: "Product:mocked",
57
+ name: "Mocked Product",
58
+ tagline: "Straight from MockPayloadGenerator",
59
+ priceCents: 12_500,
60
+ currency: "USD",
61
+ rating: 4.5,
62
+ inStock: true,
63
+ },
64
+ },
65
+ ],
66
+ }),
67
+ }),
68
+ );
69
+
70
+ renderProductList(environment);
71
+
72
+ expect(await screen.findByText("Mocked Product")).toBeInTheDocument();
73
+ expect(screen.getByText("Grace Hopper")).toBeInTheDocument();
74
+ expect(screen.getByText("$125.00", { exact: false })).toBeInTheDocument();
75
+ expect(screen.getByText(/in stock/)).toBeInTheDocument();
76
+ expect(
77
+ screen.queryByText("More products are available."),
78
+ ).not.toBeInTheDocument();
79
+ });
80
+ });
@@ -0,0 +1,59 @@
1
+ import type { ReactElement } from "react";
2
+ import { graphql, useLazyLoadQuery } from "react-relay";
3
+ import type { ProductListQuery } from "#relay/__generated__/ProductListQuery.graphql.js";
4
+ import ProductCard from "./ProductCard.js";
5
+
6
+ /** How many products the list requests from the connection. */
7
+ const PAGE_SIZE = 4;
8
+
9
+ const productListQuery = graphql`
10
+ query ProductListQuery($count: Int!, $cursor: String) {
11
+ viewer {
12
+ name
13
+ products(first: $count, after: $cursor) {
14
+ totalCount
15
+ pageInfo {
16
+ hasNextPage
17
+ }
18
+ edges {
19
+ node {
20
+ id
21
+ ...ProductCard_product
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
27
+ `;
28
+
29
+ /**
30
+ * Fetches the first page of the product catalog with `useLazyLoadQuery` and
31
+ * renders a `ProductCard` (a `useFragment` child) per edge.
32
+ *
33
+ * The hook suspends while the query is in flight, so render this component
34
+ * inside a `Suspense` boundary — and, until the SSR data-serialization PR
35
+ * lands, only on the client (see `CatalogPage`).
36
+ */
37
+ export default function ProductList(): ReactElement {
38
+ const data = useLazyLoadQuery<ProductListQuery>(productListQuery, {
39
+ count: PAGE_SIZE,
40
+ });
41
+ const { products } = data.viewer;
42
+
43
+ return (
44
+ <section aria-label="Product catalog">
45
+ <p>
46
+ Signed in as <strong>{data.viewer.name}</strong> — showing{" "}
47
+ {products.edges.length} of {products.totalCount} products.
48
+ </p>
49
+ <ul>
50
+ {products.edges.map(({ node }) => (
51
+ <li key={node.id}>
52
+ <ProductCard product={node} />
53
+ </li>
54
+ ))}
55
+ </ul>
56
+ {products.pageInfo.hasNextPage && <p>More products are available.</p>}
57
+ </section>
58
+ );
59
+ }
@@ -0,0 +1,11 @@
1
+ import { route } from "@canonical/router-core";
2
+ import CatalogPage from "./CatalogPage.js";
3
+
4
+ const routes = {
5
+ catalog: route({
6
+ url: "/catalog",
7
+ content: CatalogPage,
8
+ }),
9
+ } as const;
10
+
11
+ export default routes;