@terpjs/react-core 0.28.0 → 0.30.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.30.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.30.0"
19
19
  },
20
20
  "peerDependencies": {
21
21
  "react": "^19.0.0",
package/src/Page.test.tsx CHANGED
@@ -6,6 +6,7 @@ import { DetailPage } from "./DetailPage";
6
6
  import { OverviewPage } from "./OverviewPage";
7
7
  import { Page } from "./Page";
8
8
  import { ApiError } from "./unwrap";
9
+ import { Badge } from "./ui/Badge";
9
10
  import { Button } from "./ui/Button";
10
11
 
11
12
  afterEach(cleanup);
@@ -126,8 +127,29 @@ describe("Page", () => {
126
127
  </Page>,
127
128
  );
128
129
  const withMeta = container.querySelector('[data-terp="page-header"]');
129
- expect(withMeta?.getAttribute("data-has-meta"), "a lead line earns the row").toBe("true");
130
+ // "description" rather than a bare flag: a lead line earns the row only where it is shown,
131
+ // above the second cutover, and the sheet can only honour that if it can tell this band
132
+ // from one carrying a badge.
133
+ expect(withMeta?.getAttribute("data-has-meta"), "a lead line earns the row").toBe(
134
+ "description",
135
+ );
130
136
  expect(container.querySelector('[data-terp="page-meta"]')).not.toBeNull();
137
+
138
+ // A badge is visible at every width, so it names the kind even beside a lead line.
139
+ rerender(
140
+ <Page
141
+ title="Tasks"
142
+ badges={<Badge>Draft</Badge>}
143
+ description="A sentence."
144
+ actions={<Button>New</Button>}
145
+ >
146
+ <p>body</p>
147
+ </Page>,
148
+ );
149
+ expect(
150
+ container.querySelector('[data-terp="page-header"]')?.getAttribute("data-has-meta"),
151
+ "a badge earns the row at every width",
152
+ ).toBe("badges");
131
153
  });
132
154
 
