@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
@@ -160,6 +160,29 @@ describe("UserMenu", () => {
160
160
  expect(trigger?.tagName).toBe("BUTTON");
161
161
  });
162
162
 
163
+ it("names the sign-out item for a caller that cannot read it", async () => {
164
+ // The second half of the same contract. `logout()` used to click the menuitem named
165
+ // "Sign out", which is a sentence in one language: an app that boots in any other locale
166
+ // failed its own conformance suite before it had any code of its own. The helper finds the
167
+ // item by marker path now, so what is pinned here is that the path lands on sign-out and on
168
+ // nothing else — with Settings present, so a part wrapped around the wrong item, or around
169
+ // both, fails rather than passing by being the only candidate.
170
+ stubAuthFetch();
171
+ render(
172
+ <TerpProvider baseUrl="https://api.test">
173
+ <LogInOnMount />
174
+ <UserMenu onSettings={() => undefined} />
175
+ </TerpProvider>,
176
+ );
177
+ fireEvent.click(await screen.findByRole("button", { name: /jane\.doe@example\.com/ }));
178
+ // The panel is portalled to document.body, so the path is resolved from the document.
179
+ const named = document.querySelectorAll(
180
+ '[data-terp="user-menu-sign-out"] [data-terp="menu-item"]',
181
+ );
182
+ expect(named).toHaveLength(1);
183
+ expect(named[0]).toBe(screen.getByRole("menuitem", { name: "Sign out" }));
184
+ });
185
+
163
186
  it("signs out via the menu (revokes the token server-side)", async () => {
164
187
  const fetchMock = stubAuthFetch();
165
188
  render(
package/src/UserMenu.tsx CHANGED
@@ -94,7 +94,15 @@ export function UserMenu({ collapsed = false, onSettings, defaultOpen }: UserMen
94
94
  }}
95
95
  />
96
96
  )}
97
- <MenuItem label={strings.signOut} icon={<Icon name="logout" />} onSelect={() => void auth.logout()} />
97
+ {/* A named part, for the one caller that has to find sign-out without reading it:
98
+ `@terpjs/conformance`'s logout helper, which runs in whatever language the app
99
+ ships, so the item's accessible name cannot be its handle. `menu-item` stays on
100
+ the button because that is its styling, and one element carries one marker.
101
+ The part is display: contents, so the menu's grid still spaces the item and its
102
+ roving focus still finds it among the menuitems. */}
103
+ <div data-terp="user-menu-sign-out">
104
+ <MenuItem label={strings.signOut} icon={<Icon name="logout" />} onSelect={() => void auth.logout()} />
105
+ </div>
98
106
  </>
99
107
  )}
100
108
  </Menu>
@@ -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>
@@ -102,7 +102,7 @@ export function AuditLogAdmin() {
102
102
  items={[
103
103
  { label: strings.targetColumn, value: `${event.target_type} ${event.target_id}` },
104
104
  { label: strings.actorColumn, value: event.actor_id ?? "—" },
105
- { label: "Request", value: event.request_id ?? "—" },
105
+ { label: strings.requestLabel, value: event.request_id ?? "—" },
106
106
  ]}
107
107
  />
108
108
  {event.payload !== null && (
@@ -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
  });
@@ -1,6 +1,6 @@
1
1
  // @vitest-environment jsdom
2
2
  import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
3
- import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
3
+ import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
4
4
  import { useEffect } from "react";
5
5
  import { afterEach, describe, expect, it, vi } from "vitest";
6
6
  import type { ModuleManifest } from "@terpjs/contract";
@@ -9,6 +9,8 @@ import type { ComponentType } from "react";
9
9
  import { withAdminArea } from "../bootstrap";
10
10
  import type { AdminAreaSections } from "../bootstrap";
11
11
  import { formatDateTime } from "../format";
12
+ import { LOCALE_EN, LOCALE_NL, LocaleProvider } from "../locale";
13
+ import type { LocaleProviderProps } from "../locale";
12
14
  import { buildAppRouter } from "../router";
13
15
  import { Page } from "../Page";
14
16
  import { TerpProvider, useAuth } from "../TerpProvider";
@@ -47,7 +49,7 @@ describe("withAdminArea", () => {
47
49
  "/admin/groups/new",
48
50
  "/admin/groups/$groupId",
49
51
  ]));
