@terpjs/react-core 0.27.0 → 0.29.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 (43) hide show
  1. package/README.md +31 -7
  2. package/package.json +4 -3
  3. package/src/Field.test.tsx +95 -1
  4. package/src/Field.tsx +70 -1
  5. package/src/LoginView.test.tsx +33 -0
  6. package/src/LoginView.tsx +36 -23
  7. package/src/Meter.test.tsx +304 -0
  8. package/src/Meter.tsx +159 -0
  9. package/src/QuietActions.test.tsx +118 -0
  10. package/src/QuietActions.tsx +75 -0
  11. package/src/UserMenu.test.tsx +23 -0
  12. package/src/UserMenu.tsx +9 -1
  13. package/src/admin/AccessAdmin.tsx +6 -2
  14. package/src/admin/AuditLogAdmin.tsx +1 -1
  15. package/src/admin/access.test.tsx +2 -1
  16. package/src/admin/admin.test.tsx +57 -5
  17. package/src/admin/module.tsx +9 -6
  18. package/src/bootstrap.test.tsx +1 -1
  19. package/src/bootstrap.tsx +2 -1
  20. package/src/dataview/DataView.test.tsx +99 -0
  21. package/src/dataview/DataViewPagination.tsx +2 -2
  22. package/src/dataview/DataViewToolbar.tsx +2 -2
  23. package/src/dataview/README.md +5 -3
  24. package/src/dataview/index.ts +1 -1
  25. package/src/dataview/internal.tsx +102 -21
  26. package/src/dataview/types.ts +11 -37
  27. package/src/errorMessages.test.tsx +21 -0
  28. package/src/errorMessages.tsx +33 -19
  29. package/src/index.ts +9 -3
  30. package/src/locale.test.tsx +164 -4
  31. package/src/locale.tsx +105 -10
  32. package/src/markers.test.ts +33 -11
  33. package/src/ssr.test.tsx +18 -0
  34. package/src/styles.test.ts +265 -14
  35. package/src/styles.ts +424 -49
  36. package/src/testing.test.tsx +162 -0
  37. package/src/testing.ts +84 -0
  38. package/src/tokens.guard.test.ts +11 -6
  39. package/src/ui/controlMessages.tsx +27 -14
  40. package/src/uiText.literals.test.ts +19 -6
  41. package/src/uiText.test.tsx +143 -2
  42. package/src/uiText.tsx +287 -15
  43. package/vitest.setup.ts +7 -20
@@ -199,7 +199,15 @@ export interface DataViewSearchScope {
199
199
  broadenedLabel: UiText;
200
200
  }
201
201
 