133
155
  it("groups the action cluster even when the page passes loose nodes", () => {
package/src/Page.tsx CHANGED
@@ -185,9 +185,14 @@ export function Page({
185
185
  // shares it at no cost in height. A page with neither keeps the single row, and with it the
186
186
  // measurement the chrome is held to: the band matches the app header above it.
187
187
  const hasMeta = badgeList.length > 0 || hasDescription;
188
+ // WHICH meta, because the two are visible at different widths and the row must follow what
189
+ // is visible: badges show everywhere, a lead line only above the second cutover. A band whose
190
+ // only meta is a lead line therefore has an empty second row below that width unless the
191
+ // sheet can tell it apart, and it could not while this said "true" for both.
188
192
  // Hoisted, the density/collapsed idiom: the default stamps nothing, so the expression has a
189
193
  // branch rather than a boolean React would render as the string "false".
190
- const metaAttribute = hasMeta ? "true" : undefined;
194
+ const metaAttribute =
195
+ badgeList.length > 0 ? "badges" : hasDescription ? "description" : undefined;
191
196
  const body =
192
197
  error !== null && error !== undefined ? (
193
198
  (errorState ?? <ErrorState error={error} />)
@@ -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>
@@ -1304,7 +1304,9 @@ describe("cascade structure", () => {
1304
1304
  expect(withMeta, "rows sized to their content, so neither sits on the border").toContain(
1305
1305
  "grid-auto-rows: auto",
1306
1306
  );
1307
- // The areas move per cutover, so they are pinned in their own queries rather than here.
1307
+ // The areas move per cutover, so they are pinned in their own queries rather than here --
1308
+ // and per meta KIND, which "spends the meta row only at the widths where its meta is
1309
+ // visible" below pins.
1308
1310
  const wideMeta = mediaBodies(base, WIDE_VIEWPORT_QUERY);
1309
1311
  expect(wideMeta, "above the cutover the cluster keeps its place beside the trail").toContain(
1310
1312
  '"trail actions"',
@@ -1346,7 +1348,9 @@ describe("cascade structure", () => {
1346
1348
  expect(description, "the lead line is the first thing to go when room is short").toContain(
1347
1349
  "display: none",
1348
1350
  );
1349
- const roomy = base.indexOf(`@media ${ROOMY_VIEWPORT_QUERY}`);
1351
+ // Searched FROM the hiding rule: the meta-kind correction earlier in the band is also a
1352
+ // roomy block, and "the first roomy block in the sheet" stopped meaning this one with it.
1353
+ const roomy = base.indexOf(`@media ${ROOMY_VIEWPORT_QUERY}`, descAt);
1350
1354
  expect(roomy, "the lead line comes back above the second cutover").toBeGreaterThan(descAt);
1351
1355
  // And the truncation, which still matters on the row it does get: the sentence shares
1352
1356
  // that row with the badges, so its max-content must not decide the row's width.
@@ -1358,37 +1362,78 @@ describe("cascade structure", () => {
1358
1362
  expect(full).toContain("text-overflow: ellipsis");
1359
1363
  });
1360
1364
 
1361
- it("gives the breadcrumb trail one line box, and the leaf the step its own size needs", () => {
1365
+ it("spends the meta row only at the widths where its meta is visible", () => {
1366
+ // A lead line is hidden below the second cutover, so a band whose ONLY meta is a lead line
1367
+ // has nothing to show on a second row there. It had the row anyway: the empty meta group
1368
+ // took a track, the row gap and the multi-row padding came with it, and the band stretched
1369
+ // all of that to its floor -- measured below the first cutover, the lone title sat 6.8px
1370
+ // above the centre of a band that showed one line. Badges are visible everywhere and keep
1371
+ // their row everywhere; the lead-line kind earns it only where the lead line is shown.
1372
+ const base = layerBody("terp.base");
1373
+ const always = baseOnly(base);
1374
+ const wide = mediaBodies(base, WIDE_VIEWPORT_QUERY);
1375
+ const narrow = mediaBodies(base, NARROW_VIEWPORT);
1376
+ const roomy = mediaBodies(base, ROOMY_VIEWPORT_QUERY);
1377
+ const badges = '[data-terp="page-header"][data-has-meta="badges"]';
1378
+ const lead = '[data-terp="page-header"][data-has-meta="description"]';
1379
+
1380
+ expect(wide, "badges keep their row above the first cutover").toContain(`${badges} {`);
1381
+ expect(narrow, "and below it").toContain(`${badges} {`);
1382
+ expect(wide, "a lead line alone earns no row where it is hidden").not.toContain(lead);
1383
+ expect(narrow, "including below the first cutover").not.toContain(lead);
1384
+ expect(roomy, "the lead line's row comes back with the lead line").toContain(`${lead} {`);
1385
+
1386
+ // The empty group has to leave flow, not just sit empty: its grid-area names an area the
1387
+ // one-row template lacks, and an item placed into a missing named area gets implicit lines.
1388
+ expect(
1389
+ declaresRuleFor(always, `${lead} [data-terp="page-meta"]`),
1390
+ "the lead-line group is out of flow wherever the lead line is",
1391
+ ).toBe(true);
1392
+ expect(always).toMatch(
1393
+ /\[data-has-meta="description"\] \[data-terp="page-meta"\] \{\s*display: none;/,
1394
+ );
1395
+ expect(roomy).toMatch(
1396
+ /\[data-has-meta="description"\] \[data-terp="page-meta"\] \{\s*display: flex;/,
1397
+ );
1398
+
1399
+ // And the padding a multi-row band spends follows the same split: always for badges, only
1400
+ // above the second cutover for a lead line alone.
1401
+ expect(always.replace(/\s+/g, " ")).toContain(
1402
+ `[data-terp="page"]:not([data-measure="narrow"]) > ${badges} { padding-block: var(--space-1);`,
1403
+ );
1404
+ expect(always).not.toContain(`> ${lead} {`);
1405
+ expect(roomy.replace(/\s+/g, " ")).toContain(
1406
+ `[data-terp="page"]:not([data-measure="narrow"]) > ${lead} { padding-block: var(--space-1);`,
1407
+ );
1408
+ });
1409
+
1410
+ it("gives the breadcrumb trail one line box, leaf included", () => {
1362
1411
  // The trail is a row of items that get CENTRED, so two line heights in it are two
1363
1412
  // baselines. The leaf declared 1.3 while its ancestors inherited `normal`: measured at
1364
1413
  // font-size-sm, a 19.00px ancestor line box against an 18.19px leaf, which left the
1365
1414
  // page's own title 0.59px above the crumb it hangs off with the chevron centred on a
1366
- // third line. One declaration on the trail, inherited by every crumb, is what makes the
1367
- // ancestors share a baseline.
1415
+ // third line. One declaration on the trail, inherited by every crumb and by the h1, is
1416
+ // what makes the row share a baseline.
1368
1417
  //
1369
1418
  // The published step rather than a bare literal, and that is the second half of the fix
1370
1419
  // rather than house style: `normal` is the FONT's metric, so the mismatch was as big as
1371
1420
  // the app's typeface said it was, and an app on a webfont with taller natural leading got
1372
1421
  // a worse one than the system stack this was measured in.
1373
1422
  //
1374
- // The LEAF is now the exception, and deliberately: at xl against sm ancestors it cannot
1375
- // share their baseline whatever it declares, and the li centres it instead. That frees the
1376
- // value to do the one job only it can do here — hold the band's floor, where snug would
1377
- // cost 3.6px on every page carrying a lead line (see the rule, where the measurement is).
1378
- // So this holds it at the published tight step rather than at "absent": absent means
1379
- // inheriting the trail's snug, which is the version that grows the band.
1423
+ // 0.28.0 made the leaf the exception (xl at the tight step) and this test followed it.
1424
+ // The leaf is back at the trail's own size, so it is back on the trail's line box too.
1380
1425
  const base = layerBody("terp.base");
1381
1426
  const trail = base.slice(base.indexOf('[data-terp="breadcrumbs"] {'));
1382
1427
  expect(
1383
1428
  trail.slice(0, trail.indexOf("}")),
1384
- "the trail declares the line box every ancestor crumb shares",
1429
+ "the trail declares the line box every crumb shares",
1385
1430
  ).toContain("line-height: var(--font-line-height-snug)");
1386
1431
  const leafAt = base.indexOf('[data-terp="page-title"] {');
1387
1432
  expect(leafAt, "the trail's leaf should have a rule").toBeGreaterThan(-1);
1388
1433
  expect(
1389
1434
  base.slice(leafAt, base.indexOf("}", leafAt)),
1390
- "the leaf declares the tight step; inheriting snug is what overruns the band's floor",
1391
- ).toContain("line-height: var(--font-line-height-tight)");
1435
+ "the leaf takes the trail's line box; a second value here is the misalignment",
1436
+ ).not.toContain("line-height");
1392
1437
  });
1393
1438
 
1394
1439
  it("spans a full row across every track, and makes it a box that can", () => {
@@ -1544,16 +1589,15 @@ describe("cascade structure", () => {
1544
1589
  // one published scale rather than four sizes that happen to differ.
1545
1590
  const base = layerBody("terp.base");
1546
1591
  for (const [selector, step] of [
1547
- // page-title is back on the top step, which is where this loop found it before the band
1548
- // change demoted it to sm. At sm it tied with card-title, so the page's own name measured
1549
- // exactly as much as the name of a section on it — the flat scale this test exists to
1550
- // stop, one row further up than the version it was written for. Pinned rather than
1551
- // dropped, for the reason the band change proved: removing this marker from the loop left
1552
- // the one size the change was about free to drift.
1553
- ['[data-terp="page-title"]', "xl"],
1554
- // The top step's OTHER reader. It stopped being the thing that keeps the token read when
1555
- // page-title came back to it, and is kept for the reason it was added: a standalone
1556
- // heading asking for the masthead step should get the same size the masthead renders.
1592
+ // page-title left the TOP step when the header became a band, but it still has a step
1593
+ // and this is it: sm, the trail's own size, because the title IS the trail's leaf and a
1594
+ // 24px leaf on 14px ancestors reads as small-small-BIG rather than as one trail. Pinned
1595
+ // rather than dropped — removing it from this loop, which is what the band change first
1596
+ // did, left the one marker whose size the change was about free to drift. 0.28.0 took it
1597
+ // back to xl, and the band paid 8px of header height for it; this is that reversal.
1598
+ ['[data-terp="page-title"]', "sm"],
1599
+ // The top step keeps two readers, which is what stops the token going unread;
1600
+ // tokens.guard.test.ts holds that end.
1557
1601
  ['[data-terp="heading"][data-size="xl"]', "xl"],
1558
1602
  ['[data-terp="card-title"]', "lg"],
1559
1603
  ['[data-terp="card-description"]', "sm"],
package/src/styles.ts CHANGED
@@ -2137,12 +2137,40 @@ textarea[data-terp="input"] {
2137
2137
  to their content, plus the padding the multi-row band now spends, give 4px and 4px. */
2138
2138
  grid-auto-rows: auto;
2139
2139
  }
2140
+ /* WHICH meta decides the row, not whether there is any. Badges show at every width, so a band
2141
+ carrying one has its second row at every width. A lead line shows only above the SECOND
2142
+ cutover (see page-description below), so a band whose only meta is a lead line has nothing
2143
+ to put on that row anywhere beneath it -- and a grid row with nothing visible in it is still
2144
+ a row. It was one: the empty meta group took a track, the band's row gap and the multi-row
2145
+ band's block padding came with it, and the whole was stretched to the header floor. Measured
2146
+ below the first cutover on a hub with a lead line, the title sat 6.8px above the centre of a
2147
+ one-line band whose other line showed nothing at all.
2148
+
2149
+ So Page stamps the kind (data-has-meta="badges" or "description"), and a description-only
2150
+ band is a one-row band until the correction at the second cutover gives it its meta row --
2151
+ the same mobile-first shape the lead line itself is written in. Its meta group is taken out
2152
+ of flow there too, and not merely left empty: its grid-area names an area the one-row
2153
+ template does not declare, and an item placed into a missing named area is not dropped but
2154
+ given IMPLICIT lines, which is a new row after all. */
2155
+ [data-terp="page-header"][data-has-meta="description"] [data-terp="page-meta"] {
2156
+ display: none;
2157
+ }
2140
2158
  @media ${WIDE_VIEWPORT_QUERY} {
2141
- [data-terp="page-header"][data-has-meta] {
2159
+ [data-terp="page-header"][data-has-meta="badges"] {
2160
+ grid-template-areas:
2161
+ "trail actions"
2162
+ "meta meta";
2163
+ }
2164
+ }
2165
+ @media ${ROOMY_VIEWPORT_QUERY} {
2166
+ [data-terp="page-header"][data-has-meta="description"] {
2142
2167
  grid-template-areas:
2143
2168
  "trail actions"
2144
2169
  "meta meta";
2145
2170
  }
2171
+ [data-terp="page-header"][data-has-meta="description"] [data-terp="page-meta"] {
2172
+ display: flex;
2173
+ }
2146
2174
  }
2147
2175
  /* Below the first cutover the band is one column and nothing competes for a line. The trail
2148
2176
  keeps the leaf and one ancestor: every crumb carries min-width: 0 and an ellipsis while the
@@ -2169,13 +2197,16 @@ textarea[data-terp="input"] {
2169
2197
  }
2170
2198
  /* Written AFTER the :has() rule and not before it: the two selectors tie at (0,2,0), so
2171
2199
  source order is what decides a page that carries meta and no cluster, and it belongs to
2172
- this one. The combined selector below outranks both at (0,3,0). */
2173
- [data-terp="page-header"][data-has-meta] {
2200
+ this one. The combined selector below outranks both at (0,3,0).
2201
+
2202
+ Badges only: this whole block sits below the first cutover, where a lead line never
2203
+ shows, so a description-only band keeps the rows it would have with no meta at all. */
2204
+ [data-terp="page-header"][data-has-meta="badges"] {
2174
2205
  grid-template-areas:
2175
2206
  "trail"
2176
2207
  "meta";
2177
2208
  }
2178
- [data-terp="page-header"][data-has-meta]:has(> [data-terp="page-actions"]) {
2209
+ [data-terp="page-header"][data-has-meta="badges"]:has(> [data-terp="page-actions"]) {
2179
2210
  grid-template-areas:
2180
2211
  "trail"
2181
2212
  "meta"
@@ -2253,35 +2284,25 @@ textarea[data-terp="input"] {
2253
2284
  2em } ON the element, and a declaration on the element beats an inherited value however
2254
2285
  specific the ancestor rule is: without this the leaf renders at twice the trail.
2255
2286
 
2256
- xl, not the trail's own sm. "Heavier than its ancestors, not larger" was the rule while the
2257
- band was 3rem and the leaf had no room to be anything else, and it cost the page its name:
2258
- at sm/semibold the title measured the same as a table header, less than the action button
2259
- beside it, and exactly as much as the card titles of the sections under it — so on a hub
2260
- every HubCard outranked the page it was on. A screen whose largest type belongs to its
2261
- content is a screen with no masthead, and that reads as unfinished before any one component
2262
- does. The scale is 24 / 18 / 16 / 14 again: page title, card title, body, description.
2263
-
2264
- The one-row band still holds its floor, which is the promise this row makes and the number
2265
- to re-measure if either half moves. --shell-header-height is 3.5rem now, and xl at the TIGHT
2266
- step is 28.8px, so the title's line box sits inside 56px with room to spare: measured, a hub's
2267
- band and the app header above it are both 56.0. At the trail's snug step it would be 32.4 and
2268
- still fit, but the band that carries meta — which has broken the floor by design, and does not
2269
- make the claim — would take the extra 3.6px on every page with a lead line, so the tight step
2270
- is what keeps the two bands one apart rather than two.
2271
-
2272
- That is also the answer to the line height the trail's own rule argues for. Sharing it keeps
2273
- the leaf's glyphs on the ancestors' baseline, which mattered when leaf and ancestors were the
2274
- same size; at 24 against 14 they cannot share a baseline anyway and the li centres them, so
2275
- the value is free to do the job only it can do here.
2276
-
2277
- Tracking is the scale's tight step, which only starts earning its keep at this size: -0.02em
2278
- is 0.48px here and nothing at all at 14px, which is why the trail below does not take it. */
2287
+ Semibold at the trail's own size, which is the whole "the trail is the title" idea in one
2288
+ declaration — heavier than its ancestors, not larger.
2289
+
2290
+ This is the second time the leaf has been sm, and the first reversal is the reason to keep
2291
+ it here. 0.28.0 took it to xl so the page's name would outrank its cards, and paid for that
2292
+ in the band itself: the leaf was 24px on 14px ancestors, the small-small-BIG trail the band
2293
+ comment above warns about, and it needed --shell-header-height raised from 3rem to 3.5rem to
2294
+ fit, so every app's header grew 8px to hold a title that is chrome. The page's name is
2295
+ carried by being the trail's heaviest item and its h1, not by being its largest.
2296
+
2297
+ And no line-height of its own, which is the other half of that idea: it takes the trail's
2298
+ (see breadcrumbs, where the value and the defect are recorded). A second value here — 1.3
2299
+ against the ancestors' inherited normal — is what left the leaf's glyphs sitting 0.59px
2300
+ above the crumb they hang off, in the same font at the same size. */
2279
2301
  [data-terp="page-title"] {
2280
2302
  margin: 0;
2281
- font-size: var(--font-size-xl);
2282
- line-height: var(--font-line-height-tight);
2303
+ font-size: var(--font-size-sm);
2283
2304
  font-weight: var(--font-weight-semibold);
2284
- letter-spacing: var(--font-letter-spacing-tight);
2305
+ letter-spacing: 0;
2285
2306
  color: var(--color-neutral-900);
2286
2307
  }
2287
2308
  /* Status pills next to the title. A row of its own so a page passing several keeps them
@@ -2357,10 +2378,21 @@ textarea[data-terp="input"] {
2357
2378
  Below the cutover the same is true of a band whose cluster has taken a row of its own.
2358
2379
 
2359
2380
  The narrow rule weighs (0,3,0) plus :has()'s argument, so (0,4,0) — the same as the meta
2360
- rule, and they declare the same value, so the tie decides nothing. */
2361
- [data-terp="page"]:not([data-measure="narrow"]) > [data-terp="page-header"][data-has-meta] {
2381
+ rule, and they declare the same value, so the tie decides nothing.
2382
+
2383
+ A description-only band is multi-row only above the second cutover (see the meta-kind rule
2384
+ near the top of the band), so that is the only width it spends this padding at. Below it
2385
+ the band is one row and holds the floor like any other: spending 4px + 4px there is exactly
2386
+ what pushed a lone title off the centre of a band with nothing else in it. */
2387
+ [data-terp="page"]:not([data-measure="narrow"]) > [data-terp="page-header"][data-has-meta="badges"] {
2362
2388
  padding-block: var(--space-1);
2363
2389
  }
2390
+ @media ${ROOMY_VIEWPORT_QUERY} {
2391
+ [data-terp="page"]:not([data-measure="narrow"])
2392
+ > [data-terp="page-header"][data-has-meta="description"] {
2393
+ padding-block: var(--space-1);
2394
+ }
2395
+ }
2364
2396
  @media ${NARROW_VIEWPORT} {
2365
2397
  [data-terp="page"]:not([data-measure="narrow"])
2366
2398
  > [data-terp="page-header"]:has(> [data-terp="page-actions"]) {
@@ -148,9 +148,9 @@ const BARE_TYPE_LITERALS: Record<string, Record<string, number>> = {
148
148
  // letter-spacing on form controls, so inheritance has to be asked for explicitly — the
149
149
  // header and its button were rendering two different treatments side by side until it was.
150
150
  //
151
- // One `0` retired when page-title took --font-letter-spacing-tight: the leaf is set at lg now,
152
- // and the tight step is worth a third of a pixel there where at sm it was worth nothing.
153
- "letter-spacing": { "0": 3, "0.04em": 1, "0.06em": 1, inherit: 1 },
151
+ // Four `0`s again: page-title is back at sm, where the tight step is worth nothing, and it
152
+ // takes the trail's plain tracking as it did before 0.28.0 set it at xl.
153
+ "letter-spacing": { "0": 4, "0.04em": 1, "0.06em": 1, inherit: 1 },
154
154
  };
155
155
 
156
156
  describe("design tokens", () => {
@@ -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
  );