50
- expect(admin?.nav?.[0]?.label).toBe("Admin");
52
+ expect(admin?.nav?.[0]?.label).toEqual({ framework: "admin" });
51
53
  expect(views.TerpAdminHub).toBeDefined();
52
54
  });
53
55
 
@@ -115,7 +117,7 @@ describe("withAdminArea", () => {
115
117
  groups: false,
116
118
  });
117
119
  const admin = manifests.find((manifest) => manifest.name === "terp-admin");
118
- expect(admin?.nav?.[0]?.label).toBe("Admin");
120
+ expect(admin?.nav?.[0]?.label).toEqual({ framework: "admin" });
119
121
  expect(admin?.routes.map((route) => route.path)).toEqual([
120
122
  "/admin",
121
123
  "/admin/audit",
@@ -395,10 +397,14 @@ function stubAdminFetch() {
395
397
  return fetchMock;
396
398
  }
397
399
 
400
+ /** An English-source app opened in Dutch. */
401
+ const DUTCH = { locales: { en: LOCALE_EN, nl: LOCALE_NL }, defaultLocale: "nl" };
402
+
398
403
  function renderAdminApp(
399
404
  initialPath: string,
400
405
  roleRank = 30,
401
406
  adminArea: boolean | AdminAreaSections = true,
407
+ locale?: Pick<LocaleProviderProps, "locales" | "defaultLocale">,
402
408
  ) {
403
409
  const manifests: ModuleManifest[] = [
404
410
  { name: "notes", routes: [{ path: "/", view: "NotesList" }], nav: [] },
@@ -427,13 +433,22 @@ function renderAdminApp(
427
433
  });
428
434
  });
429
435
  }
430
- render(
436
+ const app = (
431
437
  <TerpProvider baseUrl="https://api.test">
432
438
  <ToastProvider>
433
439
  <LogInOnMount />
434
440
  <RouterProvider router={router} />
435
441
  </ToastProvider>
436
- </TerpProvider>,
442
+ </TerpProvider>
443
+ );
444
+ render(
445
+ locale === undefined ? (
446
+ app
447
+ ) : (
448
+ <LocaleProvider locales={locale.locales} defaultLocale={locale.defaultLocale}>
449
+ {app}
450
+ </LocaleProvider>
451
+ ),
437
452
  );
438
453
  return { fetchMock, router };
439
454
  }
@@ -863,6 +878,43 @@ describe("the packaged admin area", () => {
863
878
  }
864
879
  });
865
880
 
