@terpjs/react-core 0.28.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.
package/README.md CHANGED
@@ -56,7 +56,7 @@ also carries JSDoc, so your editor shows the same guidance inline. **Never deep-
56
56
  | `useSso`, `parseSsoCallback`, `fetchSsoAuthorizationUrl`, `completeSsoCallback` | The SSO login seam (ADR 0058): `useSso().begin(provider)` opens an OIDC flow; `TerpProvider` completes the `/auth/callback/{provider}` redirect landing into a normal session on boot. `renderTerpApp({ ssoProviders })` wires the buttons in one line. |
57
57
  | `RequireAuth` | Renders children only with a session; pairs with the router so the app mounts only when signed in. |
58
58
  | `ThemeProvider`, `ThemeToggle`, `useTheme` | Theming over the shipped palettes — `light`, `dark`, `midnight`, `twilight`, `contrast` — plus `system` to follow the OS preference. Applies `data-theme` on `<html>` (the token stylesheet carries every palette) and persists the choice. `defaultTheme` is how an app ships on a named theme — declare it in `layout-contract.json` so a tool can read and rewrite it, or pass the bootstrap option; both is refused. `renderTerpApp` mounts it for every app; the shell header uses an icon-only, token-themed `variant="inline"` menu. |
59
- | `LocaleProvider`, `defineAppLocales`, `LanguageSwitcher`, `useLocale`, `LOCALE_EN`, `LOCALE_NL` | The language seam over `UiTextProvider`: `defineAppLocales(i18n, frameworkCatalogs)` validates and merges checked-in app messages with framework chrome, the active locale persists, and the shell offers a picker. Pass `sourceLocale` with `locales`; missing/empty target messages, undocumented source copies, invalid locale selection and a non-English locale without a complete framework-string catalog throw rather than silently falling back. `<html lang>` follows the active locale from mount and across every switch. |
59
+ | `LocaleProvider`, `defineAppLocales`, `LanguageSwitcher`, `useLocale`, `LOCALE_EN`, `LOCALE_NL` | The language seam over `UiTextProvider`: `defineAppLocales(i18n, frameworkCatalogs)` validates and merges checked-in app messages with framework chrome, the active locale persists, and the shell offers a picker. Pass `sourceLocale` with `locales`; missing/empty target messages, undocumented source copies, invalid locale selection and a non-English locale without a complete framework-string catalog throw rather than silently falling back. A framework string that counts something (`dataViewResultsRange`, `dataViewSelectAllResults`, `accessUnexplainedRoutes`) is a `PluralText`: one form per plural category, chosen by the count under the active locale's `Intl.PluralRules`, and a catalog must supply exactly the categories its locale uses (`one` and `other` for Dutch; `one`, `few`, `many` and `other` for Polish). `<html lang>` follows the active locale from mount and across every switch. |
60
60
  | `UserMenu`, `userInitials` | The signed-in user's menu, pinned by `buildAppRouter` to the bottom of the sidebar: an initials avatar trigger opening the identity block, **Settings** (the built-in profile page) and sign-out. Collapses to the avatar in the icon rail. |
61
61
  | `ProfileView` | The built-in profile / settings page (`/profile`): the server-validated identity, theme + language preferences, and sign-out. |
62
62
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terpjs/react-core",
3
- "version": "0.28.0",
3
+ "version": "0.29.0",
4
4
  "type": "module",
5
5
  "description": "Terp React stack core — typed @terpjs/contract client provider, auth session, capability gates, TanStack Router adapter, app shell, page archetypes, DataView and token-styled UI primitives. First frontend stack; see README.md for the component catalog.",
