@plone/aurora 1.0.0-alpha.27 → 1.0.0-alpha.28

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 (58) hide show
  1. package/dist/catalog.json +73 -0
  2. package/dist/preset.d.ts +25 -0
  3. package/dist/preset.js +14 -0
  4. package/dist/registry-publicui.config.d.ts +8 -0
  5. package/dist/registry-publicui.config.js +14 -0
  6. package/dist/registry.config.d.ts +16 -0
  7. package/dist/registry.config.js +17 -0
  8. package/dist/routes.d.ts +25 -0
  9. package/dist/routes.js +23 -0
  10. package/dist/vite.d.ts +24 -0
  11. package/dist/vite.js +135 -0
  12. package/package.json +93 -47
  13. package/pnpmfile.cjs +20 -0
  14. package/server.js +2 -1
  15. package/{app → src/app}/config/index.ts +1 -2
  16. package/{app → src/app}/config/server.server.ts +2 -4
  17. package/{app → src/app}/entry.client.tsx +1 -0
  18. package/{app → src/app}/entry.server.tsx +2 -1
  19. package/{app → src/app}/i18next.server.test.ts +48 -1
  20. package/{app → src/app}/i18next.server.ts +22 -14
  21. package/{app → src/app}/middleware.server.test.ts +0 -68
  22. package/{app → src/app}/middleware.server.ts +32 -40
  23. package/src/app/root.server.ts +124 -0
  24. package/{app → src/app}/root.test.tsx +36 -7
  25. package/src/app/root.tsx +101 -0
  26. package/.release-it.json +0 -32
  27. package/.stylelintrc +0 -8
  28. package/CHANGELOG.md +0 -456
  29. package/Makefile +0 -82
  30. package/acceptance/tests/anonymous-401-redirect.test.ts +0 -75
  31. package/acceptance/tests/basic.test.ts +0 -14
  32. package/acceptance/tests/hydration.test.ts +0 -106
  33. package/acceptance/tests/multilingual-root-redirect.test.ts +0 -45
  34. package/app/root.tsx +0 -191
  35. package/app/routes.ts +0 -20
  36. package/news/.gitkeep +0 -0
  37. package/public/favicon.ico +0 -0
  38. package/public/icon.svg +0 -13
  39. package/react-router.config.ts +0 -11
  40. package/registry-publicui.config.ts +0 -11
  41. package/registry.config.ts +0 -16
  42. package/tests/setup.ts +0 -6
  43. package/tests/testHelpers.tsx +0 -29
  44. package/towncrier.toml +0 -33
  45. package/tsconfig.json +0 -35
  46. package/vite.config.ts +0 -120
  47. package/vitest.config.ts +0 -32
  48. /package/{app → src/app}/config/index.test.ts +0 -0
  49. /package/{app → src/app}/config/server/content-migrations.server.test.ts +0 -0
  50. /package/{app → src/app}/config/server/content-migrations.server.ts +0 -0
  51. /package/{app → src/app}/config/server/migrations.server.ts +0 -0
  52. /package/{app → src/app}/config/server.server.test.ts +0 -0
  53. /package/{app → src/app}/config/types.ts +0 -0
  54. /package/{app → src/app}/i18n.ts +0 -0
  55. /package/{app → src/app}/okroute.test.tsx +0 -0
  56. /package/{app → src/app}/okroute.tsx +0 -0
  57. /package/{app → src/app}/reset-fetcher.test.tsx +0 -0
  58. /package/{app → src/app}/reset-fetcher.tsx +0 -0
@@ -18,7 +18,8 @@ export const streamTimeout = 5_000;
18
18
  // The Plone devtools, in development only (see `@plone/devtools/vite`).
19
19
  export const instrumentations =
20
20
  import.meta.env.DEV && import.meta.env.PLONE_DEVTOOLS
