@terpjs/react-core 0.21.0 → 0.23.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
@@ -89,7 +89,7 @@ runtime, fail closed (ADR 0059), so every screen keeps the breadcrumb/title/erro
89
89
  | `navPlacement` (shell) | Where the primary navigation lives on desktop: `"sidebar"` (default, stamps nothing) or `"header"` — a horizontal row in the header with no sidebar at all, for an app whose destinations are few enough that 15rem of permanent chrome is a tax. The header then *becomes* the sidebar surface, so every `--color-sidebar-*` an app themes carries over and no property is overridden. Below the mobile breakpoint both placements are the drawer. `defaultCollapsed` is `never` under `"header"`: with no sidebar there is nothing to collapse. Available on `AppShell`, `buildAppRouter` and `renderTerpApp`. |
90
90
  | `contentWidth` (shell) | `"measured"` caps routed content at `--shell-content-max-width` while each page's own header keeps the full track — the subheader band. Default `"full"` stamps no attribute, so nothing moves until an app asks. Available on `AppShell`, `buildAppRouter` and `renderTerpApp`. |
91
91
  | `NavIcon`, `Icon`, `TerpMark`, `ICON_GLYPHS`, `ICON_NAMES` | The dependency-free icon layer. `ICON_NAMES` is published by `@terpjs/contract` as data and `IconName` is derived from it, so `NavItem.icon` and `Icon`'s `name` are **checked names** — a typo is a typecheck error, not a picture of nothing. `NavIcon`'s `name` stays a plain `string` on purpose: its unknown-name behaviour is a designed, visible fallback (the label's initial in a tile), while `Icon` rendered an empty box. The glyph table is held to the name set exhaustively in both directions by `satisfies`, so a glyph without a name or a name without a glyph fails to compile. The bundled catalogue covers common UI, action, object and status glyphs (home, list, folder, users, plus, edit, trash, search, check, x, chevron-{left,right,down}, arrow-left, external, logout, user, bell, key, globe, lock, tag, mail, refresh, filter, download, upload, star, heart, database, code, truck, cart, wallet, map-pin, clock, link, grid, book, briefcase, building, clipboard, layers, send, phone, image, video, music, wrench, zap, …). `TerpMark` is the placeholder brand mark until an app passes its own `logo`. |
92
- | `Page` | The base routed screen: one band carrying the breadcrumb trail — whose leaf **is** the view's single `h1` — plus `badges`, a truncated `description` lead line and the `actions` cluster, then the body with loading/error slots. Every page renders a trail, even one of a single crumb, so an overview's title sits where a detail's does. Inside a shell the band bleeds to the content column's edge and takes `--shell-header-height`; a `measure="narrow"` frame keeps the row and drops the chrome. |
92
+ | `Page` | The base routed screen: a band carrying the breadcrumb trail — whose leaf **is** the view's single `h1` — plus `badges`, a `description` lead line and the `actions` cluster, then the body with loading/error slots. The band places by grid area (ADR 0135): a page with badges or a lead line spends a second row on them and the cluster joins them there at no cost in height, which leaves the trail the whole first row; a page with neither keeps the single row. Crumbs ellipsise rather than wrap, and the lead line is shown only above the second cutover. Every page renders a trail, even one of a single crumb, so an overview's title sits where a detail's does. Inside a shell the band bleeds to the content column's edge and takes `--shell-header-height`; a `measure="narrow"` frame keeps the row and drops the chrome. |
93
93
  | `HubPage`, `HubCard` | Responsive `auto-fit` landing grid. Cards share equal outer and internal tracks even when descriptions/stats differ; nested hubs use the ordinary breadcrumb contract via `parents`. |
94
94
  | `OverviewPage` | A module's top-level listing screen (level 2); detail pages crumb back to it. |
95
95
  | `DetailPage` | One record's screen (level 3); breadcrumb trail = ancestors + record title. |
@@ -103,7 +103,7 @@ runtime, fail closed (ADR 0059), so every screen keeps the breadcrumb/title/erro
103
103
  | `useTerpNavigate` | Navigate by manifest path: `navigate({ to: "/records/:recordId", params: { recordId } })`. An undeclared path is a typecheck error and a parameterised route requires its params — a typo'd path used to be a dead link that shipped green. Takes the manifest's `:id` spelling and translates to the router's `$id`. |
104
104
  | `useRouteSearch` | Read a declared route's query-string keys, typed: `const { status, page } = useRouteSearch("/records")` (ADR 0096). Every value is `string | undefined`, and an undeclared key is a typecheck error — so a filtered list screen stays inside the checked seam instead of reaching for the router's own `useSearch`. Declare them in the manifest: `search: ["status", "page"]`. |
105
105
  | `ModuleNav` | Secondary horizontal tabs for intra-module sub-pages (real routes, not state). |
106
- | `PageActions` | Primary action + overflow menu for a page header. |
106
+ | `PageActions` | The page header's action cluster: `primary`, `secondary` nodes, `secondaryActions` descriptors and an `overflow` menu. The cluster follows the viewport — supporting actions drop to icons alone in the middle region and fold into the overflow menu below the first cutover — while the primary action keeps its label at every width. Only `secondaryActions` can follow the viewport: a `secondary` node's label is inside the caller's tree and can only be shown or hidden. |
107
107
 
108
108
  ### Typed route paths and params (generated, ADR 0092)
109
109
 
@@ -187,6 +187,8 @@ marker, counted by the escape-hatch budget.
187
187
  | `useRecord` | The singleton counterpart of `useResource` — the one record a detail screen shows: `item` (or `null`) + loading/error + reload + mutate. Deletes the one-element-list wart (`list: async () => [unwrap(…)]` then `items[0]`). |
188
188
  | `useRealtimeChannel` | The sanctioned typed SSE/WebSocket seam for the optional realtime capability: mints a short-lived one-use ticket via the authenticated generated client, validates every inbound JSON payload with the channel's runtime type guard, and exposes connection state / last message / WebSocket send. App modules never touch raw transports. |
189
189
  | `ResourceList` | The standard simple CRUD list screen: titled section, write-gated create form, loading/error/empty states. Composable — screens needing more render their own React. |
190
+ | `routeFieldErrors` | Split a failure's `fields` into the ones this form renders (`shown`, ready for `Field`'s `error`) and whether anything was `leftover`. The branch that matters is `leftover`: a reason naming a field the form has no input for would otherwise set state nobody reads and suppress the toast on the way out, so the user presses Save and *nothing at all* happens. |
191
+ | `randomUuid` | A cryptographically random v4 UUID in every context. `crypto.randomUUID` is secure-context-only while `lib.dom` declares it unconditionally, so calling it on a plain-http origin is a synchronous `TypeError` that type-checks cleanly and never fires on localhost. Falls back to `crypto.getRandomValues` (not secure-context-gated) for the same entropy, and throws rather than reaching for `Math.random`. Reach for it wherever the client mints an id -- an `Idempotency-Key`, an optimistic row key. |
190
192
  | `unwrap`, `unwrapOptional`, `ApiError` | Turn a generated-client result into data-or-throw; `ApiError` carries the envelope's `code` / `status` / `requestId`, plus `fields` — the per-field reasons of a 422, keyed by dotted path, ready to hand to `Field`'s `error` prop (`{}` when the failure names no field). `unwrapOptional` returns `null` on a 404 instead — for resources whose absence is a normal state (a `/latest` snapshot not yet published), the client-side analog of `BaseService.find` beside `get`. |