6
6
  "exports": {
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "dependencies": {
17
17
  "@tanstack/react-router": "^1.170.38",
18
- "@terpjs/contract": "^0.28.0"
18
+ "@terpjs/contract": "^0.29.0"
19
19
  },
20
20
  "peerDependencies": {
21
21
  "react": "^19.0.0",
@@ -9,7 +9,7 @@ import { Page } from "../Page";
9
9
  import { Stack } from "../layout";
10
10
  import { TileGroup } from "../ui/TileGroup";
11
11
  import { useTerpClient } from "../TerpProvider";
12
- import { useStrings } from "../uiText";
12
+ import { usePlural, useStrings } from "../uiText";
13
13
  import type { TerpStrings } from "../uiText";
14
14
  import { unwrap } from "../unwrap";
15
15
 
@@ -19,6 +19,7 @@ import type { AccessModel, ModuleRow } from "./accessModel";
19
19
  import { tilesFor } from "./accessTiles";
20
20
 
21
21
  function ModuleCard({ row, strings }: { row: ModuleRow; strings: TerpStrings }) {
22
+ const plural = usePlural();
22
23
  return (
23
24
  <Card key={row.name}>
24
25
  <Stack gap={2}>
@@ -41,7 +42,10 @@ function ModuleCard({ row, strings }: { row: ModuleRow; strings: TerpStrings })
41
42
  )}
42
43
  {row.unexplainedRoutes > 0 && (
43
44
  <Alert tone="warning">
44
- {strings.accessUnexplainedRoutes.replace("{count}", String(row.unexplainedRoutes))}
45
+ {plural(strings.accessUnexplainedRoutes, row.unexplainedRoutes).replace(
46
+ "{count}",
47
+ String(row.unexplainedRoutes),
48
+ )}
45
49
  </Alert>
46
50
  )}
47
51
  <span data-terp="tile-note">{strings.accessAdds}</span>
@@ -441,7 +441,8 @@ describe("the access screen", () => {
441
441
  renderAt("/admin/access");
442
442
  await waitFor(() =>
443
443
  expect(
444
- screen.getByText("1 action(s) in this module have no description yet"),
444
+ // One route, so the singular: the sentence used to say "1 action(s) ... have".
445
+ screen.getByText("1 action in this module has no description yet"),
445
446
  ).toBeInTheDocument(),
446
447
  );
447
448
  });
@@ -886,7 +886,7 @@ describe("the packaged admin area", () => {
886
886
  // because this is where an app's user actually met the two languages side by side.
887
887
  renderAdminApp("/admin/audit", 30, true, DUTCH);
888
888
  await screen.findByRole("heading", { level: 1, name: "Auditlog" });
889
- expect(await screen.findByText("1–1 van 1 resultaten")).toBeInTheDocument();
889
+ expect(await screen.findByText("1–1 van 1 resultaat")).toBeInTheDocument();
890
890
 
891
891
  fireEvent.click(await screen.findByRole("button", { name: "Rij uitklappen" }));
892
892
  expect(await screen.findByText("Verzoek")).toBeInTheDocument();
@@ -620,6 +620,35 @@ describe("DataView localisation", () => {
620
620
  expect(screen.queryByText(/results/)).not.toBeInTheDocument();
621
621
  });
622
622
 
623
+ it("says a single result in the singular, in both shipped languages", async () => {
624
+ // The footer used to read "1–1 of 1 results" and "1–1 van 1 resultaten": one sentence for
625
+ // every count, with the plural noun in it.
626
+ render(
627
+ <LocaleProvider locales={{ en: LOCALE_EN, nl: LOCALE_NL }}>
628
+ <LanguageSwitcher />
629
+ <DataView repository={inMemoryRepo(TICKETS.slice(0, 1))} columns={COLUMNS} />
630
+ </LocaleProvider>,
631
+ );
632
+ expect(await screen.findByText("1–1 of 1 result")).toBeInTheDocument();
633
+
634
+ fireEvent.click(screen.getByRole("button", { name: "Language" }));
635
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Nederlands" }));
636
+
637
+ expect(await screen.findByText("1–1 van 1 resultaat")).toBeInTheDocument();
638
+ });
639
+
640
+ it("renders an instance's own range as given, with no plural form chosen", async () => {
641
+ // An override is one UiText, the instance's own wording; only the locale's has forms.
642
+ render(
643
+ <DataView
644
+ repository={inMemoryRepo(TICKETS.slice(0, 1))}
645
+ columns={COLUMNS}
646
+ strings={{ resultsRange: "{from}–{to} / {total} tickets" }}
647
+ />,
648
+ );
649
+ expect(await screen.findByText("1–1 / 1 tickets")).toBeInTheDocument();
650
+ });
651
+
623
652
  it("lets a per-instance string win over the locale", async () => {
624
653
  render(
625
654
  <LocaleProvider locales={{ en: LOCALE_EN, nl: LOCALE_NL }} defaultLocale="nl">
@@ -32,7 +32,7 @@ export function DataViewPagination({
32
32
  totalCount,
33
33
  onPaginationChange,
34
34
  }: DataViewPaginationProps) {
35
- const { strings, format } = useDataViewText();
35
+ const { strings, format, formatCount } = useDataViewText();
36
36
 
37
37
  const known = totalCount !== undefined;
38
38
  const pageCount = Math.max(1, Math.ceil((totalCount ?? 0) / pagination.pageSize));
@@ -46,7 +46,7 @@ export function DataViewPagination({
46
46
 
47
47
  return (
48
48
  <div data-terp="dataview-pagination">
49
- <span>{known ? format(strings.resultsRange, { from, to, total: totalCount }) : null}</span>
49
+ <span>{known ? formatCount(strings.resultsRange, totalCount, { from, to, total: totalCount }) : null}</span>
50
50
  {/* aria-disabled, not disabled, and the difference is where focus goes. Each of these
51
51
  four buttons has a bound condition recomputed from what its own click just changed, so
52
52
  pressing "next" until the last page disabled the very control the user was operating —
@@ -59,7 +59,7 @@ export interface DataViewToolbarProps<T> {
59
59
  * one instance of an attribute is not owning every element such a selector reaches.
60
60
  */
61
61
  export function DataViewToolbar<T>(props: DataViewToolbarProps<T>) {
62
- const { strings, resolve, format } = useDataViewText();
62
+ const { strings, resolve, format, formatCount } = useDataViewText();
63
63
  const search = useViewSearch(props.search, props.onSearchChange, props.searchDebounceMs ?? 0);
64
64
 
65
65
  const selectionMode = props.selectedCount > 0;
@@ -78,7 +78,7 @@ export function DataViewToolbar<T>(props: DataViewToolbarProps<T>) {
78
78
  </span>
79
79
  {props.onSelectAllAcrossPages !== undefined && !props.selectAllAcrossPages && (
80
80
  <Button variant="secondary" onClick={props.onSelectAllAcrossPages}>
81
- {format(strings.selectAllResults, { total: props.totalCount })}
81
+ {formatCount(strings.selectAllResults, props.totalCount, { total: props.totalCount })}
82
82
  </Button>
83
83
  )}
84
84
  <span data-terp="dataview-toolbar-actions">
@@ -4,19 +4,40 @@ import type { ReactNode } from "react";
4
4
  import { useFormatDate } from "../format";
5
5
  import { injectTerpStyles } from "../styles";
6
6
  import { Menu, MenuItem } from "../ui/Menu";
7
- import { useStrings, useUiText } from "../uiText";
8
- import type { ResolveUiText, TerpStrings, UiText } from "../uiText";
7
+ import { isPluralText, usePlural, useStrings, useUiText } from "../uiText";
8
+ import type { PluralText, ResolveUiText, TerpStrings, UiText } from "../uiText";
9
9
  import { formatDataViewString } from "./types";
10
10
  import type { DataViewStrings } from "./types";
11
11
 
12
12
  injectTerpStyles();
13
13
 
14
+ /**
15
+ * The strings a DataView part reads: the locale's, under an instance's overrides.
16
+ *
17
+ * Wider than {@link DataViewStrings} in two keys. From the locale, the result range and the
18
+ * select-all label are {@link PluralText}, one form per plural category; an instance that
19
+ * overrides them passes one `UiText`, which is its own wording and is used as given.
20
+ */
21
+ export type DataViewTextSet = Omit<DataViewStrings, "resultsRange" | "selectAllResults"> & {
22
+ resultsRange: CountedText;
23
+ selectAllResults: CountedText;
24
+ };
25
+
26
+ /** A count-bearing string: the locale's plural forms, or an instance's own wording. */
27
+ type CountedText = UiText | PluralText;
28
+
14
29
  /** Internal: merged strings + resolver every DataView sub-component reads. */
15
30
  export interface DataViewTextApi {
16
- strings: DataViewStrings;
31
+ strings: DataViewTextSet;
17
32
  resolve: ResolveUiText;
18
- /** Resolve a countable string and fill its `{placeholder}`s. */
33
+ /** Resolve a string with `{placeholder}`s and fill them. */
19
34
  format: (text: UiText, values: Record<string, string | number>) => string;
35
+ /** The same for a string whose wording depends on *count*: choose its form, then fill it. */
36
+ formatCount: (
37
+ text: CountedText,
38
+ count: number,
39
+ values: Record<string, string | number>,
40
+ ) => string;
20
41
  }
21
42
 
22
43
  /**
@@ -31,7 +52,7 @@ export interface DataViewTextApi {
31
52
  * Written out rather than derived from the key names, so a missing or misspelt key is a type
32
53
  * error here and not an `undefined` on screen.
33
54
  */
34
- function dataViewStrings(strings: TerpStrings): DataViewStrings {
55
+ function dataViewStrings(strings: TerpStrings): DataViewTextSet {
35
56
  return {
36
57
  searchPlaceholder: strings.dataViewSearchPlaceholder,
37
58
  clearSearch: strings.dataViewClearSearch,
@@ -82,13 +103,16 @@ export function useDataViewText(): DataViewTextApi {
82
103
  const overrides = useContext(DataViewOverridesContext);
83
104
  const framework = useStrings();
84
105
  const resolve = useUiText();
106
+ const plural = usePlural();
85
107
  return useMemo<DataViewTextApi>(
86
108
  () => ({
87
109
  strings: { ...dataViewStrings(framework), ...overrides },
88
110
  resolve,
89
111
  format: (text, values) => formatDataViewString(resolve(text), values),
112
+ formatCount: (text, count, values) =>
113
+ formatDataViewString(isPluralText(text) ? plural(text, count) : resolve(text), values),
90
114
  }),
91
- [framework, overrides, resolve],
115
+ [framework, overrides, resolve, plural],
92
116
  );
93
117
  }
94
118
 
@@ -219,7 +219,7 @@ export interface DataViewStrings {
219
219
  tableView: UiText;
220
220
  cardView: UiText;
221
221
  pageSize: UiText;
222
- resultsRange: UiText; // "{from}–{to} of {total} results"
222
+ resultsRange: UiText; // "{from}–{to} of {total} …": yours, used as given — the locale's has plural forms
223
223
  pageOf: UiText; // "Page {page} of {pages}"
224
224
  firstPage: UiText;
225
225
  previousPage: UiText;
@@ -228,7 +228,7 @@ export interface DataViewStrings {
228
228
  selectAllPage: UiText;
229
229
  selectRow: UiText;
230
230
  selected: UiText; // "{count} selected"
231
- selectAllResults: UiText; // "Select all {total} results"
231
+ selectAllResults: UiText; // "… {total} …": yours, used as given — the locale's has plural forms
232
232
  clearSelection: UiText;
233
233
  moreActions: UiText;
234
234
  actions: UiText;
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,
@@ -10,7 +10,7 @@ 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();
@@ -24,6 +24,22 @@ function SignOutLabel() {
24
24
 
25
25
  const NL = LOCALE_NL;
26
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
+
27
43
  describe("LocaleProvider + LanguageSwitcher", () => {
28
44
  it("feeds the active catalog's overrides through the UiText seam", () => {
29
45
  render(
@@ -252,9 +268,7 @@ describe("LocaleProvider + LanguageSwitcher", () => {
252
268
  ),
253
269
  ).toThrow(/missing .* framework string translation/);
254
270
 
255
- const germanStrings = Object.fromEntries(
256
- Object.keys(DEFAULT_STRINGS).map((key) => [key, `de:${key}`]),
257
- );
271
+ const germanStrings = completeCatalog("de");
258
272
  expect(
259
273
  defineAppLocales(
260
274
  {
@@ -286,10 +300,9 @@ describe("LocaleProvider + LanguageSwitcher", () => {
286
300
  // The upgrade path, pinned: a catalog complete against the key set before DataView's
287
301
  // strings joined it. Refused, and by name, because the alternative is the defect itself —
288
302
  // every table in the app back in English under a locale that claims to be complete.
289
- const shellOnly = Object.fromEntries(
290
- Object.keys(DEFAULT_STRINGS)
291
- .filter((key) => !key.startsWith("dataView"))
292
- .map((key) => [key, `de:${key}`]),
303
+ const shellOnly = completeCatalog(
304
+ "de",
305
+ Object.keys(DEFAULT_STRINGS).filter((key) => !key.startsWith("dataView")),
293
306
  );
294
307
  expect(() =>
295
308
  render(
@@ -313,7 +326,119 @@ describe("LocaleProvider + LanguageSwitcher", () => {
313
326
  });
314
327
  });
315
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
+
316
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
+
317
442
  it("translates every framework string (completeness drift-guard)", () => {
318
443
  // A new TerpStrings key without a Dutch translation fails here, so the
319
444
  // bundled catalog can never silently fall back to English for new chrome.
package/src/locale.tsx CHANGED
@@ -4,7 +4,7 @@ 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(
@@ -240,7 +264,10 @@ export const LOCALE_NL: LocaleCatalog = {
240
264
  accessAddsNothing: "Niets extra ten opzichte van de tier eronder",
241
265
  accessNeverAssignable: "Nooit per module toe te kennen",
242
266
  accessNotAssignable: "Niet per module toe te kennen",
243
- 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
+ },
244
271
  accessDeclaredOnly:
245
272
  "Dit is wat de applicatie vastlegt. Het laat niet zien wie welke rol heeft — open een persoon om dat te zien.",
246
273
  moduleAccessTitle: "Toegang per module",
@@ -310,7 +337,10 @@ export const LOCALE_NL: LocaleCatalog = {
310
337
  dataViewTableView: "Tabelweergave",
311
338
  dataViewCardView: "Kaartweergave",
312
339
  dataViewPageSize: "Rijen per pagina",
313
- dataViewResultsRange: "{from}–{to} van {total} resultaten",
340
+ dataViewResultsRange: {
341
+ one: "{from}–{to} van {total} resultaat",
342
+ other: "{from}–{to} van {total} resultaten",
343
+ },
314
344
  dataViewPageOf: "Pagina {page} van {pages}",
315
345
  dataViewFirstPage: "Eerste pagina",
316
346
  dataViewPreviousPage: "Vorige pagina",
@@ -319,7 +349,10 @@ export const LOCALE_NL: LocaleCatalog = {
319
349
  dataViewSelectAllPage: "Alle rijen op deze pagina selecteren",
320
350
  dataViewSelectRow: "Rij selecteren",
321
351
  dataViewSelected: "{count} geselecteerd",
322
- dataViewSelectAllResults: "Alle {total} resultaten selecteren",
352
+ dataViewSelectAllResults: {
353
+ one: "{total} resultaat selecteren",
354
+ other: "Alle {total} resultaten selecteren",
355
+ },
323
356
  dataViewClearSelection: "Selectie wissen",
324
357
  dataViewMoreActions: "Meer acties",
325
358
  dataViewActions: "Acties",
@@ -466,7 +499,11 @@ export function LocaleProvider({
466
499
 
467
500
  return (
468
501
  <LocaleContext.Provider value={value}>
469
- <UiTextProvider strings={locales[activeLocale]?.strings} resolveText={resolveText}>
502
+ <UiTextProvider
503
+ strings={locales[activeLocale]?.strings}
504
+ resolveText={resolveText}
505
+ locale={activeLocale}
506
+ >
470
507
  {children}
471
508
  </UiTextProvider>
472
509
  </LocaleContext.Provider>
@@ -7,10 +7,84 @@ import type { FrameworkText, UiText } from "@terpjs/contract";
7
7
  import { Page } from "./Page";
8
8
  import { ResourceList } from "./ResourceList";
9
9
  import { TerpProvider } from "./TerpProvider";
10
- import { resolveUiText, resolveUiTextNode, UiTextProvider, useUiText } from "./uiText";
10
+ import {
11
+ resolveUiText,
12
+ resolveUiTextNode,
13
+ UiTextProvider,
14
+ usePlural,
15
+ useUiText,
16
+ } from "./uiText";
17
+ import type { PluralText } from "./uiText";
11
18
 
12
19
  afterEach(cleanup);
13
20
 
21
+ describe("usePlural", () => {
22
+ // Polish, because its categories differ from English for the same counts: 3 is "few" and 5
23
+ // is "many" there, and both are "other" in English — so a form chosen by the wrong rules is
24
+ // visible, where Dutch and English would agree on every integer.
25
+ const FORMS: PluralText = { one: "one", few: "few", many: "many", other: "other" };
26
+
27
+ function Chosen({ count, text = FORMS }: { count: number; text?: PluralText }) {
28
+ const plural = usePlural();
29
+ return <li>{`${count}:${plural(text, count)}`}</li>;
30
+ }
31
+
32
+ it("chooses the form the provider's locale gives each count", () => {
33
+ render(
34
+ <UiTextProvider locale="pl">
35
+ <Chosen count={1} />
36
+ <Chosen count={3} />
37
+ <Chosen count={5} />
38
+ </UiTextProvider>,
39
+ );
40
+ expect(screen.getAllByRole("listitem").map((item) => item.textContent)).toEqual([
41
+ "1:one",
42
+ "3:few",
43
+ "5:many",
44
+ ]);
45
+ });
46
+
47
+ it("uses English rules with no provider, and a nested provider inherits its parent's", () => {
48
+ render(
49
+ <>
50
+ <Chosen count={3} />
51
+ <UiTextProvider locale="pl">
52
+ <UiTextProvider strings={{ loading: "Ładowanie…" }}>
53
+ <Chosen count={3} />
54
+ </UiTextProvider>
55
+ </UiTextProvider>
56
+ </>,
57
+ );
58
+ expect(screen.getAllByRole("listitem").map((item) => item.textContent)).toEqual([
59
+ "3:other",
60
+ "3:few",
61
+ ]);
62
+ });
63
+
64
+ it("answers with the other form when the text lacks the chosen one", () => {
65
+ render(
66
+ <UiTextProvider locale="pl">
67
+ <Chosen count={3} text={{ other: "some" }} />
68
+ </UiTextProvider>,
69
+ );
70
+ expect(screen.getByRole("listitem")).toHaveTextContent("3:some");
71
+ });
72
+
73
+ it("refuses a table given directly that writes a count-bearing string as one string", () => {
74
+ // The old shape. Unchecked, `plural` would have handed `undefined` to the caller that
75
+ // fills the placeholders, and the access pane would have thrown on `.replace`.
76
+ expect(() =>
77
+ render(
78
+ <UiTextProvider
79
+ strings={{ accessUnexplainedRoutes: "{count} acties" as unknown as PluralText }}
80
+ >
81
+ <span />
82
+ </UiTextProvider>,
83
+ ),
84
+ ).toThrow(/UiTextProvider framework string "accessUnexplainedRoutes" counts something/);
85
+ });
86
+ });
87
+
14
88
  describe("resolveUiText", () => {
15
89
  it("passes plain strings through and falls back to a descriptor's message", () => {
16
90
  expect(resolveUiText("Tasks")).toBe("Tasks");
@@ -139,6 +213,21 @@ describe("FrameworkText", () => {
139
213
  expect(() => render(<Label text={inherited} />)).toThrow(/names "toString"/);
140
214
  });
141
215
 
216
+ it("refuses a count-bearing key, which has forms and no one string to render", () => {
217
+ const counted = { framework: "dataViewResultsRange" } as unknown as FrameworkText;
218
+ expect(() => render(<Label text={counted} />)).toThrow(
219
+ /FrameworkText names "dataViewResultsRange", which counts something/,
220
+ );
221
+ });
222
+
223
+ it("is a typecheck error for a count-bearing key", () => {
224
+ // As below: `tsc --noEmit` runs the directive, which fails as unused if the manifest's key
225
+ // type ever widens back to every TerpStrings key.
226
+ // @ts-expect-error dataViewResultsRange holds plural forms, not a label.
227
+ const counted: FrameworkText = { framework: "dataViewResultsRange" };
228
+ expect(counted.framework).toBe("dataViewResultsRange");
229
+ });
230
+
142
231
  it("is a typecheck error for a key the table does not have", () => {
143
232
  // The directive is the test, and `tsc --noEmit` is what runs it: it fails as unused the
144
233
  // moment a misspelt key compiles, as one would if the key were widened to `string`. The
package/src/uiText.tsx CHANGED
@@ -5,11 +5,75 @@ import type { FrameworkText, UiText } from "@terpjs/contract";
5
5
  export type { UiText } from "@terpjs/contract";
6
6
 
7
7
  // The keys a manifest's `FrameworkText` may name are this table's, so a misspelt one is a
8
- // typecheck error where the manifest is written rather than an empty label on screen.
8
+ // typecheck error where the manifest is written rather than an empty label on screen. Only its
9
+ // plain-string keys: a nav label has no count to choose a plural form by.
9
10
  declare module "@terpjs/contract" {
10
- interface TerpFrameworkStrings extends TerpStrings {}
11
+ interface TerpFrameworkStrings extends Pick<TerpStrings, FrameworkTextKey> {}
11
12
  }
12
13
 
14
+ /**
15
+ * A framework string whose wording depends on a count: one form per CLDR plural category.
16
+ *
17
+ * English and Dutch each have two categories, `one` and `other`; Polish has four. The form is
18
+ * chosen by the count under the active locale's `Intl.PluralRules`, so "1 result" and
19
+ * "2 results" are two sentences rather than one sentence with "(s)" in it, and `other` answers
20
+ * for a category the catalog has no form for. Each form keeps the same `{placeholder}`s,
21
+ * because a category is a grammatical class and not a number: in Russian, 21 takes the `one`
22
+ * form.
23
+ */
24
+ export type PluralText = Readonly<Partial<Record<Intl.LDMLPluralRule, string>>> & {
25
+ readonly other: string;
26
+ };
27
+
28
+ /** Every CLDR plural category; a {@link PluralText} names its forms from these. */
29
+ const PLURAL_CATEGORIES: readonly string[] = ["zero", "one", "two", "few", "many", "other"];
30
+
31
+ /**
32
+ * Refuse a count-bearing framework string that is not a {@link PluralText}.
33
+ *
34
+ * Structure only, and deliberately: which categories a language uses comes from the runtime's
35
+ * ICU data, which differs between browsers and versions — French is `one`/`other` on some and
36
+ * `one`/`many`/`other` on newer ones — so a check against it would pass a catalog in one browser
37
+ * and blank the app in the next. The shipped catalogs are held to their languages' categories
38
+ * by react-core's own tests instead, where the ICU is fixed. *where* names the table in the
39
+ * message: a locale, or a provider given its strings directly.
40
+ */
41
+ export function assertPluralShape(where: string, key: string, value: unknown): void {
42
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
43
+ throw new Error(
44
+ `${where} framework string "${key}" counts something, so it takes one form per plural ` +
45
+ 'category — at least { other: "…" }, usually { one: "…", other: "…" } — not a single string.',
46
+ );
47
+ }
48
+ const forms = value as Record<string, unknown>;
49
+ const stray = Object.keys(forms).find((category) => !PLURAL_CATEGORIES.includes(category));
50
+ if (stray !== undefined) {
51
+ throw new Error(
52
+ `${where} framework string "${key}" has a "${stray}" form, which is not a plural ` +
53
+ `category (${PLURAL_CATEGORIES.join(", ")}).`,
54
+ );
55
+ }
56
+ for (const category of ["other", ...Object.keys(forms)]) {
57
+ const form = forms[category];
58
+ if (typeof form !== "string" || form.trim() === "") {
59
+ throw new Error(
60
+ `${where} framework string "${key}" has no "${category}" form` +
61
+ (category === "other" ? ", which every language uses." : "."),
62
+ );
63
+ }
64
+ }
65
+ }
66
+
67
+ /** Whether *text* is a {@link PluralText} rather than a {@link UiText}. */
68
+ export function isPluralText(text: UiText | PluralText): text is PluralText {
69
+ return typeof text === "object" && "other" in text;
70
+ }
71
+
72
+ /** The `TerpStrings` keys that hold one plain string, which a `FrameworkText` may name. */
73
+ type FrameworkTextKey = {
74
+ [K in keyof TerpStrings]: TerpStrings[K] extends string ? K : never;
75
+ }[keyof TerpStrings];
76
+
13
77
  /**
14
78
  * A piece of user-facing text: either a plain string (used as-is) or a message
15
79
  * descriptor — a stable `id` for a translation catalog plus the source-language
@@ -187,8 +251,8 @@ export interface TerpStrings {
187
251
  accessNeverAssignable: string;
188
252
  /** Access pane: shown on a module that has not opted into per-module roles. */
189
253
  accessNotAssignable: string;
190
- /** Access pane: warns that some of the module's routes declared no operation. */
191
- accessUnexplainedRoutes: string;
254
+ /** Access pane: warns that some of the module's routes declared no operation; `{count}`. */
255
+ accessUnexplainedRoutes: PluralText;
192
256
  /** Access pane: the note that this screen shows the declared model, not who holds what. */
193
257
  accessDeclaredOnly: string;
194
258
  /** Assignment panel: the section heading on a person's or group's detail screen. */
@@ -335,8 +399,8 @@ export interface TerpStrings {
335
399
  dataViewCardView: string;
336
400
  /** DataView: the page-size selector. */
337
401
  dataViewPageSize: string;
338
- /** DataView: the footer's result range; `{from}`, `{to}` and `{total}` are replaced. */
339
- dataViewResultsRange: string;
402
+ /** DataView: the footer's result range; `{from}`, `{to}` and `{total}`, plural by `{total}`. */
403
+ dataViewResultsRange: PluralText;
340
404
  /** DataView: the footer's page position; `{page}` and `{pages}` are replaced. */
341
405
  dataViewPageOf: string;
342
406
  /** DataView: pagination, to the first page. */
@@ -353,8 +417,8 @@ export interface TerpStrings {
353
417
  dataViewSelectRow: string;
354
418
  /** DataView: the selection count; `{count}` is replaced. */
355
419
  dataViewSelected: string;
356
- /** DataView: widens the selection to every result; `{total}` is replaced. */
357
- dataViewSelectAllResults: string;
420
+ /** DataView: widens the selection to every result; `{total}`, plural by it. */
421
+ dataViewSelectAllResults: PluralText;
358
422
  /** DataView: clears the row selection. */
359
423
  dataViewClearSelection: string;
360
424
  /** DataView: the row-action and batch-action overflow trigger. */
@@ -475,7 +539,10 @@ export const DEFAULT_STRINGS: TerpStrings = {
475
539
  accessAddsNothing: "Nothing beyond the tier below",
476
540
  accessNeverAssignable: "Never assignable per module",
477
541
  accessNotAssignable: "Not assignable per module",
478
- accessUnexplainedRoutes: "{count} action(s) in this module have no description yet",
542
+ accessUnexplainedRoutes: {
543
+ one: "{count} action in this module has no description yet",
544
+ other: "{count} actions in this module have no description yet",
545
+ },
479
546
  accessDeclaredOnly:
480
547
  "This is what the application declares. It does not show who holds which role — open a person to see that.",
481
548
  moduleAccessTitle: "Access per module",
@@ -545,7 +612,10 @@ export const DEFAULT_STRINGS: TerpStrings = {
545
612
  dataViewTableView: "Table view",
546
613
  dataViewCardView: "Card view",
547
614
  dataViewPageSize: "Rows per page",
548
- dataViewResultsRange: "{from}–{to} of {total} results",
615
+ dataViewResultsRange: {
616
+ one: "{from}–{to} of {total} result",
617
+ other: "{from}–{to} of {total} results",
618
+ },
549
619
  dataViewPageOf: "Page {page} of {pages}",
550
620
  dataViewFirstPage: "First page",
551
621
  dataViewPreviousPage: "Previous page",
@@ -554,7 +624,10 @@ export const DEFAULT_STRINGS: TerpStrings = {
554
624
  dataViewSelectAllPage: "Select all rows on this page",
555
625
  dataViewSelectRow: "Select row",
556
626
  dataViewSelected: "{count} selected",
557
- dataViewSelectAllResults: "Select all {total} results",
627
+ dataViewSelectAllResults: {
628
+ one: "Select the {total} result",
629
+ other: "Select all {total} results",
630
+ },
558
631
  dataViewClearSelection: "Clear selection",
559
632
  dataViewMoreActions: "More actions",
560
633
  dataViewActions: "Actions",
@@ -579,11 +652,14 @@ export const DEFAULT_STRINGS: TerpStrings = {
579
652
  interface UiTextContextValue {
580
653
  strings: TerpStrings;
581
654
  resolveText: ResolveUiText;
655
+ /** The locale whose plural rules choose a {@link PluralText}'s form. */
656
+ locale: string;
582
657
  }
583
658
 
584
659
  const UiTextContext = createContext<UiTextContextValue>({
585
660
  strings: DEFAULT_STRINGS,
586
661
  resolveText: resolveUiText,
662
+ locale: "en",
587
663
  });
588
664
 
589
665
  export interface UiTextProviderProps {
@@ -597,6 +673,12 @@ export interface UiTextProviderProps {
597
673
  * before it is reached (see {@link useUiText}).
598
674
  */
599
675
  resolveText?: ResolveUiText;
676
+ /**
677
+ * The locale code the `strings` are in, whose plural rules choose a {@link PluralText}'s
678
+ * form. `LocaleProvider` passes its active locale; without one the parent's applies, and
679
+ * at the root that is English.
680
+ */
681
+ locale?: string;
600
682
  children: ReactNode;
601
683
  }
602
684
 
@@ -606,15 +688,22 @@ export interface UiTextProviderProps {
606
688
  * use the bundled English defaults. An app localises by wrapping its tree
607
689
  * once — no per-component wiring, no i18n dependency inside react-core.
608
690
  */
609
- export function UiTextProvider({ strings, resolveText, children }: UiTextProviderProps) {
691
+ export function UiTextProvider({ strings, resolveText, locale, children }: UiTextProviderProps) {
610
692
  const parent = useContext(UiTextContext);
611
- const value = useMemo<UiTextContextValue>(
612
- () => ({
693
+ const value = useMemo<UiTextContextValue>(() => {
694
+ // A table given here directly has not been through LocaleProvider's check, and a
695
+ // count-bearing key written the old way, as one string, would render nothing usable.
696
+ for (const [key, supplied] of Object.entries(strings ?? {})) {
697
+ if (typeof DEFAULT_STRINGS[key as keyof TerpStrings] !== "string") {
698
+ assertPluralShape("UiTextProvider", key, supplied);
699
+ }
700
+ }
701
+ return {
613
702
  strings: { ...parent.strings, ...strings },
614
703
  resolveText: resolveText ?? parent.resolveText,
615
- }),
616
- [parent, strings, resolveText],
617
- );
704
+ locale: locale ?? parent.locale,
705
+ };
706
+ }, [parent, strings, resolveText, locale]);
618
707
  return <UiTextContext.Provider value={value}>{children}</UiTextContext.Provider>;
619
708
  }
620
709
 
@@ -623,6 +712,22 @@ export function useStrings(): TerpStrings {
623
712
  return useContext(UiTextContext).strings;
624
713
  }
625
714
 
715
+ /**
716
+ * The form of a {@link PluralText} the active locale's grammar gives *count*.
717
+ *
718
+ * `other` answers for a category the text has no form for — a catalog written against another
719
+ * engine's plural data, or one that leaves a rare category out — so a count always renders a
720
+ * sentence. For an app that renders a count-bearing framework string itself, read from
721
+ * {@link useStrings}.
722
+ */
723
+ export function usePlural(): (text: PluralText, count: number) => string {
724
+ const { locale } = useContext(UiTextContext);
725
+ return useMemo(() => {
726
+ const rules = new Intl.PluralRules(locale);
727
+ return (text: PluralText, count: number) => text[rules.select(count)] ?? text.other;
728
+ }, [locale]);
729
+ }
730
+
626
731
  /**
627
732
  * The active {@link UiText} resolver — call it on any `UiText` prop before rendering, and on a
628
733
  * manifest's navigation label, which may also be a {@link FrameworkText}.
@@ -648,7 +753,14 @@ export function useUiText(): (text: UiText | FrameworkText) => string {
648
753
  "{ id, message } descriptor in frontend/i18n.json.",
649
754
  );
650
755
  }
651
- return strings[text.framework];
756
+ const value: unknown = strings[text.framework];
757
+ if (typeof value !== "string") {
758
+ throw new Error(
759
+ `FrameworkText names "${text.framework}", which counts something and has one form ` +
760
+ "per plural category. A navigation label is one string; name a plain one.",
761
+ );
762
+ }
763
+ return value;
652
764
  },
653
765
  [strings, resolveText],
654
766
  );