21
- ? [(await import('@plone/devtools/server')).serverInstrumentation]
21
+ ? // eslint-disable-next-line import/no-extraneous-dependencies -- development only, removed from production builds
22
+ [(await import('@plone/devtools/server')).serverInstrumentation]
22
23
  : [];
23
24
 
24
25
  export default async function handleRequest(
@@ -1,10 +1,49 @@
1
- import { afterEach, beforeEach, describe, expect, it } from 'vitest';
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import {
5
+ afterAll,
6
+ afterEach,
7
+ beforeAll,
8
+ beforeEach,
9
+ describe,
10
+ expect,
11
+ it,
12
+ vi,
13
+ } from 'vitest';
2
14
  import config from '@plone/registry';
3
15
  import { RouterContextProvider } from 'react-router';
4
16
  import { localeCookie } from '@plone/react-router';
17
+ import { ploneLocaleContext } from '@plone/react-router/context';
5
18
  import { getInstance, getLocale, i18nextMiddleware } from './i18next.server';
6
19
 
7
20
  describe('i18nextMiddleware', () => {
21
+ // In development, the middleware reads the locales that the registry
22
+ // generates in the app's `public/locales`, and the app is the working
23
+ // directory. The tests give it an app with a catalog of their own.
24
+ let appDir: string;
25
+
26
+ beforeAll(() => {
27
+ appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'aurora-i18n-'));
28
+ for (const [lng, save] of [
29
+ ['en', 'Save'],
30
+ ['de', 'Speichern'],
31
+ ]) {
32
+ const dir = path.join(appDir, 'public', 'locales', lng);
33
+ fs.mkdirSync(dir, { recursive: true });
34
+ fs.writeFileSync(
35
+ path.join(dir, 'common.json'),
36
+ JSON.stringify({ cmsui: { save } }),
37
+ );
38
+ }
39
+ vi.spyOn(process, 'cwd').mockReturnValue(appDir);
40
+ });
41
+
42
+ afterAll(() => {
43
+ vi.restoreAllMocks();
44
+ fs.rmSync(appDir, { recursive: true, force: true });
45
+ });
46
+
8
47
  let supportedLanguages: string[];
9
48
  let defaultLanguage: unknown;
10
49
 
@@ -45,6 +84,14 @@ describe('i18nextMiddleware', () => {
45
84
  expect(getInstance(context).t('cmsui.save')).toBe('Speichern');
46
85
  });
47
86
 
87
+ it('sets the locale in ploneLocaleContext for add-ons', async () => {
88
+ const context = await runMiddleware(
89
+ new Request('http://localhost:3000/?lng=de'),
90
+ );
91
+
92
+ expect(context.get(ploneLocaleContext)).toBe('de');
93
+ });
94
+
48
95
  it('reads the language from the locale cookie', async () => {
49
96
  const context = await runMiddleware(
50
97
  new Request('http://localhost:3000/', {
@@ -1,23 +1,25 @@
1
1
  import Backend from 'i18next-fs-backend/cjs';
2
+ import path from 'node:path';
2
3
  import { fileURLToPath } from 'node:url';
3
4
  import type { RouterContextProvider } from 'react-router';
4
5
  import { initReactI18next } from 'react-i18next';
5
6
  import { createI18nextMiddleware } from 'remix-i18next';
6
7
  import { getI18nOptions } from './i18n'; // your i18n configuration file
7
8
  import { localeCookie } from '@plone/react-router';
9
+ import { ploneLocaleContext } from '@plone/react-router/context';
8
10
 
9
- // The add-on locales are generated into `public/locales`, which the build copies
10
- // to `build/client/locales`. Resolve them relative to this module, not the
11
- // working directory: in development it is `app/i18next.server.ts`, in
12
- // production the server bundle `build/server/index.js`. If the server can't
13
- // load them, it renders the raw message keys, the client renders the
14
- // translations, and React discards the server-rendered DOM on hydration.
15
- const localesPath = fileURLToPath(
16
- new URL(
17
- import.meta.env.PROD ? '../client/locales/' : '../public/locales/',
18
- import.meta.url,
19
- ),
20
- );
11
+ // The add-on locales are generated into the app's `public/locales`, which the
12
+ // build copies to `build/client/locales`. In production, resolve them relative
13
+ // to the server bundle `build/server/index.js`, so the server finds them from
14
+ // any working directory. In development, this module is in `@plone/aurora`,
15
+ // and the app is the working directory. If the server can't load them, it
16
+ // renders the raw message keys, the client renders the translations, and React
17
+ // discards the server-rendered DOM on hydration.
18
+ function getLocalesPath() {
19
+ return import.meta.env.PROD
20
+ ? fileURLToPath(new URL('../client/locales/', import.meta.url))
21
+ : path.join(process.cwd(), 'public', 'locales') + path.sep;
22
+ }
21
23
 
22
24
  let i18next: createI18nextMiddleware.ReturnType | undefined;
23
25
 
@@ -39,7 +41,7 @@ function getI18next() {
39
41
  ...i18n,
40
42
  ns: i18n.defaultNS,
41
43
  backend: {
42
- loadPath: `${localesPath}{{lng}}/{{ns}}.json`,
44
+ loadPath: `${getLocalesPath()}{{lng}}/{{ns}}.json`,
43
45
  },
44
46
  },
45
47
  // The i18next plugins the middleware's instance uses.
@@ -50,10 +52,16 @@ function getI18next() {
50
52
  return i18next;
51
53
  }
52
54
 
55
+ // After detecting the locale, set it in `ploneLocaleContext`, so add-ons can
56
+ // read it without knowing how the app does i18n.
53
57
  export const i18nextMiddleware: createI18nextMiddleware.ReturnType[0] = (
54
58
  args,
55
59
  next,
56
- ) => getI18next()[0](args, next);
60
+ ) =>
61
+ getI18next()[0](args, () => {
62
+ args.context.set(ploneLocaleContext, getLocale(args.context));
63
+ return next();
64
+ });
57
65
 
58
66
  export const getLocale = (context: Readonly<RouterContextProvider>) =>
59
67
  getI18next()[1](context);
@@ -3,13 +3,11 @@ import config from '@plone/registry';
3
3
  import { RouterContextProvider } from 'react-router';
4
4
  import { jwtDecode } from 'jwt-decode';
5
5
  import { getAuthFromRequest } from '@plone/react-router';
6
- import PloneClient from '@plone/client';
7
6
  import {
8
7
  contentResourceMiddleware,
9
8
  fetchPloneContent,
10
9
  getAPIResourceWithAuth,
11
10
  getContentExpand,
12
- getPloneClientClass,
13
11
  isResourcePattern,
14
12
  installServerMiddleware,
15
13
  linkMiddleware,
@@ -140,72 +138,6 @@ describe('middleware', () => {
140
138
  });
141
139
  });
142
140
 
143
- describe('getPloneClientClass', () => {
144
- afterEach(() => {
145
- config.utilities.clientEndpoints = {};
146
- });
147
-
148
- it('returns the ploneClient utility when there are no clientEndpoints', () => {
149
- config.registerUtility({
150
- name: 'ploneClient',
151
- type: 'client',
152
- method: () => PloneClient,
153
- });
154
-
155
- expect(getPloneClientClass()).toBe(PloneClient);
156
- });
157
-
158
- it('adds the methods of every clientEndpoints utility', () => {
159
- config.registerUtility({
160
- name: 'ploneClient',
161
- type: 'client',
162
- method: () => PloneClient,
163
- });
164
- config.registerUtility({
165
- name: 'first-addon',
166
- type: 'clientEndpoints',
167
- method: () => ({
168
- getApiPath(this: PloneClient) {
169
- return this.config.apiPath;
170
- },
171
- }),
172
- });
173
- config.registerUtility({
174
- name: 'second-addon',
175
- type: 'clientEndpoints',
176
- method: () => ({ getAnswer: () => 42 }),
177
- });
178
-
179
- const cli = getPloneClientClass().initialize({
180
- apiPath: 'http://localhost:8080/Plone',
181
- }) as PloneClient & Record<string, () => unknown>;
182
-
183
- expect(cli).toBeInstanceOf(PloneClient);
184
- expect(cli.getApiPath()).toBe('http://localhost:8080/Plone');
185
- expect(cli.getAnswer()).toBe(42);
186
- expect(cli.getContent).toBeTypeOf('function');
187
- });
188
-
189
- it('extends a custom ploneClient utility', () => {
190
- class CustomClient extends PloneClient {}
191
- config.registerUtility({
192
- name: 'ploneClient',
193
- type: 'client',
194
- method: () => CustomClient,
195
- });
196
- config.registerUtility({
197
- name: 'addon',
198
- type: 'clientEndpoints',
199
- method: () => ({ getAnswer: () => 42 }),
200
- });
201
-
202
- const cli = getPloneClientClass().initialize({ apiPath: '' });
203
-
204
- expect(cli).toBeInstanceOf(CustomClient);
205
- expect(cli).toHaveProperty('getAnswer');
206
- });
207
- });
208
-
209
141
  describe('PloneClientMiddleware', () => {
210
142
  it('initializes the PloneClient and sets it in context', async () => {
211
143
  const request = new Request('http://example.com');
@@ -1,22 +1,35 @@
1
1
  import { jwtDecode } from 'jwt-decode';
2
- import { data, createContext, redirect } from 'react-router';
2
+ import { data, redirect, type MiddlewareFunction } from 'react-router';
3
3
  import { flattenToAppURL } from '@plone/helpers';
4
- import { clearAuthOnResponse, getAuthFromRequest } from '@plone/react-router';
4
+ import {
5
+ clearAuthOnResponse,
6
+ getAuthFromRequest,
7
+ getPloneClientClass,
8
+ } from '@plone/react-router';
9
+ import {
10
+ ploneClearAuthCookieContext,
11
+ ploneClientContext,
12
+ ploneContentContext,
13
+ ploneSiteContext,
14
+ ploneUserContext,
15
+ } from '@plone/react-router/context';
5
16
  import config from '@plone/registry';
6
17
  import type PloneClient from '@plone/client';
7
- import type { Route } from './+types/root';
8
18
  import installServer from './config/server.server';
9
19
  import { migrateContent } from './config/server/content-migrations.server';
10
20
 
11
- export const ploneClientContext = createContext<PloneClient>();
12
- export const ploneContentContext =
13
- createContext<Awaited<ReturnType<PloneClient['getContent']>>['data']>();
14
- export const ploneSiteContext =
15
- createContext<Awaited<ReturnType<PloneClient['getSite']>>['data']>();
16
- export const ploneUserContext = createContext<
17
- Awaited<ReturnType<PloneClient['getUser']>>['data'] | null
18
- >(null);
19
- export const ploneClearAuthCookieContext = createContext<boolean>(false);
21
+ // The request contexts and the client class live in `@plone/react-router`, so
22
+ // add-ons can import them without importing the app. They are re-exported
23
+ // here for add-ons that still import them from the app.
24
+ // TODO: remove the re-exports once no add-on imports them from here.
25
+ export {
26
+ ploneClientContext,
27
+ ploneContentContext,
28
+ ploneSiteContext,
29
+ ploneUserContext,
30
+ ploneClearAuthCookieContext,
31
+ getPloneClientClass,
32
+ };
20
33
 
21
34
  /**
22
35
  * Where the site root sends a visitor on a multilingual site: the default
@@ -68,27 +81,6 @@ function getAuthorizedResourceHeaders(
68
81
  return headers;
69
82
  }
70
83
 
71
- /**
72
- * Returns the `PloneClient` class registered as the `ploneClient` utility,
73
- * extended with the methods of every registered `clientEndpoints` utility.
74
- */
75
- export function getPloneClientClass() {
76
- const PloneClient = config
77
- .getUtility({
78
- name: 'ploneClient',
79
- type: 'client',
80
- })
81
- .method();
82
-
83
- const endpoints = config
84
- .getUtilities({ type: 'clientEndpoints' })
85
- .map((utility) => utility.method());
86
-
87
- return endpoints.length > 0
88
- ? PloneClient.extend(Object.assign({}, ...endpoints))
89
- : PloneClient;
90
- }
91
-
92
84
  /**
93
85
  * Whether a route pattern names a resource: one of its segments starts with
94
86
  * a single `@`, like `@search/*` or `@@contents/@delete/*`. Views use `@@`.
@@ -117,7 +109,7 @@ export function routeSkipsContent(pattern: string) {
117
109
  // HMR, which resets the flag and applies the new configuration.
118
110
  let serverConfigInstalled = false;
119
111
 
120
- export const installServerMiddleware: Route.MiddlewareFunction = async (
112
+ export const installServerMiddleware: MiddlewareFunction<Response> = async (
121
113
  { request, context },
122
114
  next,
123
115
  ) => {
@@ -126,7 +118,7 @@ export const installServerMiddleware: Route.MiddlewareFunction = async (
126
118
  serverConfigInstalled = true;
127
119
  };
128
120
 
129
- export const PloneClientMiddleware: Route.MiddlewareFunction = async (
121
+ export const PloneClientMiddleware: MiddlewareFunction<Response> = async (
130
122
  { request, context },
131
123
  next,
132
124
  ) => {
@@ -142,7 +134,7 @@ export const PloneClientMiddleware: Route.MiddlewareFunction = async (
142
134
  context.set(ploneClientContext, cli);
143
135
  };
144
136
 
145
- export const otherResources: Route.MiddlewareFunction = async (
137
+ export const otherResources: MiddlewareFunction<Response> = async (
146
138
  { request, params, context },
147
139
  next,
148
140
  ) => {
@@ -166,7 +158,7 @@ export const otherResources: Route.MiddlewareFunction = async (
166
158
  }
167
159
  };
168
160
 
169
- export const getAPIResourceWithAuth: Route.MiddlewareFunction = async (
161
+ export const getAPIResourceWithAuth: MiddlewareFunction<Response> = async (
170
162
  { request, params },
171
163
  next,
172
164
  ) => {
@@ -252,7 +244,7 @@ export function matchContentResource(path: string) {
252
244
  * resource. React Router can't match a route below a splat, so they are
253
245
  * handled here, before the content of the path is fetched.
254
246
  */
255
- export const contentResourceMiddleware: Route.MiddlewareFunction = async ({
247
+ export const contentResourceMiddleware: MiddlewareFunction<Response> = async ({
256
248
  request,
257
249
  params,
258
250
  }) => {
@@ -294,7 +286,7 @@ export function getContentExpand(path: string, authenticated: boolean) {
294
286
  return expand;
295
287
  }
296
288
 
297
- export const fetchPloneContent: Route.MiddlewareFunction = async (
289
+ export const fetchPloneContent: MiddlewareFunction<Response> = async (
298
290
  { request, params, context, pattern, url },
299
291
  next,
300
292
  ) => {
@@ -414,7 +406,7 @@ export const fetchPloneContent: Route.MiddlewareFunction = async (
414
406
  }
415
407
  };
416
408
 
417
- export const linkMiddleware: Route.MiddlewareFunction = async (
409
+ export const linkMiddleware: MiddlewareFunction<Response> = async (
418
410
  { context, pattern },
419
411
  next,
420
412
  ) => {
@@ -0,0 +1,124 @@
1
+ // The server-only part of the app's root route: its middleware and loader.
2
+ // The app's `root.tsx` re-exports them, and React Router removes them, and
3
+ // this module with them, from the client build.
4
+ import {
5
+ data,
6
+ type LoaderFunctionArgs,
7
+ type RouterContextProvider,
8
+ } from 'react-router';
9
+ import type { RootLoaderData } from '@plone/types';
10
+ import config from '@plone/registry';
11
+ import { getClearAuthCookieHeader } from '@plone/react-router';
12
+ import { i18nextMiddleware, getLocale } from './i18next.server';
13
+ import {
14
+ ploneClearAuthCookieContext,
15
+ fetchPloneContent,
16
+ getAPIResourceWithAuth,
17
+ contentResourceMiddleware,
18
+ installServerMiddleware,
19
+ PloneClientMiddleware,
20
+ otherResources,
21
+ ploneClientContext,
22
+ ploneContentContext,
23
+ ploneSiteContext,
24
+ ploneUserContext,
25
+ linkMiddleware,
26
+ } from './middleware.server';
27
+
28
+ export const middleware = [
29
+ // Install the configuration first: the i18next middleware reads the
30
+ // supported languages from it.
31
+ installServerMiddleware,
32
+ i18nextMiddleware,
33
+ PloneClientMiddleware,
34
+ otherResources,
35
+ getAPIResourceWithAuth,
36
+ contentResourceMiddleware,
37
+ fetchPloneContent,
38
+ linkMiddleware,
39
+ ];
40
+
41
+ export async function loader({
42
+ params,
43
+ request,
44
+ context,
45
+ }: LoaderFunctionArgs<RouterContextProvider>) {
46
+ const locale = getLocale(context);
47
+
48
+ const cli = context.get(ploneClientContext);
49
+ const content = context.get(ploneContentContext);
50
+ const site = context.get(ploneSiteContext);
51
+ const user = context.get(ploneUserContext);
52
+
53
+ const path = `/${params['*'] || ''}`;
54
+
55
+ const rootLoaderDataUtilities = config.getUtilities({
56
+ type: 'rootLoaderData',
57
+ });
58
+
59
+ const rootContentSubRequests = config.getUtilities({
60
+ type: 'rootContentSubRequest',
61
+ });
62
+
63
+ try {
64
+ for (const utility of rootContentSubRequests) {
65
+ await utility.method({
66
+ cli,
67
+ content,
68
+ request,
69
+ path,
70
+ params,
71
+ locale,
72
+ });
73
+ }
74
+
75
+ const rootLoaderDataUtilitiesData = await Promise.all([
76
+ ...rootLoaderDataUtilities.map((utility) =>
77
+ utility.method({
78
+ cli,
79
+ content,
80
+ request,
81
+ path,
82
+ params,
83
+ locale,
84
+ }),
85
+ ),
86
+ ]);
87
+
88
+ // Add-ons read the root route's data as `RootLoaderData`, so the loader
89
+ // must keep returning that shape.
90
+ const loaderData = {
91
+ content,
92
+ site,
93
+ locale,
94
+ isAuthenticated: user !== null,
95
+ // Each `rootLoaderData` utility returns a `{ status, data }` envelope
96
+ // (see `config/types.ts`). Merge each utility's `data` into the root
97
+ // loader data; utilities namespace their `data` to avoid clobbering.
98
+ // TODO: act on `status` (e.g. propagate a non-2xx to the response).
99
+ ...rootLoaderDataUtilitiesData
100
+ .filter((item) => item)
101
+ .reduce(
102
+ (acc, item) => ({
103
+ ...acc,
104
+ ...(item.data as Record<string, unknown>),
105
+ }),
106
+ {},
107
+ ),
108
+ } satisfies RootLoaderData;
109
+
110
+ return data(loaderData, {
111
+ headers: context.get(ploneClearAuthCookieContext)
112
+ ? {
113
+ 'Set-Cookie': await getClearAuthCookieHeader(),
114
+ }
115
+ : undefined,
116
+ });
117
+ } catch (error: any) {
118
+ throw data('Content Not Found', {
119
+ status: typeof error.status === 'number' ? error.status : 500,
120
+ });
121
+ }
122
+ }
123
+
124
+ export type RootLoader = typeof loader;
@@ -1,8 +1,9 @@
1
1
  import { expect, describe, it, vi, afterEach } from 'vitest';
2
2
  import { render, screen } from '@testing-library/react';
3
- import { createRoutesStub, RouterContextProvider } from 'react-router';
3
+ import { createRoutesStub, data, RouterContextProvider } from 'react-router';
4
4
  import config from '@plone/registry';
5
- import { Layout, ErrorBoundary, loader } from './root';
5
+ import { Layout, ErrorBoundary } from './root';
6
+ import { loader } from './root.server';
6
7
  import {
7
8
  ploneClientContext,
8
9
  ploneClearAuthCookieContext,
@@ -10,7 +11,7 @@ import {
10
11
  ploneSiteContext,
11
12
  } from './middleware.server';
12
13
  import { migrateContent } from './config/server/content-migrations.server';
13
- import { renderWithI18n } from '../tests/testHelpers';
14
+ import { renderWithI18n } from '../../tests/testHelpers';
14
15
 
15
16
  vi.mock('./i18next.server', () => ({
16
17
  i18nextMiddleware: vi.fn(),
@@ -163,10 +164,38 @@ describe('Layout', () => {
163
164
  });
164
165
 
165
166
  describe('ErrorBoundary', () => {
166
- it('should render the error message', async () => {
167
- const error = new Error('Test error');
168
- render(<ErrorBoundary error={error} params={{}} />);
169
- expect(screen.getByText('Test error')).toBeInTheDocument();
167
+ // The app re-exports it from its `root.tsx`, so React Router doesn't pass it
168
+ // the error as a prop: it has to read it from the route.
169
+ const renderRouteError = (thrown: unknown) => {
170
+ const Stub = createRoutesStub([
171
+ {
172
+ path: '/',
173
+ loader() {
174
+ throw thrown;
175
+ },
176
+ Component: () => null,
177
+ ErrorBoundary,
178
+ },
179
+ ]);
180
+ render(<Stub />);
181
+ };
182
+
183
+ it('renders the message of an error', async () => {
184
+ vi.spyOn(console, 'error').mockImplementation(() => {});
185
+ renderRouteError(new Error('Test error'));
186
+
187
+ expect(await screen.findByText('Test error')).toBeInTheDocument();
188
+ });
189
+
190
+ it('renders the status of an error response', async () => {
191
+ renderRouteError(data('Content Not Found', { status: 500 }));
192
+
193
+ expect(await screen.findByText('500')).toBeInTheDocument();
194
+ expect(
195
+ screen.getByText(
196
+ 'The server encountered an internal error. Did you start the backend?',
197
+ ),
198
+ ).toBeInTheDocument();
170
199
  });
171
200
  });
172
201
 
@@ -0,0 +1,101 @@
1
+ import { useEffect, type PropsWithChildren } from 'react';
2
+ import {
3
+ isRouteErrorResponse,
4
+ useRouteError,
5
+ useRouteLoaderData,
6
+ } from 'react-router';
7
+ import { useTranslation } from 'react-i18next';
8
+ import type { RootLoaderData } from '@plone/types';
9
+
10
+ // The client-safe part of the app's root route. Its middleware and loader are
11
+ // in `root.server.ts`.
12
+
13
+ export const handle = {
14
+ // In the handle export, we can add a i18n key with namespaces our route
15
+ // will need to load. This key can be a single string or an array of strings.
16
+ // TIP: In most cases, you should set this to your defaultNS from your i18n config
17
+ // or if you did not set one, set it to the i18next default namespace "translation"
18
+ i18n: 'common',
19
+ };
20
+
21
+ export function Layout({ children }: PropsWithChildren) {
22
+ // React Router doesn't pass the loader data to `Layout`, and it can be
23
+ // undefined in case of an error
24
+ const loaderData = useRouteLoaderData<RootLoaderData>('root');
25
+ const locale = loaderData?.locale || 'en';
26
+
27
+ // Sync the i18n instance's language to the locale detected by the loader,
28
+ // this way, when we do something to change the language, this locale will
29
+ // change and i18next will load the correct translation files
30
+ const { i18n } = useTranslation();
31
+ useEffect(() => {
32
+ if (i18n.language !== locale) i18n.changeLanguage(locale);
33
+ }, [locale, i18n]);
34
+
35
+ return children;
36
+ }
37
+
38
+ // ToDo: improve error page and error handling
39
+ // Inline styles, not Tailwind classes: Tailwind only scans the app and the
40
+ // add-ons, not this package, and a public theme may not use Tailwind at all.
41
+ export function ErrorBoundary() {
42
+ // React Router passes the error as a prop only to an `ErrorBoundary` that is
43
+ // declared in the route file. The app's `root.tsx` re-exports this one, so
44
+ // read the error from the route instead.
45
+ const error = useRouteError();
46
+ let message = 'Oops!';
47
+ let details = 'An unexpected error occurred.';
48
+ let stack: string | undefined;
49
+
50
+ if (isRouteErrorResponse(error)) {
51
+ switch (error.status) {
52
+ case 404:
53
+ message = '404';
54
+ details = 'The requested page could not be found.';
55
+ break;
56
+ case 401:
57
+ message = '401';
58
+ details = 'You are not authorized to view this page.';
59
+ break;
60
+ case 500:
61
+ message = '500';
62
+ details =
63
+ 'The server encountered an internal error. Did you start the backend?';
64
+ break;
65
+ default:
66
+ message = 'Error ' + error.status;
67
+ details = error.statusText || details;
68
+ break;
69
+ }
70
+ } else if (import.meta.env.DEV && error && error instanceof Error) {
71
+ details = error.message;
72
+ stack = error.stack;
73
+ }
74
+
75
+ return (
76
+ <html lang="en">
77
+ <head>
78
+ <meta charSet="utf-8" />
79
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
80
+ <meta name="mobile-web-app-capable" content="yes" />
81
+ </head>
82
+ <body>
83
+ <main
84
+ style={{
85
+ maxWidth: '80rem',
86
+ marginInline: 'auto',
87
+ padding: '4rem 1rem 1rem',
88
+ }}
89
+ >
90
+ <h1>{message}</h1>
91
+ <p>{details}</p>
92
+ {stack && (
93
+ <pre style={{ width: '100%', overflowX: 'auto', padding: '1rem' }}>
94
+ <code>{stack}</code>
95
+ </pre>
96
+ )}
97
+ </main>
98
+ </body>
99
+ </html>
100
+ );
101
+ }
package/.release-it.json DELETED
@@ -1,32 +0,0 @@
1
- {
2
- "plugins": {
3
- "../../packages/scripts/prepublish.js": {}
4
- },
5
- "hooks": {
6
- "after:bump": [
7
- "uvx towncrier build --draft --yes --version ${version} > .changelog.draft",
8
- "uvx towncrier build --yes --version ${version}"
9
- ],
10
- "after:release": [
11
- "rm .changelog.draft",
12
- "pnpm dist-tag add @plone/aurora@${version} latest"
13
- ]
14
- },
15
- "npm": {
16
- "publish": false
17
- },
18
- "git": {
19
- "commitArgs": ["--no-verify"],
20
- "changelog": "uvx towncrier build --draft --yes --version 0.0.0",
21
- "requireUpstream": false,
22
- "requireCleanWorkingDir": false,
23
- "commitMessage": "Releasing @plone/aurora ${version}",
24
- "tagName": "${version}",
25
- "tagAnnotation": "${version}"
26
- },
27
- "github": {
28
- "release": true,
29
- "releaseName": "${version}",
30
- "releaseNotes": "cat .changelog.draft"
31
- }
32
- }