202
- /** Every user-facing string the DataView renders, overridable per instance. */
202
+ /**
203
+ * Every user-facing string the DataView renders, overridable per instance through its
204
+ * `strings` prop.
205
+ *
206
+ * The defaults are not here. Each key is read from the active locale's `TerpStrings`, under
207
+ * the same name with a `dataView` prefix (`searchPlaceholder` is `dataViewSearchPlaceholder`),
208
+ * so a DataView speaks whatever language the app's `LocaleProvider` does and a catalog that
209
+ * leaves one of them out is refused. A per-instance override wins over the locale.
210
+ */
203
211
  export interface DataViewStrings {
204
212
  searchPlaceholder: UiText;
205
213
  clearSearch: UiText;
@@ -211,7 +219,7 @@ export interface DataViewStrings {
211
219
  tableView: UiText;
212
220
  cardView: UiText;
213
221
  pageSize: UiText;
214
- resultsRange: UiText; // "{from}–{to} of {total} results"
222
+ resultsRange: UiText; // "{from}–{to} of {total} …": yours, used as given — the locale's has plural forms
215
223
  pageOf: UiText; // "Page {page} of {pages}"
216
224
  firstPage: UiText;
217
225
  previousPage: UiText;
@@ -220,7 +228,7 @@ export interface DataViewStrings {
220
228
  selectAllPage: UiText;
221
229
  selectRow: UiText;
222
230
  selected: UiText; // "{count} selected"
223
- selectAllResults: UiText; // "Select all {total} results"
231
+ selectAllResults: UiText; // "… {total} …": yours, used as given — the locale's has plural forms
224
232
  clearSelection: UiText;
225
233
  moreActions: UiText;
226
234
  actions: UiText;
@@ -234,40 +242,6 @@ export interface DataViewStrings {
234
242
  resizeColumn: UiText;
235
243
  }
236
244
 
237
- export const DEFAULT_DATA_VIEW_STRINGS: DataViewStrings = {
238
- searchPlaceholder: "Search…",
239
- clearSearch: "Clear search",
240
- clearFilters: "Clear filters",
241
- viewOptions: "View options",
242
- columns: "Columns",
243
- moveUp: "Move up",
244
- moveDown: "Move down",
245
- tableView: "Table view",
246
- cardView: "Card view",
247
- pageSize: "Rows per page",
248
- resultsRange: "{from}–{to} of {total} results",
249
- pageOf: "Page {page} of {pages}",
250
- firstPage: "First page",
251
- previousPage: "Previous page",
252
- nextPage: "Next page",
253
- lastPage: "Last page",
254
- selectAllPage: "Select all rows on this page",
255
- selectRow: "Select row",
256
- selected: "{count} selected",
257
- selectAllResults: "Select all {total} results",
258
- clearSelection: "Clear selection",
259
- moreActions: "More actions",
260
- actions: "Actions",
261
- openRow: "Open details: {label}",
262
- expandRow: "Expand row",
263
- collapseRow: "Collapse row",
264
- empty: "Nothing to show.",
265
- loading: "Loading…",
266
- refreshing: "Refreshing…",
267
- errorTitle: "Could not load data.",
268
- resizeColumn: "Resize column",
269
- };
270
-
271
245
  /** Tiny `{placeholder}` formatter for the countable strings above. */
272
246
  export function formatDataViewString(
273
247
  template: string,
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";
4
4
 
5
5
  import { ErrorState } from "./ErrorState";
6
6
  import { ErrorMessagesProvider, useErrorMessage } from "./errorMessages";
7
+ import { LOCALE_EN, LOCALE_NL, LocaleProvider } from "./locale";
7
8
  import { UiTextProvider } from "./uiText";
8
9
  import { ApiError } from "./unwrap";
9
10
 
@@ -57,6 +58,26 @@ describe("useErrorMessage", () => {
57
58
  });
58
59
  });
59
60
 
61
+ describe("useErrorMessage under a locale", () => {
62
+ it("words the platform's codes in the active locale, and an app's map still wins", () => {
63
+ // The built-in wording used to be an English map that was the context's default, and a
64
+ // plain string resolves as-is, so these two read in English under the Dutch catalog while
65
+ // that catalog was reported complete.
66
+ render(
67
+ <LocaleProvider locales={{ en: LOCALE_EN, nl: LOCALE_NL }} defaultLocale="nl">
68
+ <ErrorMessagesProvider messages={{ not_found: "Geen factuur met dit nummer." }}>
69
+ <Probe error={new ApiError("x", { code: "permission_denied", status: 403 })} />
70
+ <Probe error={new ApiError("x", { code: "not_found", status: 404 })} />
71
+ </ErrorMessagesProvider>
72
+ </LocaleProvider>,
73
+ );
74
+
75
+ const statuses = screen.getAllByRole("status");
76
+ expect(statuses[0]).toHaveTextContent("Je hebt geen toestemming om dit te doen.");
77
+ expect(statuses[1]).toHaveTextContent("Geen factuur met dit nummer.");
78
+ });
79
+ });
80
+
60
81
  describe("ErrorState with coded errors", () => {
61
82
  it("prefers the mapped message over the backend detail for known codes", () => {
62
83
  render(
@@ -1,8 +1,8 @@
1
1
  import { createContext, useCallback, useContext, useMemo } from "react";
2
2
  import type { ReactNode } from "react";
3
3
 
4
- import { useUiText } from "./uiText";
5
- import type { UiText } from "./uiText";
4
+ import { useStrings, useUiText } from "./uiText";
5
+ import type { TerpStrings, UiText } from "./uiText";
6
6
 
7
7
  /**
8
8
  * Client-owned messages for the platform's stable error codes.
@@ -19,22 +19,29 @@ import type { UiText } from "./uiText";
19
19
  export type ErrorMessages = Record<string, UiText>;
20
20
 
21
21
  /**
22
- * English defaults for the core `AppError` taxonomy. Apps override or extend
23
- * per code via {@link ErrorMessagesProvider} — including codes their own
24
- * backend modules add.
22
+ * The wording for the core `AppError` taxonomy, read from the active locale.
23
+ *
24
+ * These were an exported map of English strings, the context's default value, so a plain
25
+ * string resolved as-is and a `permission_denied` read "You do not have permission to do this."
26
+ * under every locale — while the Dutch catalog was reported complete, because the check walks
27
+ * `TerpStrings` and these were not in it. They are `errorCode*` keys of that table now, so a
28
+ * locale catalog translates them and a non-English one that leaves one out is refused.
25
29
  */
26
- export const DEFAULT_ERROR_MESSAGES: ErrorMessages = {
27
- bad_request: "The request could not be processed.",
28
- validation_failed: "Some fields are invalid. Check the form and try again.",
29
- invalid_token: "Your session is invalid. Sign in again.",
30
- authentication_required: "Sign in to continue.",
31
- permission_denied: "You do not have permission to do this.",
32
- not_found: "This item could not be found.",
33
- conflict: "This conflicts with the current state. Refresh and try again.",
34
- stale_data: "This item was changed by someone else. Refresh and try again.",
35
- };
30
+ function builtInErrorMessages(strings: TerpStrings): ErrorMessages {
31
+ return {
32
+ bad_request: strings.errorCodeBadRequest,
33
+ validation_failed: strings.errorCodeValidationFailed,
34
+ invalid_token: strings.errorCodeInvalidToken,
35
+ authentication_required: strings.errorCodeAuthenticationRequired,
36
+ permission_denied: strings.errorCodePermissionDenied,
37
+ not_found: strings.errorCodeNotFound,
38
+ conflict: strings.errorCodeConflict,
39
+ stale_data: strings.errorCodeStaleData,
40
+ };
41
+ }
36
42
 
37
- const ErrorMessagesContext = createContext<ErrorMessages>(DEFAULT_ERROR_MESSAGES);
43
+ /** The app's own map only; the built-in wording is read from the locale at every use. */
44
+ const ErrorMessagesContext = createContext<ErrorMessages>({});
38
45
 
39
46
  export interface ErrorMessagesProviderProps {
40
47
  /** Per-code overrides and additions, merged over any outer provider's map. */
@@ -44,8 +51,9 @@ export interface ErrorMessagesProviderProps {
44
51
 
45
52
  /**
46
53
  * Override or extend the code→message map for a subtree. Wrap the app once to
47
- * localise the built-in codes and register module-specific ones; nests, so a
48
- * module can add its own codes without touching the app shell.
54
+ * register module-specific codes, or to reword a built-in one — its translated
55
+ * wording already comes from the active locale; nests, so a module can add its
56
+ * own codes without touching the app shell.
49
57
  */
50
58
  export function ErrorMessagesProvider({ messages, children }: ErrorMessagesProviderProps) {
51
59
  const parent = useContext(ErrorMessagesContext);
@@ -60,8 +68,14 @@ export function ErrorMessagesProvider({ messages, children }: ErrorMessagesProvi
60
68
  * property, as carried by `ApiError` thrown from `unwrap`.
61
69
  */
62
70
  export function useErrorMessage(): (error: unknown) => string | null {
63
- const messages = useContext(ErrorMessagesContext);
71
+ const appMessages = useContext(ErrorMessagesContext);
72
+ const strings = useStrings();
64
73
  const resolve = useUiText();
74
+ // The app's map over the built-in wording, so an app still overrides a platform code.
75
+ const messages = useMemo(
76
+ () => ({ ...builtInErrorMessages(strings), ...appMessages }),
77
+ [strings, appMessages],
78
+ );
65
79
  return useCallback(
66
80
  (error: unknown) => {
67
81
  if (error === null || typeof error !== "object") {
package/src/index.ts CHANGED
@@ -91,6 +91,7 @@ export {
91
91
  UiTextProvider,
92
92
  Trans,
93
93
  useStrings,
94
+ usePlural,
94
95
  useUiText,
95
96
  resolveUiText,
96
97
  resolveUiTextNode,
@@ -100,6 +101,7 @@ export type {
100
101
  UiText,
101
102
  UiTextNode,
102
103
  ResolveUiText,
104
+ PluralText,
103
105
  TerpStrings,
104
106
  TransProps,
105
107
  UiTextProviderProps,
@@ -108,7 +110,7 @@ export { EmptyState } from "./EmptyState";
108
110
  export type { EmptyStateProps } from "./EmptyState";
109
111
  export { ErrorState, describeError } from "./ErrorState";
110
112
  export type { ErrorStateProps } from "./ErrorState";
111
- export { ErrorMessagesProvider, useErrorMessage, DEFAULT_ERROR_MESSAGES } from "./errorMessages";
113
+ export { ErrorMessagesProvider, useErrorMessage } from "./errorMessages";
112
114
  export type { ErrorMessages, ErrorMessagesProviderProps } from "./errorMessages";
113
115
  export { ConfirmDialog } from "./ConfirmDialog";
114
116
  export { Disclosure } from "./Disclosure";
@@ -175,8 +177,12 @@ export type {
175
177
  CodeProps,
176
178
  LinkProps,
177
179
  } from "./typography";
178
- export { Field } from "./Field";
179
- export type { FieldProps } from "./Field";
180
+ export { Field, FieldRow } from "./Field";
181
+ export { QuietActions } from "./QuietActions";
182
+ export { Meter } from "./Meter";
183
+ export type { FieldProps, FieldRowProps } from "./Field";
184
+ export type { QuietActionsProps } from "./QuietActions";
185
+ export type { MeterProps } from "./Meter";
180
186
  export { Stack, Grid, Divider, DetailList, DetailListGroup } from "./layout";
181
187
  export type {
182
188
  StackProps,
@@ -10,11 +10,12 @@ import {
10
10
  LocaleProvider,
11
11
  defineAppLocales,
12
12
  } from "./locale";
13
- import { DEFAULT_STRINGS, Trans, useStrings } from "./uiText";
13
+ import { DEFAULT_STRINGS, Trans, usePlural, useStrings } from "./uiText";
14
14
 
15
15
  afterEach(() => {
16
16
  cleanup();
17
17
  window.localStorage.clear();
18
+ document.documentElement.removeAttribute("lang");
18
19
  });
19
20
 
20
21
  function SignOutLabel() {
@@ -23,6 +24,22 @@ function SignOutLabel() {
23
24
 
24
25
  const NL = LOCALE_NL;
25
26
 
27
+ /**
28
+ * A complete framework catalog for *code* whose every value names its key: a plain string for
29
+ * a plain key, and a count-bearing key in exactly the plural forms *code* uses.
30
+ */
31
+ function completeCatalog(code: string, keys: readonly string[] = Object.keys(DEFAULT_STRINGS)) {
32
+ const categories = new Intl.PluralRules(code).resolvedOptions().pluralCategories;
33
+ return Object.fromEntries(
34
+ keys.map((key) => [
35
+ key,
36
+ typeof DEFAULT_STRINGS[key as keyof typeof DEFAULT_STRINGS] === "string"
37
+ ? `${code}:${key}`
38
+ : Object.fromEntries(categories.map((category) => [category, `${code}:${key}:${category}`])),
39
+ ]),
40
+ );
41
+ }
42
+
26
43
  describe("LocaleProvider + LanguageSwitcher", () => {
27
44
  it("feeds the active catalog's overrides through the UiText seam", () => {
28
45
  render(
@@ -251,9 +268,7 @@ describe("LocaleProvider + LanguageSwitcher", () => {
251
268
  ),
252
269
  ).toThrow(/missing .* framework string translation/);
253
270
 
254
- const germanStrings = Object.fromEntries(
255
- Object.keys(DEFAULT_STRINGS).map((key) => [key, `de:${key}`]),
256
- );
271
+ const germanStrings = completeCatalog("de");
257
272
  expect(
258
273
  defineAppLocales(
259
274
  {
@@ -265,6 +280,39 @@ describe("LocaleProvider + LanguageSwitcher", () => {
265
280
  ).toEqual({ greeting: "Hallo" });
266
281
  });
267
282
 
283
+ it("keeps <html lang> on the active locale, from mount and across a switch", () => {
284
+ // A value neither locale has, so the assertion can only pass if the provider wrote it:
285
+ // starting from "en" would let an effect that never ran pass the English half.
286
+ document.documentElement.lang = "x-stale";
287
+ render(
288
+ <LocaleProvider locales={{ en: LOCALE_EN, nl: NL }} defaultLocale="nl">
289
+ <LanguageSwitcher />
290
+ </LocaleProvider>,
291
+ );
292
+ expect(document.documentElement.lang).toBe("nl");
293
+
294
+ fireEvent.click(screen.getByRole("button", { name: "Taal" }));
295
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "English" }));
296
+ expect(document.documentElement.lang).toBe("en");
297
+ });
298
+
299
+ it("refuses a catalog that translates the shell but not DataView", () => {
300
+ // The upgrade path, pinned: a catalog complete against the key set before DataView's
301
+ // strings joined it. Refused, and by name, because the alternative is the defect itself —
302
+ // every table in the app back in English under a locale that claims to be complete.
303
+ const shellOnly = completeCatalog(
304
+ "de",
305
+ Object.keys(DEFAULT_STRINGS).filter((key) => !key.startsWith("dataView")),
306
+ );
307
+ expect(() =>
308
+ render(
309
+ <LocaleProvider locales={{ en: LOCALE_EN, de: { strings: shellOnly } }}>
310
+ <span />
311
+ </LocaleProvider>,
312
+ ),
313
+ ).toThrow(/missing .* framework string translation.*dataViewSearchPlaceholder/);
314
+ });
315
+
268
316
  it("always renders the descriptor fallback in the source locale", () => {
269
317
  render(
270
318
  <LocaleProvider
@@ -278,7 +326,119 @@ describe("LocaleProvider + LanguageSwitcher", () => {
278
326
  });
279
327
  });
280
328
 
329
+ describe("count-bearing framework strings", () => {
330
+ // The check at render is structural: which categories a language uses comes from the
331
+ // runtime's ICU data, which differs between browsers, so a check against it would pass a
332
+ // catalog in one browser and blank the app in another. The shipped catalogs are held to
333
+ // their languages' categories below, by tests that run where the ICU is fixed.
334
+ function refuse(code: string, key: string, translated: unknown): () => void {
335
+ return () =>
336
+ render(
337
+ <LocaleProvider
338
+ locales={{ en: LOCALE_EN, [code]: { strings: { ...completeCatalog(code), [key]: translated } } }}
339
+ >
340
+ <span />
341
+ </LocaleProvider>,
342
+ );
343
+ }
344
+
345
+ function Range({ count }: { count: number }) {
346
+ const plural = usePlural();
347
+ return <p>{plural(useStrings().dataViewResultsRange, count)}</p>;
348
+ }
349
+
350
+ it("refuses a single string where the key takes a form per category", () => {
351
+ expect(refuse("nl", "dataViewResultsRange", "{from}–{to} van {total} resultaten")).toThrow(
352
+ /Locale "nl" framework string "dataViewResultsRange" counts something, so it takes one form per plural category/,
353
+ );
354
+ });
355
+
356
+ it("refuses a catalog with no other form, or an empty form", () => {
357
+ expect(refuse("nl", "accessUnexplainedRoutes", { one: "{count} actie" })).toThrow(
358
+ /"accessUnexplainedRoutes" has no "other" form, which every language uses/,
359
+ );
360
+ expect(refuse("nl", "accessUnexplainedRoutes", { one: " ", other: "{count} acties" })).toThrow(
361
+ /"accessUnexplainedRoutes" has no "one" form/,
362
+ );
363
+ });
364
+
365
+ it("refuses a form named by something that is not a plural category", () => {
366
+ expect(
367
+ refuse("nl", "dataViewSelectAllResults", { one: "a", plural: "b", other: "c" }),
368
+ ).toThrow(/"dataViewSelectAllResults" has a "plural" form, which is not a plural category/);
369
+ });
370
+
371
+ it("accepts a form the runtime's plural data does not select, and answers a missing one with other", () => {
372
+ // French is one/other on some engines and one/many/other on newer ones: a catalog written
373
+ // for either must work on both, so a stray category is harmless and a missing one falls
374
+ // back. Here: Polish four is "few", which the catalog does not have.
375
+ render(
376
+ <LocaleProvider
377
+ locales={{
378
+ en: LOCALE_EN,
379
+ pl: {
380
+ strings: {
381
+ ...completeCatalog("pl"),
382
+ dataViewResultsRange: { one: "jeden", zero: "zero", other: "inne" },
383
+ },
384
+ },
385
+ }}
386
+ defaultLocale="pl"
387
+ >
388
+ <Range count={4} />
389
+ </LocaleProvider>,
390
+ );
391
+ expect(screen.getByText("inne")).toBeInTheDocument();
392
+ });
393
+
394
+ it("refuses a locale code that is not a language tag, before anything renders a count", () => {
395
+ // `Intl.PluralRules` throws on `en_US`, so without this the first DataView on the page
396
+ // would fail with a RangeError instead of the app being told what to write.
397
+ expect(() =>
398
+ render(
399
+ <LocaleProvider locales={{ en_US: LOCALE_EN }}>
400
+ <span />
401
+ </LocaleProvider>,
402
+ ),
403
+ ).toThrow(/Locale "en_US" is not a language tag \(BCP 47: "en-US", not "en_US"\)/);
404
+ });
405
+
406
+ it("chooses the form by the active locale's rules, not English's", () => {
407
+ // Four is "few" in Polish and "other" in English, so this fails if LocaleProvider stops
408
+ // handing its locale to the UiText seam. Dutch could not show it: for every integer, Dutch
409
+ // and English choose the same form.
410
+ render(
411
+ <LocaleProvider
412
+ locales={{ en: LOCALE_EN, pl: { strings: completeCatalog("pl") } }}
413
+ defaultLocale="pl"
414
+ >
415
+ <Range count={4} />
416
+ </LocaleProvider>,
417
+ );
418
+ expect(screen.getByText("pl:dataViewResultsRange:few")).toBeInTheDocument();
419
+ });
420
+ });
421
+
281
422
  describe("LOCALE_NL", () => {
423
+ it("writes each count-bearing string in exactly the plural forms its language uses", () => {
424
+ // The per-language half of the plural check, run where the ICU data is fixed rather than
425
+ // in whatever browser renders the catalog. English is the defaults; Dutch is this catalog.
426
+ const counted = Object.keys(DEFAULT_STRINGS).filter(
427
+ (key) => typeof DEFAULT_STRINGS[key as keyof typeof DEFAULT_STRINGS] !== "string",
428
+ );
429
+ expect(counted.length).toBeGreaterThan(0);
430
+ for (const [code, table] of [
431
+ ["en", DEFAULT_STRINGS],
432
+ ["nl", LOCALE_NL.strings ?? {}],
433
+ ] as const) {
434
+ const categories = [...new Intl.PluralRules(code).resolvedOptions().pluralCategories].sort();
435
+ for (const key of counted) {
436
+ const forms = (table as Record<string, unknown>)[key] as Record<string, string>;
437
+ expect(Object.keys(forms).sort(), `${code} ${key}`).toEqual(categories);
438
+ }
439
+ }
440
+ });
441
+
282
442
  it("translates every framework string (completeness drift-guard)", () => {
283
443
  // A new TerpStrings key without a Dutch translation fails here, so the
284
444
  // bundled catalog can never silently fall back to English for new chrome.
package/src/locale.tsx CHANGED
@@ -1,10 +1,10 @@
1
- import { createContext, useCallback, useContext, useMemo, useState } from "react";
1
+ import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
2
2
  import type { ReactNode } from "react";
3
3
  import type { UiText } from "@terpjs/contract";
4
4
 
5
5
  import { Icon } from "./icons";
6
6
  import { Menu, MenuItem } from "./ui/Menu";
7
- import { DEFAULT_STRINGS, UiTextProvider, useStrings } from "./uiText";
7
+ import { assertPluralShape, DEFAULT_STRINGS, UiTextProvider, useStrings } from "./uiText";
8
8
  import type { TerpStrings } from "./uiText";
9
9
 
10
10
  /**
@@ -34,6 +34,25 @@ function isRecord(value: unknown): value is Record<string, unknown> {
34
34
  return typeof value === "object" && value !== null && !Array.isArray(value);
35
35
  }
36
36
 
37
+ /**
38
+ * Refuse a locale code the runtime cannot read as a language tag.
39
+ *
40
+ * A code chooses a plural form through `Intl.PluralRules`, which throws on a code that is not
41
+ * a BCP 47 tag — `en_US` rather than `en-US` — and it is written to `<html lang>`, which needs
42
+ * one too. Refused here, with the spelling to use, rather than as a `RangeError` the first
43
+ * time a page renders a count.
44
+ */
45
+ function assertLanguageTag(code: string): void {
46
+ try {
47
+ new Intl.PluralRules(code);
48
+ } catch {
49
+ throw new Error(
50
+ `Locale "${code}" is not a language tag (BCP 47: "en-US", not "en_US"). Its plural ` +
51
+ "rules and <html lang> both need one.",
52
+ );
53
+ }
54
+ }
55
+
37
56
  function assertLocaleCatalogs(
38
57
  locales: unknown,
39
58
  sourceLocale?: string,
@@ -51,6 +70,7 @@ function assertLocaleCatalogs(
51
70
  if (code.trim() === "" || !isRecord(value)) {
52
71
  throw new Error("Locale entries must be non-empty codes mapped to catalog objects.");
53
72
  }
73
+ assertLanguageTag(code);
54
74
  if (
55
75
  value.label !== undefined &&
56
76
  (typeof value.label !== "string" || value.label.trim() === "")
@@ -64,6 +84,10 @@ function assertLocaleCatalogs(
64
84
  if (!Object.hasOwn(DEFAULT_STRINGS, key)) {
65
85
  throw new Error(`Locale "${code}" has unknown framework string "${key}".`);
66
86
  }
87
+ if (typeof DEFAULT_STRINGS[key as keyof TerpStrings] !== "string") {
88
+ assertPluralShape(`Locale "${code}"`, key, translated);
89
+ continue;
90
+ }
67
91
  if (typeof translated !== "string" || translated.trim() === "") {
68
92
  throw new Error(`Locale "${code}" has an empty or invalid framework string "${key}".`);
69
93
  }
@@ -98,10 +122,10 @@ function assertLocaleCatalogs(
98
122
  function assertFrameworkStringsComplete(locales: Record<string, LocaleCatalog>): void {
99
123
  for (const [code, catalog] of Object.entries(locales)) {
100
124
  if (code.split("-")[0].toLowerCase() === "en") continue;
125
+ // Present is enough: every value that is present was already held to its shape, a plain
126
+ // string or its locale's plural forms, when the catalogs were checked.
101
127
  const missing = Object.keys(DEFAULT_STRINGS).filter(
102
- (key) =>
103
- typeof catalog.strings?.[key as keyof TerpStrings] !== "string" ||
104
- catalog.strings[key as keyof TerpStrings]?.trim() === "",
128
+ (key) => catalog.strings?.[key as keyof TerpStrings] === undefined,
105
129
  );
106
130
  if (missing.length > 0) {
107
131
  throw new Error(
@@ -154,9 +178,12 @@ export function defineAppLocales(
154
178
  export const LOCALE_EN: LocaleCatalog = { label: "English" };
155
179
 
156
180
  /**
157
- * The built-in Dutch catalog: a complete translation of every framework string,
158
- * so `locales: { en: LOCALE_EN, nl: LOCALE_NL }` localises the whole chrome out
159
- * of the box (a completeness test pins it to the `TerpStrings` key set).
181
+ * The built-in Dutch catalog: a translation of every `TerpStrings` key, so
182
+ * `locales: { en: LOCALE_EN, nl: LOCALE_NL }` translates every string react-core
183
+ * reads from that table — the shell, the packaged admin area and its sidebar
184
+ * entry, every `DataView`'s toolbar and footer, and the wording for the platform's
185
+ * own error codes — with no catalog work in the app (a completeness test pins it to
186
+ * the `TerpStrings` key set).
160
187
  */
161
188
  export const LOCALE_NL: LocaleCatalog = {
162
189
  label: "Nederlands",
@@ -237,7 +264,10 @@ export const LOCALE_NL: LocaleCatalog = {
237
264
  accessAddsNothing: "Niets extra ten opzichte van de tier eronder",
238
265
  accessNeverAssignable: "Nooit per module toe te kennen",
239
266
  accessNotAssignable: "Niet per module toe te kennen",
240
- accessUnexplainedRoutes: "{count} actie(s) in deze module hebben nog geen omschrijving",
267
+ accessUnexplainedRoutes: {
268
+ one: "{count} actie in deze module heeft nog geen omschrijving",
269
+ other: "{count} acties in deze module hebben nog geen omschrijving",
270
+ },
241
271
  accessDeclaredOnly:
242
272
  "Dit is wat de applicatie vastlegt. Het laat niet zien wie welke rol heeft — open een persoon om dat te zien.",
243
273
  moduleAccessTitle: "Toegang per module",
@@ -294,8 +324,57 @@ export const LOCALE_NL: LocaleCatalog = {
294
324
  targetColumn: "Doel",
295
325
  whenColumn: "Wanneer",
296
326
  details: "Details",
327
+ requestLabel: "Verzoek",
297
328
  saved: "Opgeslagen",
298
329
  requestFailed: "Het verzoek is mislukt. Probeer opnieuw.",
330
+ dataViewSearchPlaceholder: "Zoeken…",
331
+ dataViewClearSearch: "Zoekopdracht wissen",
332
+ dataViewClearFilters: "Filters wissen",
333
+ dataViewViewOptions: "Weergaveopties",
334
+ dataViewColumns: "Kolommen",
335
+ dataViewMoveUp: "Omhoog verplaatsen",
336
+ dataViewMoveDown: "Omlaag verplaatsen",
337
+ dataViewTableView: "Tabelweergave",
338
+ dataViewCardView: "Kaartweergave",
339
+ dataViewPageSize: "Rijen per pagina",
340
+ dataViewResultsRange: {
341
+ one: "{from}–{to} van {total} resultaat",
342
+ other: "{from}–{to} van {total} resultaten",
343
+ },
344
+ dataViewPageOf: "Pagina {page} van {pages}",
345
+ dataViewFirstPage: "Eerste pagina",
346
+ dataViewPreviousPage: "Vorige pagina",
347
+ dataViewNextPage: "Volgende pagina",
348
+ dataViewLastPage: "Laatste pagina",
349
+ dataViewSelectAllPage: "Alle rijen op deze pagina selecteren",
350
+ dataViewSelectRow: "Rij selecteren",
351
+ dataViewSelected: "{count} geselecteerd",
352
+ dataViewSelectAllResults: {
353
+ one: "{total} resultaat selecteren",
354
+ other: "Alle {total} resultaten selecteren",
355
+ },
356
+ dataViewClearSelection: "Selectie wissen",
357
+ dataViewMoreActions: "Meer acties",
358
+ dataViewActions: "Acties",
359
+ dataViewOpenRow: "Details openen: {label}",
360
+ dataViewExpandRow: "Rij uitklappen",
361
+ dataViewCollapseRow: "Rij inklappen",
362
+ dataViewEmpty: "Niets om te tonen.",
363
+ dataViewLoading: "Laden…",
364
+ dataViewRefreshing: "Bijwerken…",
365
+ dataViewErrorTitle: "De gegevens konden niet worden geladen.",
366
+ dataViewResizeColumn: "Kolombreedte aanpassen",
367
+ errorCodeBadRequest: "Het verzoek kon niet worden verwerkt.",
368
+ errorCodeValidationFailed:
369
+ "Sommige velden zijn ongeldig. Controleer het formulier en probeer het opnieuw.",
370
+ errorCodeInvalidToken: "Je sessie is ongeldig. Log opnieuw in.",
371
+ errorCodeAuthenticationRequired: "Log in om verder te gaan.",
372
+ errorCodePermissionDenied: "Je hebt geen toestemming om dit te doen.",
373
+ errorCodeNotFound: "Dit item kon niet worden gevonden.",
374
+ errorCodeConflict:
375
+ "Dit botst met de huidige stand van zaken. Vernieuw de pagina en probeer het opnieuw.",
376
+ errorCodeStaleData:
377
+ "Iemand anders heeft dit item intussen gewijzigd. Vernieuw de pagina en probeer het opnieuw.",
299
378
  },
300
379
  };
301
380
 
@@ -326,6 +405,7 @@ export interface LocaleProviderProps {
326
405
  * the choice in `localStorage`, and feeds the active catalog's string overrides to the
327
406
  * `UiText` context — so every react-core component (and every `UiText` prop) follows the
328
407
  * switch with no per-component wiring. Adding a language to an app is one catalog entry.
408
+ * It also keeps `<html lang>` on the active locale, from mount and across every switch.
329
409
  */
330
410
  export function LocaleProvider({
331
411
  locales,
@@ -351,6 +431,17 @@ export function LocaleProvider({
351
431
  });
352
432
  const activeLocale = codes.includes(locale) ? locale : fallback;
353
433
 
434
+ // The document says which language it is in, and it has to be the language on screen.
435
+ // `index.html` can only declare the default; a reader who picked another one, or a stored
436
+ // choice from an earlier visit, would otherwise have a Dutch interface announced to a screen
437
+ // reader as English and read aloud with English pronunciation throughout (WCAG 3.1.1). An
438
+ // effect rather than a write during render, because an effect never runs on the server:
439
+ // there is no `document` there, and `ssr.test.tsx` renders this provider without one to hold
440
+ // that.
441
+ useEffect(() => {
442
+ document.documentElement.lang = activeLocale;
443
+ }, [activeLocale]);
444
+
354
445
  const setLocale = useCallback(
355
446
  (next: string) => {
356
447
  if (!codes.includes(next)) {
@@ -408,7 +499,11 @@ export function LocaleProvider({
408
499
 
409
500
  return (
410
501
  <LocaleContext.Provider value={value}>
411
- <UiTextProvider strings={locales[activeLocale]?.strings} resolveText={resolveText}>
502
+ <UiTextProvider
503
+ strings={locales[activeLocale]?.strings}
504
+ resolveText={resolveText}
505
+ locale={activeLocale}
506
+ >
412
507
  {children}
413
508
  </UiTextProvider>
414
509
  </LocaleContext.Provider>