881
+ it("speaks the app's language on the audit screen, its table and expanded row included", async () => {
882
+ // The framework's own screen, under the framework's own Dutch catalog. Its title was Dutch
883
+ // and everything its DataView drew was not — the result count, the row controls — because
884
+ // DataView's strings were a table the locale could not reach; and the expanded row carried
885
+ // one label written straight into the screen. Asserted here rather than on a bare DataView
886
+ // because this is where an app's user actually met the two languages side by side.
887
+ renderAdminApp("/admin/audit", 30, true, DUTCH);
888
+ await screen.findByRole("heading", { level: 1, name: "Auditlog" });
889
+ expect(await screen.findByText("1–1 van 1 resultaat")).toBeInTheDocument();
890
+
891
+ fireEvent.click(await screen.findByRole("button", { name: "Rij uitklappen" }));
892
+ expect(await screen.findByText("Verzoek")).toBeInTheDocument();
893
+ expect(screen.queryByText("Request")).toBeNull();
894
+ expect(screen.queryByText(/results/)).toBeNull();
895
+ });
896
+
897
+ it.each([
898
+ ["nl", "nl", "Hoofdnavigatie", "Beheer"],
899
+ ["nl", "en", "Primary", "Admin"],
900
+ ["en", "nl", "Hoofdnavigatie", "Beheer"],
901
+ ])(
902
+ "labels the sidebar entry in the active locale (source %s, opened in %s)",
903
+ async (source, active, navigationName, label) => {
904
+ // The first row is the case a `{ id, message }` descriptor could not serve. In an app whose
905
+ // source locale is Dutch, a descriptor opened in Dutch renders its `message` without
906
+ // consulting any catalog — and a framework-authored message is English. The entry names
907
+ // the framework string instead, so it is the active table's word whichever locale is the
908
+ // source: Dutch where the app opens in Dutch, English where it opens in English.
909
+ const locales =
910
+ source === "nl" ? { nl: LOCALE_NL, en: LOCALE_EN } : { en: LOCALE_EN, nl: LOCALE_NL };
911
+ renderAdminApp("/admin", 30, true, { locales, defaultLocale: active });
912
+ const sidebar = await screen.findByRole("navigation", { name: navigationName });
913
+ expect(await within(sidebar).findByRole("link", { name: label })).toBeInTheDocument();
914
+ expect(within(sidebar).getAllByRole("link")).toHaveLength(1);
915
+ },
916
+ );
917
+
866
918
  it("keeps the audit payload's scroll container reachable by keyboard", async () => {
867
919
  // The gate for the SC 2.1.1 fix, and it has to be here rather than in the workbench.
868
920
  // `code-block` declares `overflow-x: auto`, so a wide payload is a scroll container, and a
@@ -13,11 +13,14 @@ import { UserDetail } from "./UserDetail";
13
13
  import { UsersAdmin } from "./UsersAdmin";
14
14
 
15
15
  /**
16
- * The packaged administration area every Terp app ships: one admin-gated "Admin"
17
- * sidebar entry opening a hub (`/admin`) whose cards lead to the users, groups and
18
- * audit-log overviews — the UI over the base-profile capabilities the backend
19
- * mounts in every app (users, groups + access, audit; ADR 0074). The whole area is
20
- * `role: "admin"` end to end; the backend re-checks every call regardless.
16
+ * The packaged administration area every Terp app ships: one admin-gated sidebar entry
17
+ * opening a hub (`/admin`) whose cards lead to the users, groups and audit-log overviews —
18
+ * the UI over the base-profile capabilities the backend mounts in every app (users,
19
+ * groups + access, audit; ADR 0074). The whole area is `role: "admin"` end to end; the
20
+ * backend re-checks every call regardless.
21
+ *
22
+ * The entry's label names the `admin` framework string rather than spelling it out, so it
23
+ * reads "Beheer" under `LOCALE_NL` whatever the app's own source locale is (ADR 0153).
21
24
  *
22
25
  * `renderTerpApp` injects it by default (`adminArea: false` opts out; an app
23
26
  * manifest claiming one of its paths overrides that screen). An L2 composition
@@ -38,7 +41,7 @@ export const adminModule: TerpModule = {
38
41
  { path: "/admin/audit", view: "TerpAdminAudit", role: "admin" },
39
42
  { path: "/admin/access", view: "TerpAdminAccess", role: "admin" },
40
43
  ],
41
- nav: [{ label: "Admin", to: "/admin", icon: "shield", role: "admin" }],
44
+ nav: [{ label: { framework: "admin" }, to: "/admin", icon: "shield", role: "admin" }],
42
45
  }),
43
46
  views: {
44
47
  TerpAdminHub: AdminHub,
@@ -122,7 +122,7 @@ describe("renderTerpApp", () => {
122
122
  screen.getByText("That value table is published and cannot be edited."),
123
123
  ).toBeInTheDocument(),
124
124
  );
125
- // And an override of a built-in code wins over DEFAULT_ERROR_MESSAGES, which is the
125
+ // And an override of a built-in code wins over the built-in wording, which is the
126
126
  // half that would still look fine if the map were merged the wrong way round.
127
127
  expect(screen.getByText("Niets gevonden.")).toBeInTheDocument();
128
128
  expect(screen.queryByText("This item could not be found.")).not.toBeInTheDocument();
package/src/bootstrap.tsx CHANGED
@@ -132,7 +132,8 @@ export interface RenderTerpAppOptions {
132
132
  headerActions?: ReactNode;
133
133
  /**
134
134
  * Per-code overrides and additions for the error copy an app shows
135
- * ({@link ErrorMessagesProvider}), merged over {@link DEFAULT_ERROR_MESSAGES}.
135
+ * ({@link ErrorMessagesProvider}), which win over the platform's own wording for its codes
136
+ * — the `errorCode*` keys of the active locale's `TerpStrings`.
136
137
  *
137
138
  * The provider, the hook and the default map were all exported and there was no way to
138
139
  * register a map from the one-call bootstrap, which owns everything between the root and
@@ -2,7 +2,9 @@
2
2
  import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
3
3
  import { afterEach, describe, expect, it, vi } from "vitest";
4
4
 
5
+ import { LOCALE_EN, LOCALE_NL, LanguageSwitcher, LocaleProvider } from "../locale";
5
6
  import { DataView } from "./DataView";
7
+ import { DataViewPagination } from "./DataViewPagination";
6
8
  import { InMemoryDataViewRepository } from "./repositories/InMemoryDataViewRepository";
7
9
  import { InMemoryViewStateRepository } from "./repositories/viewState";
8
10
  import type { DataViewColumn, DataViewQuery, DataViewRepository } from "./types";
@@ -584,3 +586,100 @@ describe("DataView search scope", () => {
584
586
  }
585
587
  });
586
588
  });
589
+
590
+ describe("DataView localisation", () => {
591
+ // DataView's strings are framework strings: the `dataView*` keys of TerpStrings. They used to
592
+ // be a separate English table that only the per-instance `strings` prop could change, so a
593
+ // DataView under a Dutch LocaleProvider still said "Search…" and "1–4 of 4 results" — the
594
+ // framework's own admin screens included — while every locale gate reported the catalog
595
+ // complete.
596
+ afterEach(() => {
597
+ // The switcher persists its choice; the next test must not open in it.
598
+ window.localStorage.clear();
599
+ });
600
+
601
+ it("speaks the app's locale without a strings prop, and follows a switch", async () => {
602
+ render(
603
+ <LocaleProvider locales={{ en: LOCALE_EN, nl: LOCALE_NL }}>
604
+ <LanguageSwitcher />
605
+ <DataView repository={inMemoryRepo()} columns={COLUMNS} />
606
+ </LocaleProvider>,
607
+ );
608
+ expect(await screen.findByText("1–4 of 4 results")).toBeInTheDocument();
609
+
610
+ fireEvent.click(screen.getByRole("button", { name: "Language" }));
611
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Nederlands" }));
612
+
613
+ expect(await screen.findByText("1–4 van 4 resultaten")).toBeInTheDocument();
614
+ expect(screen.getByRole("searchbox", { name: "Zoeken…" })).toHaveAttribute(
615
+ "placeholder",
616
+ "Zoeken…",
617
+ );
618
+ expect(screen.getByRole("button", { name: "Rijen per pagina" })).toBeInTheDocument();
619
+ expect(screen.getByRole("button", { name: "Weergaveopties" })).toBeInTheDocument();
620
+ expect(screen.queryByText(/results/)).not.toBeInTheDocument();
621
+ });
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
+
652
+ it("lets a per-instance string win over the locale", async () => {
653
+ render(
654
+ <LocaleProvider locales={{ en: LOCALE_EN, nl: LOCALE_NL }} defaultLocale="nl">
655
+ <DataView
656
+ repository={inMemoryRepo()}
657
+ columns={COLUMNS}
658
+ strings={{ searchPlaceholder: "Zoek een ticket…" }}
659
+ />
660
+ </LocaleProvider>,
661
+ );
662
+ // The rest of the view still follows the locale; only the overridden key does not.
663
+ expect(await screen.findByText("1–4 van 4 resultaten")).toBeInTheDocument();
664
+ expect(screen.getByRole("searchbox", { name: "Zoek een ticket…" })).toBeInTheDocument();
665
+ expect(screen.queryByRole("searchbox", { name: "Zoeken…" })).not.toBeInTheDocument();
666
+ });
667
+
668
+ it("localises a sub-component rendered outside any DataView", () => {
669
+ // The parts are exported for hand-built compositions, and outside a DataView there is no
670
+ // provider above them. The context's default used to be a finished English set with a
671
+ // resolver that ignored the locale, so this path stayed English whatever the provider did.
672
+ render(
673
+ <LocaleProvider locales={{ en: LOCALE_EN, nl: LOCALE_NL }} defaultLocale="nl">
674
+ <DataViewPagination
675
+ pagination={{ pageIndex: 1, pageSize: 10 }}
676
+ totalCount={45}
677
+ onPaginationChange={() => {}}
678
+ />
679
+ </LocaleProvider>,
680
+ );
681
+ expect(screen.getByText("11–20 van 45 resultaten")).toBeInTheDocument();
682
+ expect(screen.getByText("Pagina 2 van 5")).toBeInTheDocument();
683
+ expect(screen.getByRole("button", { name: "Volgende pagina" })).toBeInTheDocument();
684
+ });
685
+ });
@@ -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">
@@ -152,9 +152,11 @@ versioned envelope; corrupt data falls back to defaults) and
152
152
  `density="comfortable"` cannot make one view comfortable inside a compact subtree.
153
153
  - **Variants**: `variant="embedded"` renders a plain compact view (no view toggle, no
154
154
  page-size selector, no pagination footer, all rows) for panels/detail sections.
155
- - **i18n**: no hard-coded user-facing strings — every label is a `UiText` routed
156
- through the app's `UiTextProvider` resolver, with defaults overridable per instance
157
- via the `strings` prop.
155
+ - **i18n**: no hard-coded user-facing strings. The defaults are framework strings — the
156
+ `dataView*` keys of `TerpStrings` — so a DataView follows the app's `LocaleProvider` like
157
+ the rest of the chrome, and `LOCALE_NL` translates them. The `strings` prop overrides a key
158
+ for one instance and wins over the locale; every value is a `UiText` resolved through the
159
+ active resolver.
158
160
 
159
161
  ## Files
160
162
 
@@ -32,7 +32,7 @@ export type {
32
32
  DataViewSearchScope,
33
33
  DataViewStrings,
34
34
  } from "./types";
35
- export { DEFAULT_DATA_VIEW_STRINGS, emptyDataViewState } from "./types";
35
+ export { emptyDataViewState } from "./types";
36
36
 
37
37
  export { InMemoryDataViewRepository } from "./repositories/InMemoryDataViewRepository";
38
38
  export type { InMemoryDataViewRepositoryOptions } from "./repositories/InMemoryDataViewRepository";
@@ -1,33 +1,119 @@
1
- import { createContext, useCallback, useContext } from "react";
1
+ import { createContext, useCallback, useContext, useMemo } from "react";
2
2
  import type { ReactNode } from "react";
3
3
 
4
4
  import { useFormatDate } from "../format";
5
5
  import { injectTerpStyles } from "../styles";
6
6
  import { Menu, MenuItem } from "../ui/Menu";
7
- import { useUiText } from "../uiText";
8
- import type { ResolveUiText, UiText } from "../uiText";
9
- import { DEFAULT_DATA_VIEW_STRINGS, formatDataViewString } from "./types";
7
+ import { isPluralText, usePlural, useStrings, useUiText } from "../uiText";
8
+ import type { PluralText, ResolveUiText, TerpStrings, UiText } from "../uiText";
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
- const DataViewTextContext = createContext<DataViewTextApi>({
23
- strings: DEFAULT_DATA_VIEW_STRINGS,
24
- resolve: (text) => (typeof text === "string" ? text : text.message),
25
- format: (text, values) =>
26
- formatDataViewString(typeof text === "string" ? text : text.message, values),
27
- });
43
+ /**
44
+ * The DataView's strings, read out of the framework table.
45
+ *
46
+ * They used to be a second table of English defaults that only the per-instance `strings` prop
47
+ * could change. A locale catalog is typed against `TerpStrings`, so it had nowhere to put a
48
+ * DataView translation, and the completeness check that refuses a half-translated shell walked
49
+ * a table these strings were not in: under a Dutch locale every DataView rendered its toolbar
50
+ * and footer in English, the framework's own admin screens included, with every gate green.
51
+ *
52
+ * Written out rather than derived from the key names, so a missing or misspelt key is a type
53
+ * error here and not an `undefined` on screen.
54
+ */
55
+ function dataViewStrings(strings: TerpStrings): DataViewTextSet {
56
+ return {
57
+ searchPlaceholder: strings.dataViewSearchPlaceholder,
58
+ clearSearch: strings.dataViewClearSearch,
59
+ clearFilters: strings.dataViewClearFilters,
60
+ viewOptions: strings.dataViewViewOptions,
61
+ columns: strings.dataViewColumns,
62
+ moveUp: strings.dataViewMoveUp,
63
+ moveDown: strings.dataViewMoveDown,
64
+ tableView: strings.dataViewTableView,
65
+ cardView: strings.dataViewCardView,
66
+ pageSize: strings.dataViewPageSize,
67
+ resultsRange: strings.dataViewResultsRange,
68
+ pageOf: strings.dataViewPageOf,
69
+ firstPage: strings.dataViewFirstPage,
70
+ previousPage: strings.dataViewPreviousPage,
71
+ nextPage: strings.dataViewNextPage,
72
+ lastPage: strings.dataViewLastPage,
73
+ selectAllPage: strings.dataViewSelectAllPage,
74
+ selectRow: strings.dataViewSelectRow,
75
+ selected: strings.dataViewSelected,
76
+ selectAllResults: strings.dataViewSelectAllResults,
77
+ clearSelection: strings.dataViewClearSelection,
78
+ moreActions: strings.dataViewMoreActions,
79
+ actions: strings.dataViewActions,
80
+ openRow: strings.dataViewOpenRow,
81
+ expandRow: strings.dataViewExpandRow,
82
+ collapseRow: strings.dataViewCollapseRow,
83
+ empty: strings.dataViewEmpty,
84
+ loading: strings.dataViewLoading,
85
+ refreshing: strings.dataViewRefreshing,
86
+ errorTitle: strings.dataViewErrorTitle,
87
+ resizeColumn: strings.dataViewResizeColumn,
88
+ };
89
+ }
90
+
91
+ /**
92
+ * A DataView's per-instance overrides, and nothing else.
93
+ *
94
+ * The context carries only what the instance said, never a finished set of strings, so there is
95
+ * no default value to go stale: a sub-component rendered on its own — a `DataViewPagination`
96
+ * outside any `DataView` — reads the active locale exactly as one inside does. The context's
97
+ * default used to BE a finished set, English strings and a resolver that ignored the locale, so
98
+ * a fix to the provider alone would have left every standalone part exactly as it was.
99
+ */
100
+ const DataViewOverridesContext = createContext<Partial<DataViewStrings> | undefined>(undefined);
28
101
 
29
102
  export function useDataViewText(): DataViewTextApi {
30
- return useContext(DataViewTextContext);
103
+ const overrides = useContext(DataViewOverridesContext);
104
+ const framework = useStrings();
105
+ const resolve = useUiText();
106
+ const plural = usePlural();
107
+ return useMemo<DataViewTextApi>(
108
+ () => ({
109
+ strings: { ...dataViewStrings(framework), ...overrides },
110
+ resolve,
111
+ format: (text, values) => formatDataViewString(resolve(text), values),
112
+ formatCount: (text, count, values) =>
113
+ formatDataViewString(isPluralText(text) ? plural(text, count) : resolve(text), values),
114
+ }),
115
+ [framework, overrides, resolve, plural],
116
+ );
31
117
  }
32
118
 
33
119
  /**
@@ -66,14 +152,9 @@ export function DataViewTextProvider({
66
152
  overrides?: Partial<DataViewStrings>;
67
153
  children: ReactNode;
68
154
  }) {
69
- const resolve = useUiText();
70
- const strings: DataViewStrings = { ...DEFAULT_DATA_VIEW_STRINGS, ...overrides };
71
- const api: DataViewTextApi = {
72
- strings,
73
- resolve,
74
- format: (text, values) => formatDataViewString(resolve(text), values),
75
- };
76
- return <DataViewTextContext.Provider value={api}>{children}</DataViewTextContext.Provider>;
155
+ return (
156
+ <DataViewOverridesContext.Provider value={overrides}>{children}</DataViewOverridesContext.Provider>
157
+ );
77
158
  }
78
159
 
79
160
  /**