191
193
  | `useFormatDate`, `useFormatDateTime`, `useFormatNumber` (and locale-explicit `formatDate` / `formatDateTime` / `formatNumber`) | Render a date or a number in the **app's** locale. `toLocaleDateString()` with no argument asks the browser, so an app shipping one language renders its own tables in whatever the visitor's OS is set to. The hooks read `LocaleProvider` and are `useCallback`-stable, so a column list built in a `useMemo` can depend on one. An absent or unparseable value renders as an em dash rather than throwing. |
192
194
  | `FileUpload`, `useFileDownload` | The files-capability surface (ADR 0056/0057): a token-styled attachment picker that uploads through the typed client, and an authenticated download helper (a raw `<a href>` would carry no bearer token). |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terpjs/react-core",
3
- "version": "0.21.0",
3
+ "version": "0.23.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": {
@@ -13,8 +13,8 @@
13
13
  "test": "vitest run"
14
14
  },
15
15
  "dependencies": {
16
- "@tanstack/react-router": "^1.170.32",
17
- "@terpjs/contract": "^0.21.0"
16
+ "@tanstack/react-router": "^1.170.35",
17
+ "@terpjs/contract": "^0.23.0"
18
18
  },
19
19
  "peerDependencies": {
20
20
  "react": "^19.0.0",
@@ -23,14 +23,14 @@
23
23
  "devDependencies": {
24
24
  "@testing-library/jest-dom": "^7.0.1",
25
25
  "@testing-library/react": "^16.3.3",
26
- "@types/react": "^19.2.18",
27
- "@types/react-dom": "^19.2.7",
26
+ "@types/react": "^19.3.0",
27
+ "@types/react-dom": "^19.3.0",
28
28
  "@vitejs/plugin-react": "^6.1.1",
29
29
  "jsdom": "^30.0.1",
30
- "react": "^19.2.7",
31
- "react-dom": "^19.2.7",
30
+ "react": "^19.3.0",
31
+ "react-dom": "^19.3.0",
32
32
  "typescript": "^5.9.3",
33
- "vite": "^8.2.2",
33
+ "vite": "^8.3.0",
34
34
  "vitest": "^5.0.0"
35
35
  },
36
36
  "license": "Apache-2.0",
package/src/Page.test.tsx CHANGED
@@ -106,6 +106,65 @@ describe("Page", () => {
106
106
  expect(bare.container.querySelector('[data-terp="page-description"]')).toBeNull();
107
107
  });
108
108
 
109
+ it("earns its second row only when there is meta to put on it", () => {
110
+ // The conditional half of ADR 0135. A page with badges or a lead line already spends a
111
+ // row on them, so the action cluster joining them costs no height; a page with neither
112
+ // keeps the single row and the measurement the chrome is held to. Both directions are
113
+ // asserted, because the attribute deciding the grid template is the whole mechanism.
114
+ const { container, rerender } = render(
115
+ <Page title="Tasks" actions={<Button>New</Button>}>
116
+ <p>body</p>
117
+ </Page>,
118
+ );
119
+ const bare = container.querySelector('[data-terp="page-header"]');
120
+ expect(bare?.hasAttribute("data-has-meta"), "nothing to show, so no second row").toBe(false);
121
+ expect(container.querySelector('[data-terp="page-meta"]'), "no empty group").toBeNull();
122
+
123
+ rerender(
124
+ <Page title="Tasks" description="A sentence." actions={<Button>New</Button>}>
125
+ <p>body</p>
126
+ </Page>,
127
+ );
128
+ const withMeta = container.querySelector('[data-terp="page-header"]');
129
+ expect(withMeta?.getAttribute("data-has-meta"), "a lead line earns the row").toBe("true");
130
+ expect(container.querySelector('[data-terp="page-meta"]')).not.toBeNull();
131
+ });
132
+
133
+ it("groups the action cluster even when the page passes loose nodes", () => {
134
+ // A page that passed a fragment used to put each button in the band as its own item,
135
+ // which the grid would scatter across cells it has no areas for. The wrapper is Page's,
136
+ // not PageActions', so it holds whether or not the page reached for that component.
137
+ const { container } = render(
138
+ <Page
139
+ title="Tasks"
140
+ actions={
141
+ <>
142
+ <Button>Discard</Button>
143
+ <Button>Publish</Button>
144
+ </>
145
+ }
146
+ >
147
+ <p>body</p>
148
+ </Page>,
149
+ );
150
+ const header = container.querySelector('[data-terp="page-header"]');
151
+ const cluster = container.querySelector('[data-terp="page-actions"]');
152
+ expect(cluster, "the cluster is always a group").not.toBeNull();
153
+ expect(cluster?.parentElement).toBe(header);
154
+ expect(cluster?.querySelectorAll("button")).toHaveLength(2);
155
+ // And the buttons are NOT direct children of the band, which is the failure this prevents.
156
+ expect(header?.querySelectorAll(':scope > button')).toHaveLength(0);
157
+ });
158
+
159
+ it("renders no cluster box at all when the page passes no actions", () => {
160
+ const { container } = render(
161
+ <Page title="Tasks">
162
+ <p>body</p>
163
+ </Page>,
164
+ );
165
+ expect(container.querySelector('[data-terp="page-actions"]')).toBeNull();
166
+ });
167
+
109
168
  it("takes several badges as one row, not one row each", () => {
110
169
  const { container } = render(
111
170
  <Page title="Fix the door" badges={[<span key="a">Open</span>, <span key="b">Urgent</span>]}>
package/src/Page.tsx CHANGED
@@ -175,11 +175,19 @@ export function Page({
175
175
  .concat(badges ?? [])
176
176
  .filter((badge) => badge !== false && badge !== null && badge !== undefined && badge !== "");
177
177
  // Same test for the lead line, for the same reason: `description={error && error.message}`.
178
+ const hasActions = actions !== undefined && actions !== null && actions !== false;
178
179
  const hasDescription =
179
180
  description !== undefined &&
180
181
  description !== null &&
181
182
  description !== false &&
182
183
  description !== "";
184
+ // The band's second row exists when there is meta to put on it, and the action cluster then
185
+ // shares it at no cost in height. A page with neither keeps the single row, and with it the
186
+ // measurement the chrome is held to: the band matches the app header above it.
187
+ const hasMeta = badgeList.length > 0 || hasDescription;
188
+ // Hoisted, the density/collapsed idiom: the default stamps nothing, so the expression has a
189
+ // branch rather than a boolean React would render as the string "false".
190
+ const metaAttribute = hasMeta ? "true" : undefined;
183
191
  const body =
184
192
  error !== null && error !== undefined ? (
185
193
  (errorState ?? <ErrorState error={error} />)
@@ -200,24 +208,37 @@ export function Page({
200
208
  additive; the tag is load-bearing. For the same reason the body below takes no
201
209
  wrapper of its own — not even a display: contents one, since article.children is a
202
210
  DOM traversal and would see it. */}
203
- <header data-terp="page-header">
211
+ <header data-terp="page-header" data-has-meta={metaAttribute}>
204
212
  <div data-terp="page-heading">
205
213
  {/* The trail carries the h1 as its leaf. No wrapper of its own any more: the crumb
206
214
  row it used to sit in existed to hold a 2rem floor above the title row, and
207
215
  there is no title row to be above. */}
208
216
  <Breadcrumbs items={trail} renderLink={renderLink} currentAs="h1" />
209
- {badgeList.length > 0 && (
210
- <div data-terp="page-badges">
211
- {badgeList.map((badge, index) => (
212
- <Fragment key={index}>{badge}</Fragment>
213
- ))}
217
+ {/* Badges and the lead line travel together as one grid item: with meta present
218
+ they share the band's second row with the action cluster, and a group is what
219
+ lets them be left of it rather than competing for the same cells. Rendered only
220
+ when there is something in it, because the empty box would still take a row. */}
221
+ {hasMeta && (
222
+ <div data-terp="page-meta">
223
+ {badgeList.length > 0 && (
224
+ <div data-terp="page-badges">
225
+ {badgeList.map((badge, index) => (
226
+ <Fragment key={index}>{badge}</Fragment>
227
+ ))}
228
+ </div>
229
+ )}
230
+ {hasDescription && (
231
+ <p data-terp="page-description">{resolveUiTextNode(description, resolve)}</p>
232
+ )}
214
233
  </div>
215
234
  )}
216
- {hasDescription && (
217
- <p data-terp="page-description">{resolveUiTextNode(description, resolve)}</p>
218
- )}
219
235
  </div>
220
- {actions}
236
+ {/* Always a group, never the caller's nodes loose in the band. A page that passed a
237
+ fragment of buttons used to put each one in the band as its own item, which the
238
+ grid would now scatter across cells it has no areas for. One wrapper means the
239
+ cluster is one item wherever the areas put it, whether or not the page reached
240
+ for PageActions. */}
241
+ {hasActions && <div data-terp="page-actions">{actions}</div>}
221
242
  </header>
222
243
  {/* Reset the slot for the body's own subtree, so nested content is never judged
223
244
  by an ancestor archetype's slot. */}
@@ -8,6 +8,35 @@ import { UiTextProvider } from "./uiText";
8
8
 
9
9
  afterEach(cleanup);
10
10
 
11
+ /**
12
+ * Put the cluster in one of its three regions.
13
+ *
14
+ * `readDensity` asks NARROW first and MEDIUM second, so the stub answers per query rather than
15
+ * with one boolean: a width in the middle region matches MEDIUM and not NARROW, and that pair
16
+ * is the only thing separating icons from a menu.
17
+ */
18
+ function stubRegion(region: "narrow" | "medium" | "roomy") {
19
+ vi.stubGlobal(
20
+ "matchMedia",
21
+ vi.fn().mockImplementation((query: string) => ({
22
+ matches:
23
+ query === "(max-width: 768px)"
24
+ ? region === "narrow"
25
+ : query === "(max-width: 1024px)"
26
+ ? region !== "roomy"
27
+ : false,
28
+ addEventListener: vi.fn(),
29
+ removeEventListener: vi.fn(),
30
+ })),
31
+ );
32
+ }
33
+
34
+ // A text-free icon on purpose: the icon-only assertion below is that the BOX carries no
35
+ // text, and a glyph that is itself text would satisfy it for the wrong reason.
36
+ const SUPPORTING = [
37
+ { label: "Discard", icon: <svg aria-hidden="true" focusable={false} />, onSelect: () => {} },
38
+ ];
39
+
11
40
  describe("PageActions", () => {
12
41
  it("returns no wrapper when no actions are supplied", () => {
13
42
  const { container } = render(<PageActions />);
@@ -92,6 +121,50 @@ describe("PageActions", () => {
92
121
  expect(screen.queryByRole("menu")).not.toBeInTheDocument();
93
122
  });
94
123
 
124
+ it("shows supporting actions as labelled buttons above the second cutover", () => {
125
+ stubRegion("roomy");
126
+ render(<PageActions primary={<Button>Publish</Button>} secondaryActions={SUPPORTING} />);
127
+ expect(screen.getByRole("button", { name: "Discard" })).toHaveTextContent("Discard");
128
+ expect(screen.queryByRole("button", { name: "More actions" })).toBeNull();
129
+ });
130
+
131
+ it("drops supporting actions to icons alone in the middle region, keeping their names", () => {
132
+ stubRegion("medium");
133
+ render(<PageActions primary={<Button>Publish</Button>} secondaryActions={SUPPORTING} />);
134
+ const discard = screen.getByRole("button", { name: "Discard" });
135
+ // The label moves to the accessible name rather than being dropped: the control has to
136
+ // read the same to a screen reader at every width, which is the whole cost of an icon.
137
+ expect(discard).toHaveTextContent("");
138
+ expect(discard).toHaveAttribute("title", "Discard");
139
+ // Still a button, not a menu — the fold happens at the FIRST cutover, not this one.
140
+ expect(screen.queryByRole("button", { name: "More actions" })).toBeNull();
141
+ });
142
+
143
+ it("folds supporting actions into the menu below the first cutover", () => {
144
+ stubRegion("narrow");
145
+ render(
146
+ <PageActions
147
+ primary={<Button>Publish</Button>}
148
+ secondaryActions={SUPPORTING}
149
+ overflow={[{ label: "Delete", variant: "destructive", onSelect: () => {} }]}
150
+ />,
151
+ );
152
+ // Gone from the band...
153
+ expect(screen.queryByRole("button", { name: "Discard" })).toBeNull();
154
+ // ...and present in the menu, above the page's own rare items.
155
+ fireEvent.click(screen.getByRole("button", { name: "More actions" }));
156
+ const items = screen.getAllByRole("menuitem").map((item) => item.textContent);
157
+ expect(items).toEqual(["Discard", "Delete"]);
158
+ });
159
+
160
+ it("keeps the primary action labelled at every width", () => {
161
+ // The decision ADR 0135 records: everything around the primary gives way, the primary
162
+ // never does. Asserted in the narrowest region, where the pressure to fold it is highest.
163
+ stubRegion("narrow");
164
+ render(<PageActions primary={<Button>Publish</Button>} secondaryActions={SUPPORTING} />);
165
+ expect(screen.getByRole("button", { name: "Publish" })).toHaveTextContent("Publish");
166
+ });
167
+
95
168
  it("localises the overflow trigger label", () => {
96
169
  render(
97
170
  <UiTextProvider strings={{ moreActions: "Meer acties" }}>
@@ -1,8 +1,11 @@
1
+ import { useEffect, useState } from "react";
1
2
  import type { ReactNode } from "react";
2
3
 
4
+ import { MEDIUM_VIEWPORT, NARROW_VIEWPORT } from "./breakpoints";
3
5
  import { injectTerpStyles } from "./styles";
6
+ import { Button } from "./ui/Button";
4
7
  import { Menu, MenuItem } from "./ui/Menu";
5
- import { useStrings } from "./uiText";
8
+ import { useStrings, useUiText } from "./uiText";
6
9
  import type { UiText } from "./uiText";
7
10
 
8
11
  injectTerpStyles();
@@ -23,29 +26,116 @@ export interface PageActionsProps {
23
26
  primary?: ReactNode;
24
27
  /** Supporting action(s), supplied by the page as styled element(s). */
25
28
  secondary?: ReactNode;
29
+ /**
30
+ * Supporting actions as DESCRIPTIONS rather than elements, which is what lets the cluster
31
+ * change form with the viewport: a label and an icon can be a button, an icon alone, or a
32
+ * line in a menu, and the same tuple renders all three. An element cannot — by the time a
33
+ * caller hands over a `<Button>` the label is inside someone else's tree, so `secondary`
34
+ * below can only ever be shown or hidden.
35
+ *
36
+ * Prefer this over `secondary` for anything that should survive a narrow viewport.
37
+ */
38
+ secondaryActions?: readonly OverflowAction[];
26
39
  /** Rare or destructive actions, kept out of the primary click path. */
27
40
  overflow?: readonly OverflowAction[];
28
41
  className?: string;
29
42
  }
30
43
 
31
- /** Standard right-aligned action cluster for page headers. */
32
- export function PageActions({ primary, secondary, overflow, className }: PageActionsProps) {
44
+ /**
45
+ * Which form the supporting actions take at this width.
46
+ *
47
+ * Read from the two cutovers rather than one: `labels` above the second, `icons` in the middle
48
+ * region, `menu` below the first. The regions come out of asking NARROW first and MEDIUM
49
+ * second — see ./breakpoints for why that is two queries and not three.
50
+ *
51
+ * `labels` is also the answer with no `window` at all, so a server render and a first paint
52
+ * agree on the widest form and hydration only ever takes things away.
53
+ */
54
+ type ActionDensity = "labels" | "icons" | "menu";
55
+
56
+ function readDensity(): ActionDensity {
57
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
58
+ return "labels";
59
+ }
60
+ if (window.matchMedia(NARROW_VIEWPORT).matches) {
61
+ return "menu";
62
+ }
63
+ if (window.matchMedia(MEDIUM_VIEWPORT).matches) {
64
+ return "icons";
65
+ }
66
+ return "labels";
67
+ }
68
+
69
+ function useActionDensity(): ActionDensity {
70
+ const [density, setDensity] = useState(readDensity);
71
+ useEffect(() => {
72
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
73
+ return;
74
+ }
75
+ // Both cutovers, because a drag across the middle region crosses one of them without
76
+ // touching the other and the cluster has to change form either way.
77
+ const narrow = window.matchMedia(NARROW_VIEWPORT);
78
+ const medium = window.matchMedia(MEDIUM_VIEWPORT);
79
+ const onChange = () => setDensity(readDensity());
80
+ narrow.addEventListener("change", onChange);
81
+ medium.addEventListener("change", onChange);
82
+ return () => {
83
+ narrow.removeEventListener("change", onChange);
84
+ medium.removeEventListener("change", onChange);
85
+ };
86
+ }, []);
87
+ return density;
88
+ }
89
+
90
+ function actionKey(action: OverflowAction): string {
91
+ return typeof action.label === "string" ? action.label : action.label.id;
92
+ }
93
+
94
+ /**
95
+ * Standard right-aligned action cluster for page headers.
96
+ *
97
+ * The primary action keeps its label at every width, and that is a decision rather than an
98
+ * oversight: it is the one thing the page is for, and a glyph or a menu line makes the main
99
+ * act of the screen a guess or a second tap. Everything around it gives way instead —
100
+ * `secondaryActions` drop to icons in the middle region and fold into the overflow menu below
101
+ * the first cutover, where they sit above the page's own rare and destructive items.
102
+ */
103
+ export function PageActions({
104
+ primary,
105
+ secondary,
106
+ secondaryActions,
107
+ overflow,
108
+ className,
109
+ }: PageActionsProps) {
33
110
  const strings = useStrings();
34
- const hasOverflow = overflow !== undefined && overflow.length > 0;
111
+ const resolve = useUiText();
112
+ const density = useActionDensity();
113
+ const supporting = secondaryActions ?? [];
114
+ const rare = overflow ?? [];
115
+ // Below the first cutover the supporting actions stop being buttons and become the top of
116
+ // the menu. Order is deliberate: what the page offers first, then what it keeps back.
117
+ const inMenu = density === "menu" ? [...supporting, ...rare] : rare;
118
+ const asButtons = density === "menu" ? [] : supporting;
119
+ const hasMenu = inMenu.length > 0;
35
120
 
36
- if (primary === undefined && secondary === undefined && !hasOverflow) {
121
+ if (
122
+ primary === undefined &&
123
+ secondary === undefined &&
124
+ supporting.length === 0 &&
125
+ rare.length === 0
126
+ ) {
37
127
  return null;
38
128
  }
39
129
 
40
130
  return (
41
131
  <div className={className} data-terp="page-actions">
42
- {hasOverflow && (
132
+ {hasMenu && (
43
133
  <Menu trigger="⋯" triggerLabel={strings.moreActions}>
44
134
  {({ close }) => (
45
135
  <>
46
- {overflow.map((action) => (
136
+ {inMenu.map((action) => (
47
137
  <MenuItem
48
- key={typeof action.label === "string" ? action.label : action.label.id}
138
+ key={actionKey(action)}
49
139
  label={action.label}
50
140
  icon={action.icon}
51
141
  destructive={action.variant === "destructive"}
@@ -60,6 +150,33 @@ export function PageActions({ primary, secondary, overflow, className }: PageAct
60
150
  )}
61
151
  </Menu>
62
152
  )}
153
+ {asButtons.map((action) => {
154
+ const label = resolve(action.label);
155
+ // Icon-only still has to SAY what it is: the label moves from the box to the
156
+ // accessible name and the tooltip rather than being dropped, so the control reads the
157
+ // same to a screen reader at every width and hovers legibly for everyone else.
158
+ return density === "icons" && action.icon !== undefined ? (
159
+ <Button
160
+ key={actionKey(action)}
161
+ variant={action.variant === "destructive" ? "danger" : "secondary"}
162
+ icon={action.icon}
163
+ aria-label={label}
164
+ title={label}
165
+ disabled={action.disabled}
166
+ onClick={action.onSelect}
167
+ />
168
+ ) : (
169
+ <Button
170
+ key={actionKey(action)}
171
+ variant={action.variant === "destructive" ? "danger" : "secondary"}
172
+ icon={action.icon}
173
+ disabled={action.disabled}
174
+ onClick={action.onSelect}
175
+ >
176
+ {label}
177
+ </Button>
178
+ );
179
+ })}
63
180
  {secondary}
64
181
  {primary}
65
182
  </div>
@@ -15,7 +15,7 @@ import { useStrings } from "../uiText";
15
15
  import { unwrap } from "../unwrap";
16
16
 
17
17
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
18
- import { routeFieldErrors } from "./fieldErrors";
18
+ import { routeFieldErrors } from "../fieldErrors";
19
19
 
20
20
  const FORM_ID = "terp-admin-group-create";
21
21
 
@@ -16,7 +16,7 @@ import { useStrings } from "../uiText";
16
16
  import { unwrap } from "../unwrap";
17
17
 
18
18
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
19
- import { routeFieldErrors } from "./fieldErrors";
19
+ import { routeFieldErrors } from "../fieldErrors";
20
20
  import { lowestRank } from "./roles";
21
21
  import { useAccessLadder } from "./useAccessLadder";
22
22
 
@@ -1,41 +1,70 @@
1
1
  /**
2
- * The one viewport cutover the framework has, in the one place it is written.
2
+ * The viewport cutovers the framework has, in the one place they are written.
3
3
  *
4
- * It was written in three: `AppShell` and `DataView` each declared
4
+ * They were written in three: `AppShell` and `DataView` each declared
5
5
  * `const MOBILE_BREAKPOINT = "(max-width: 768px)"` verbatim — the duplication the diagnosis
6
6
  * named — and the responsive `Stack` props would have made a third copy, this time in the
7
7
  * stylesheet where the first two could not see it.
8
8
  *
9
- * ## Why the value is a literal and not `var(--breakpoint-md)`
9
+ * ## Why the values are literals and not `var(--breakpoint-md)`
10
10
  *
11
- * The contract publishes `--breakpoint-md: 768px`, and neither consumer can read it. CSS
12
- * forbids a custom property in a media-query condition, and `matchMedia` takes a string, so
13
- * a component would have to resolve the property off `document.documentElement` at runtime —
14
- * which is a layout read on every mount, breaks under SSR where there is no document, and
15
- * turns a static query into a value that can change after first paint.
11
+ * The contract publishes `--breakpoint-md: 768px` and `--breakpoint-lg: 1024px`, and neither
12
+ * consumer can read them. CSS forbids a custom property in a media-query condition, and
13
+ * `matchMedia` takes a string, so a component would have to resolve the property off
14
+ * `document.documentElement` at runtime — which is a layout read on every mount, breaks under
15
+ * SSR where there is no document, and turns a static query into a value that can change after
16
+ * first paint.
16
17
  *
17
- * So the literal stays, and the drift it invites is gated instead:
18
- * `styles.test.ts` reads `--breakpoint-md` out of the contract's token sheet and refuses a
19
- * mismatch here or in the stylesheet. The token remains the published source of truth about
20
- * what the number IS; this module is the single place it is spelled for use.
18
+ * So the literals stay, and the drift they invite is gated instead:
19
+ * `tokens.guard.test.ts` reads `--breakpoint-md` and `--breakpoint-lg` out of the contract's
20
+ * token sheet and refuses a mismatch here or in the stylesheet. The tokens remain the
21
+ * published source of truth about what the numbers ARE; this module is the single place they
22
+ * are spelled for use.
21
23
  *
22
- * ## Why WIDE is a negation
24
+ * ## Why WIDE and ROOMY are negations
23
25
  *
24
- * `NARROW` and `WIDE` have to partition the viewport exactly: a width that satisfies both
26
+ * A cutover's two sides have to partition the viewport exactly: a width that satisfied both
25
27
  * would render the shell's drawer beside a row-direction toolbar, and a width satisfying
26
28
  * neither would render nothing at all. Two independent queries cannot guarantee that — the
27
29
  * conventional pairing is `max-width: 767.98px` with `min-width: 768px`, which works but
28
30
  * makes the partition depend on an epsilon somebody chose, and picking one here would also
29
31
  * have moved the shell's existing behaviour at exactly 768px.
30
32
  *
31
- * `not all and (max-width: 768px)` is the complement of `NARROW` by construction. The
33
+ * `not all and (max-width: N)` is the complement of `(max-width: N)` by construction. The
32
34
  * `not all and` spelling rather than the shorter `not (…)` because it is the form every
33
35
  * browser has supported since media queries existed, and this is a stylesheet a consumer
34
36
  * cannot patch.
37
+ *
38
+ * ## Why two cutovers still make no third query
39
+ *
40
+ * The page band wants three regions, not two: below 768 it drops its lead line and folds its
41
+ * action cluster to a menu, between 768 and 1024 it keeps the cluster but shows icons alone,
42
+ * and above 1024 it shows everything. The obvious spelling of a middle region is an
43
+ * `and` of a min and a max — which reintroduces exactly the epsilon the cutover above refuses,
44
+ * and, worse, needs a negation nested inside an `and` that Media Queries 3 has no syntax for.
45
+ *
46
+ * So the regions are not three queries; they are two cutovers applied in cascade order. A rule
47
+ * block writes the narrow case unconditionally, `WIDE_VIEWPORT_QUERY` corrects it for
48
+ * everything above the first cutover, and `ROOMY_VIEWPORT_QUERY` corrects it again for
49
+ * everything above the second. The middle region is what the first correction leaves standing
50
+ * when the second does not apply — never named, never queried, and therefore never able to
51
+ * disagree with its neighbours about who owns 768px or 1024px.
52
+ *
53
+ * `matchMedia` callers get the same shape from the other end: a component asks `NARROW` first
54
+ * and `MEDIUM` second, and the first match wins.
35
55
  */
36
56
 
37
57
  /** The condition both narrow-viewport components match on (`matchMedia`, so no `@media`). */
38
58
  export const NARROW_VIEWPORT = "(max-width: 768px)";
39
59
 
40
- /** The stylesheet's complement of {@link NARROW_VIEWPORT} — everything above the cutover. */
60
+ /** The stylesheet's complement of {@link NARROW_VIEWPORT} — everything above the first cutover. */
41
61
  export const WIDE_VIEWPORT_QUERY = "not all and (max-width: 768px)";
62
+
63
+ /**
64
+ * At or below the second cutover — narrow AND the middle region together. Asked after
65
+ * {@link NARROW_VIEWPORT}, so a match that is not already narrow IS the middle region.
66
+ */
67
+ export const MEDIUM_VIEWPORT = "(max-width: 1024px)";
68
+
69
+ /** The stylesheet's complement of {@link MEDIUM_VIEWPORT} — everything above the second cutover. */
70
+ export const ROOMY_VIEWPORT_QUERY = "not all and (max-width: 1024px)";
@@ -47,6 +47,33 @@ describe("DataView states", () => {
47
47
  expect(screen.getByText("1–4 of 4 results")).toBeInTheDocument();
48
48
  });
49
49
 
50
+ it("states no count while the total is unknown, rather than zero", async () => {
51
+ // The defect: the footer computed its range from a totalCount that started at 0, so a
52
+ // fresh view asserted "0–0 of 0 results" directly underneath its own loading skeleton.
53
+ // A count is a fact, and that one was both unasked-for and usually wrong.
54
+ render(<DataView repository={inMemoryRepo()} columns={COLUMNS} />);
55
+ expect(screen.getByRole("status", { name: "Loading…" })).toBeInTheDocument();
56
+ expect(screen.queryByText(/results/)).not.toBeInTheDocument();
57
+ expect(screen.queryByText(/0.*of.*0/)).not.toBeInTheDocument();
58
+ // ... and the real count still arrives.
59
+ expect(await screen.findByText("1–4 of 4 results")).toBeInTheDocument();
60
+ });
61
+
62
+ it("says no count when the query failed either, having none to report", async () => {
63
+ // A failed refetch knows nothing about how many rows match now. Carrying the previous
64
+ // number over, or falling back to zero, both present a guess as an answer.
65
+ const failing: DataViewRepository<Ticket> = {
66
+ capabilities: inMemoryRepo().capabilities,
67
+ getRowId: (t) => t.id,
68
+ query: () => Promise.reject(new Error("upstream is down")),
69
+ };
70
+ render(<DataView repository={failing} columns={COLUMNS} />);
71
+ await waitFor(() =>
72
+ expect(screen.queryByRole("status", { name: "Loading…" })).not.toBeInTheDocument(),
73
+ );
74
+ expect(screen.queryByText(/results/)).not.toBeInTheDocument();
75
+ });
76
+
50
77
  it("shows the empty state with the emptyActions slot", async () => {
51
78
  render(
52
79
  <DataView
@@ -208,7 +208,12 @@ function DataViewInner<T>(props: DataViewProps<T>) {
208
208
  // last valid page, so the emitted query and the footer never disagree.
209
209
  const setPagination = state.setPagination;
210
210
  useEffect(() => {
211
- if (isLoading || isFetching || (error !== null && error !== undefined)) {
211
+ if (
212
+ isLoading ||
213
+ isFetching ||
214
+ (error !== null && error !== undefined) ||
215
+ totalCount === undefined
216
+ ) {
212
217
  return;
213
218
  }
214
219
  const { pageIndex, pageSize } = query.pagination;
@@ -425,10 +430,10 @@ function DataViewInner<T>(props: DataViewProps<T>) {
425
430
  hasActiveFilters={hasActiveFilters}
426
431
  layout={layout}
427
432
  selectedCount={selectedIds.size}
428
- totalCount={totalCount}
433
+ totalCount={totalCount ?? 0}
429
434
  selectAllAcrossPages={selectAllAcrossPages}
430
435
  onSelectAllAcrossPages={
431
- allPageSelected && totalCount > selectedIds.size
436
+ allPageSelected && (totalCount ?? 0) > selectedIds.size
432
437
  ? () => setSelectAllAcrossPages(true)
433
438
  : undefined
434
439
  }
@@ -471,10 +476,10 @@ function DataViewInner<T>(props: DataViewProps<T>) {
471
476
  state.setPagination({ pageIndex: 0, pageSize })
472
477
  }
473
478
  selectedCount={selectedIds.size}
474
- totalCount={totalCount}
479
+ totalCount={totalCount ?? 0}
475
480
  selectAllAcrossPages={selectAllAcrossPages}
476
481
  onSelectAllAcrossPages={
477
- allPageSelected && totalCount > selectedIds.size
482
+ allPageSelected && (totalCount ?? 0) > selectedIds.size
478
483
  ? () => setSelectAllAcrossPages(true)
479
484
  : undefined
480
485
  }