@terpjs/react-core 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +35 -14
  2. package/package.json +5 -5
  3. package/src/DashboardPage.tsx +34 -0
  4. package/src/Field.test.tsx +26 -1
  5. package/src/Field.tsx +15 -5
  6. package/src/HubPage.tsx +7 -2
  7. package/src/Page.test.tsx +192 -0
  8. package/src/Page.tsx +141 -55
  9. package/src/PageActions.test.tsx +64 -3
  10. package/src/PageActions.tsx +40 -15
  11. package/src/PageSequence.tsx +114 -0
  12. package/src/Stat.test.tsx +341 -0
  13. package/src/Stat.tsx +314 -0
  14. package/src/Timeline.test.tsx +74 -0
  15. package/src/Timeline.tsx +71 -0
  16. package/src/admin/AdminHub.tsx +11 -3
  17. package/src/admin/AuditLogAdmin.tsx +3 -1
  18. package/src/admin/GroupCreate.tsx +3 -1
  19. package/src/admin/GroupDetail.tsx +72 -67
  20. package/src/admin/GroupsAdmin.tsx +3 -1
  21. package/src/admin/ModuleAccessPanel.tsx +13 -12
  22. package/src/admin/RecordHistory.tsx +83 -0
  23. package/src/admin/UserCreate.tsx +3 -1
  24. package/src/admin/UserDetail.tsx +8 -1
  25. package/src/admin/UsersAdmin.tsx +3 -0
  26. package/src/admin/admin.test.tsx +208 -5
  27. package/src/bootstrap.test.tsx +31 -7
  28. package/src/bootstrap.tsx +30 -4
  29. package/src/charts/BarChart.tsx +74 -0
  30. package/src/charts/ProportionBar.tsx +118 -0
  31. package/src/charts/StatusHistory.tsx +75 -0
  32. package/src/charts/TrendChart.tsx +232 -0
  33. package/src/charts/charts.test.tsx +409 -0
  34. package/src/charts/scale.ts +103 -0
  35. package/src/dataview/DataView.test.tsx +255 -0
  36. package/src/dataview/DataView.tsx +35 -0
  37. package/src/dataview/DataViewCardList.tsx +21 -13
  38. package/src/dataview/DataViewTable.tsx +5 -6
  39. package/src/dataview/README.md +18 -0
  40. package/src/dataview/index.ts +1 -0
  41. package/src/dataview/internal.tsx +112 -5
  42. package/src/dataview/types.ts +39 -10
  43. package/src/errorMessages.test.tsx +17 -0
  44. package/src/errorMessages.tsx +18 -0
  45. package/src/format.ts +15 -0
  46. package/src/index.ts +24 -1
  47. package/src/layout.manifest.json +2 -9
  48. package/src/layout.manifest.test.ts +4 -2
  49. package/src/layout.test.tsx +74 -6
  50. package/src/layout.tsx +85 -25
  51. package/src/layoutContract.test.tsx +239 -1
  52. package/src/layoutContract.ts +131 -5
  53. package/src/layoutDeclaration.test.ts +31 -10
  54. package/src/layoutDeclaration.ts +9 -4
  55. package/src/locale.tsx +20 -3
  56. package/src/markers.test.ts +70 -2
  57. package/src/router.test.tsx +15 -3
  58. package/src/router.tsx +11 -2
  59. package/src/ssr.test.tsx +18 -0
  60. package/src/styles.test.ts +222 -190
  61. package/src/styles.ts +1268 -328
  62. package/src/theme.test.tsx +44 -18
  63. package/src/theme.themes.test.ts +22 -2
  64. package/src/theme.tsx +22 -14
  65. package/src/themes.ts +39 -4
  66. package/src/tokens.guard.test.ts +13 -15
  67. package/src/typography.tsx +5 -1
  68. package/src/ui/Alert.test.tsx +24 -1
  69. package/src/ui/Alert.tsx +10 -1
  70. package/src/ui/Card.tsx +5 -4
  71. package/src/ui/Tooltip.test.tsx +171 -2
  72. package/src/ui/Tooltip.tsx +144 -8
  73. package/src/ui/controlMessages.tsx +20 -7
  74. package/src/uiText.test.tsx +16 -0
  75. package/src/uiText.tsx +76 -7
@@ -0,0 +1,74 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, render, screen, within } from "@testing-library/react";
3
+ import type { ReactNode } from "react";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+
6
+ import { LOCALE_EN, LOCALE_NL, LocaleProvider } from "./locale";
7
+ import { Timeline } from "./Timeline";
8
+
9
+ afterEach(() => {
10
+ cleanup();
11
+ window.localStorage.clear();
12
+ });
13
+
14
+ function renderIn(locale: "nl" | "en", node: ReactNode) {
15
+ return render(
16
+ <LocaleProvider locales={{ nl: LOCALE_NL, en: LOCALE_EN }} defaultLocale={locale}>
17
+ {node}
18
+ </LocaleProvider>,
19
+ );
20
+ }
21
+
22
+ const EVENTS = [
23
+ { label: "Changed", when: "2026-08-21T09:30:00Z", detail: "Actor: 9f2c1b7e" },
24
+ { label: "Created", when: "2026-08-20T08:00:00Z", tone: "success" as const },
25
+ ];
26
+
27
+ describe("Timeline", () => {
28
+ it("is an ordered list named for what its events are of, one item per event", () => {
29
+ // An ordered list, so a screen reader says how many events there are and where it is.
30
+ renderIn("en", <Timeline label="History" events={EVENTS} />);
31
+ const list = screen.getByRole("list", { name: "History" });
32
+ expect(list.tagName).toBe("OL");
33
+ // Mutation: drop the stated role, and VoiceOver reads a list without markers as no list.
34
+ expect(list).toHaveAttribute("role", "list");
35
+ expect(within(list).getAllByRole("listitem")).toHaveLength(2);
36
+ });
37
+
38
+ it("prints each event's words and its moment in the app's locale, with the instant in a time element", () => {
39
+ // Mutation: drop the dateTime, and the machine-readable instant is gone.
40
+ renderIn("nl", <Timeline label="Geschiedenis" events={EVENTS} />);
41
+ const times = [...document.querySelectorAll('[data-terp="timeline-when"]')];
42
+ expect(times[0]!.tagName).toBe("TIME");
43
+ expect(times[0]).toHaveAttribute("dateTime", "2026-08-21T09:30:00.000Z");
44
+ expect(times[0]!.textContent).toMatch(/21 aug\.? 2026/);
45
+ expect(document.querySelector('[data-terp="timeline-label"]')!.textContent).toBe("Changed");
46
+ expect(document.querySelector('[data-terp="timeline-detail"]')!.textContent).toBe("Actor: 9f2c1b7e");
47
+ });
48
+
49
+ it("marks an event's tone on the event and hides the marker, whose word is the label", () => {
50
+ renderIn("en", <Timeline label="History" events={EVENTS} />);
51
+ const events = [...document.querySelectorAll('[data-terp="timeline-event"]')];
52
+ expect(events[0]).not.toHaveAttribute("data-tone");
53
+ expect(events[1]).toHaveAttribute("data-tone", "success");
54
+ expect(events[1]!.querySelector('[data-terp="timeline-marker"]')).toHaveAttribute("aria-hidden", "true");
55
+ });
56
+
57
+ it("renders no detail line for a detail that renders nothing, and no instant for a value that is not a date", () => {
58
+ // Mutation: test `detail !== undefined` alone, and an empty line is added.
59
+ renderIn("en", (
60
+ <Timeline
61
+ label="History"
62
+ events={[
63
+ { label: "A", when: "not a date", detail: "" },
64
+ { label: "B", when: null, detail: false },
65
+ ]}
66
+ />
67
+ ));
68
+ expect(document.querySelector('[data-terp="timeline-detail"]')).toBeNull();
69
+ for (const time of document.querySelectorAll('[data-terp="timeline-when"]')) {
70
+ expect(time).not.toHaveAttribute("dateTime");
71
+ expect(time.textContent).toBe("—");
72
+ }
73
+ });
74
+ });
@@ -0,0 +1,71 @@
1
+ import type { FormattableDate } from "./format";
2
+ import { useFormatDateTime } from "./format";
3
+ import { injectTerpStyles } from "./styles";
4
+ import type { BadgeTone } from "./ui/Badge";
5
+ import { resolveUiTextNode, useUiText } from "./uiText";
6
+ import type { UiText, UiTextNode } from "./uiText";
7
+
8
+ injectTerpStyles();
9
+
10
+ /** One thing that happened, and when. */
11
+ export interface TimelineEvent {
12
+ /** What happened, in words ("Updated", "Approved"). */
13
+ label: UiText;
14
+ /** When: a date-time the `format` helpers take, printed in the app's locale with its time. */
15
+ when: FormattableDate;
16
+ /** One line more — who did it, or what it changed. */
17
+ detail?: UiTextNode;
18
+ /**
19
+ * The event's tone where it marks a change of state worth seeing at a glance — a deletion
20
+ * as danger. The label is its word, so the marker's colour never carries meaning alone.
21
+ */
22
+ tone?: BadgeTone;
23
+ }
24
+
25
+ export interface TimelineProps {
26
+ /** What the events are of ("History"): the list's accessible name. */
27
+ label: UiText;
28
+ /** The events, in the order to read them — a record's history newest first. */
29
+ events: readonly TimelineEvent[];
30
+ }
31
+
32
+ /** An ISO string for `<time dateTime>`, or nothing where the value is not a date. */
33
+ function isoOf(value: FormattableDate): string | undefined {
34
+ const date = value instanceof Date ? value : value === null || value === undefined ? null : new Date(value);
35
+ return date === null || Number.isNaN(date.getTime()) ? undefined : date.toISOString();
36
+ }
37
+
38
+ /**
39
+ * Events in order (ADR 0169 §5): what happened to a record, and when, on a line that joins them
40
+ * — a record's audit trail on its detail page, a request's steps.
41
+ *
42
+ * An ordered list, so a screen reader announces how many events there are and where it is
43
+ * among them -- with the list role stated, because WebKit drops a list's semantics once the
44
+ * sheet takes its markers away -- and each `when` is a `<time>` carrying its machine-readable
45
+ * instant. The marker is
46
+ * decoration: the label says what its tone shows. Unframed, so it reads in a card or on the page
47
+ * alike.
48
+ */
49
+ export function Timeline({ label, events }: TimelineProps) {
50
+ const resolve = useUiText();
51
+ const formatDateTime = useFormatDateTime();
52
+ return (
53
+ <ol data-terp="timeline" role="list" aria-label={resolve(label)}>
54
+ {events.map((event, index) => (
55
+ <li key={index} data-terp="timeline-event" data-tone={event.tone}>
56
+ <span data-terp="timeline-marker" aria-hidden="true" />
57
+ <span data-terp="timeline-label">{resolve(event.label)}</span>
58
+ <time data-terp="timeline-when" dateTime={isoOf(event.when)}>
59
+ {formatDateTime(event.when)}
60
+ </time>
61
+ {event.detail !== undefined &&
62
+ event.detail !== null &&
63
+ event.detail !== false &&
64
+ event.detail !== "" && (
65
+ <span data-terp="timeline-detail">{resolveUiTextNode(event.detail, resolve)}</span>
66
+ )}
67
+ </li>
68
+ ))}
69
+ </ol>
70
+ );
71
+ }
@@ -5,6 +5,7 @@ import { HubCard, HubPage } from "../HubPage";
5
5
  import type { RenderHubCardLink } from "../HubPage";
6
6
  import type { AdminAreaSections } from "../bootstrap";
7
7
  import { NavIcon } from "../icons";
8
+ import { Stat } from "../Stat";
8
9
  import { useTerpClient } from "../TerpProvider";
9
10
  import { unwrap } from "../unwrap";
10
11
  import { useStrings } from "../uiText";
@@ -58,7 +59,8 @@ function useHubStats(sections: Required<AdminAreaSections>): HubStats {
58
59
 
59
60
  /**
60
61
  * The packaged admin hub (`/admin`): one card per administration area — users,
61
- * groups and the audit log — with live totals where they are cheap to know.
62
+ * groups and the audit log — with live totals where they are cheap to know, each a `Stat`
63
+ * so a count reads here as it does on every other page (ADR 0169 §5).
62
64
  * The sidebar's single "Admin" entry opens this hub; the overviews breadcrumb
63
65
  * back to it, keeping the hub -> overview -> detail layering every Terp screen
64
66
  * follows. `sections` (default: all) mirrors the app's `adminArea` selection —
@@ -81,7 +83,9 @@ export function AdminHub({ sections }: { sections?: AdminAreaSections } = {}) {
81
83
  title={strings.adminUsers}
82
84
  description={strings.adminUsersDescription}
83
85
  icon={<NavIcon name="users" label={strings.adminUsers} />}
84
- stat={stats.users !== null ? String(stats.users) : undefined}
86
+ stat={
87
+ stats.users !== null ? <Stat label={strings.adminHubTotal} value={stats.users} /> : undefined
88
+ }
85
89
  renderLink={renderLink}
86
90
  />
87
91
  )}
@@ -91,7 +95,11 @@ export function AdminHub({ sections }: { sections?: AdminAreaSections } = {}) {
91
95
  title={strings.adminGroups}
92
96
  description={strings.adminGroupsDescription}
93
97
  icon={<NavIcon name="shield" label={strings.adminGroups} />}
94
- stat={stats.groups !== null ? String(stats.groups) : undefined}
98
+ stat={
99
+ stats.groups !== null ? (
100
+ <Stat label={strings.adminHubTotal} value={stats.groups} />
101
+ ) : undefined
102
+ }
95
103
  renderLink={renderLink}
96
104
  />
97
105
  )}
@@ -13,6 +13,7 @@ import type { TerpStrings } from "../uiText";
13
13
  import { unwrap } from "../unwrap";
14
14
 
15
15
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
16
+ import { auditActionWord } from "./RecordHistory";
16
17
 
17
18
  type AuditEventRead = components["schemas"]["AuditEventRead"];
18
19
 
@@ -31,7 +32,8 @@ function buildColumns(
31
32
  {
32
33
  id: "action",
33
34
  header: strings.actionColumn,
34
- accessor: (e) => e.action,
35
+ // The app's words for the four actions, as a record's history says them.
36
+ accessor: (e) => auditActionWord(strings, e.action),
35
37
  meta: { mobileSlot: "status", width: "xs" },
36
38
  },
37
39
  {
@@ -11,6 +11,7 @@ import { useTerpClient } from "../TerpProvider";
11
11
  import { useToast } from "../toast";
12
12
  import { Button } from "../ui/Button";
13
13
  import { Input } from "../ui/Input";
14
+ import { useErrorMessage } from "../errorMessages";
14
15
  import { useStrings } from "../uiText";
15
16
  import { unwrap } from "../unwrap";
16
17
 
@@ -27,6 +28,7 @@ export function GroupCreate() {
27
28
  const client = useTerpClient();
28
29
  const navigate = useNavigate();
29
30
  const strings = useStrings();
31
+ const messageForCode = useErrorMessage();
30
32
  const toast = useToast();
31
33
  const [name, setName] = useState("");
32
34
  const [description, setDescription] = useState("");
@@ -54,7 +56,7 @@ export function GroupCreate() {
54
56
  const { shown, leftover } = routeFieldErrors(error, RENDERED_FIELDS);
55
57
  setFieldErrors(shown);
56
58
  if (Object.keys(shown).length === 0 || leftover) {
57
- toast.warning(error instanceof Error ? error.message : strings.requestFailed);
59
+ toast.warning(messageForCode(error) ?? (error instanceof Error ? error.message : strings.requestFailed));
58
60
  }
59
61
  } finally {
60
62
  setCreating(false);
@@ -18,10 +18,12 @@ import { useToast } from "../toast";
18
18
  import { Button } from "../ui/Button";
19
19
  import { Input } from "../ui/Input";
20
20
  import { useFormatDate, useFormatDateTime } from "../format";
21
+ import { useErrorMessage } from "../errorMessages";
21
22
  import { useStrings } from "../uiText";
22
23
  import { ApiError, unwrap } from "../unwrap";
23
24
 
24
25
  import { ModuleAccessPanel } from "./ModuleAccessPanel";
26
+ import { RecordHistory } from "./RecordHistory";
25
27
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
26
28
 
27
29
  type GroupRead = components["schemas"]["GroupRead"];
@@ -47,6 +49,7 @@ export function GroupDetail() {
47
49
  const navigate = useNavigate();
48
50
  const toast = useToast();
49
51
  const strings = useStrings();
52
+ const messageForCode = useErrorMessage();
50
53
  const suggestionsId = useId();
51
54
 
52
55
  const formatDate = useFormatDate();
@@ -193,7 +196,7 @@ export function GroupDetail() {
193
196
  );
194
197
 
195
198
  function failed(error: unknown): void {
196
- toast.warning(error instanceof Error ? error.message : strings.requestFailed);
199
+ toast.warning(messageForCode(error) ?? (error instanceof Error ? error.message : strings.requestFailed));
197
200
  }
198
201
 
199
202
  /**
@@ -366,7 +369,9 @@ export function GroupDetail() {
366
369
  >
367
370
  <Stack gap={6}>
368
371
  {record !== null && (
372
+ // The group's facts as a ruled sheet (ADR 0169 §5), above its access and collections.
369
373
  <DetailList
374
+ layout="grid"
370
375
  items={[
371
376
  { label: strings.description, value: record.description || "-" },
372
377
  { label: strings.members, value: record.member_count },
@@ -380,72 +385,72 @@ export function GroupDetail() {
380
385
  // members through the same expansion that already carries the group's grants.
381
386
  <ModuleAccessPanel subjectId={record.id} />
382
387
  )}
383
- <Stack gap={3}>
384
- <h2 data-terp="admin-section-title">
385
- {strings.members}
386
- </h2>
387
- <Stack as="form" direction="row" gap={2} align="end" wrap onSubmit={onAddMember}>
388
- <Field label={strings.userField} error={memberError}>
389
- <Input
390
- type="email"
391
- value={memberQuery}
392
- list={suggestionsId}
393
- placeholder={strings.email}
394
- onChange={(event) => setMemberQuery(event.target.value)}
395
- required
396
- />
397
- </Field>
398
- <datalist id={suggestionsId}>
399
- {suggestions.map((user) => (
400
- <option key={user.id} value={user.email} />
401
- ))}
402
- </datalist>
403
- <Button type="submit" disabled={adding || memberQuery.trim() === ""}>
404
- {adding ? strings.working : strings.addMember}
405
- </Button>
406
- </Stack>
407
- <DataView<GroupMemberRead>
408
- variant="embedded"
409
- repository={membersRepository}
410
- columns={memberColumns}
411
- rowActions={(member) => [
412
- {
413
- label: strings.removeMember,
414
- variant: "destructive",
415
- onClick: () => setPendingMember(member),
416
- },
417
- ]}
418
- />
419
- </Stack>
420
- <Stack gap={3}>
421
- <h2 data-terp="admin-section-title">
422
- {strings.permissions}
423
- </h2>
424
- <Stack as="form" direction="row" gap={2} align="end" wrap onSubmit={onGrant}>
425
- <Field label={strings.permission} error={permissionError}>
426
- <Input
427
- value={permission}
428
- onChange={(event) => setPermission(event.target.value)}
429
- required
430
- />
431
- </Field>
432
- <Button type="submit" disabled={granting}>
433
- {granting ? strings.working : strings.grantPermission}
434
- </Button>
435
- </Stack>
436
- <DataView<GrantRead>
437
- variant="embedded"
438
- repository={grantsRepository}
439
- columns={grantColumns}
440
- rowActions={(grant) => [
441
- {
442
- label: strings.revoke,
443
- variant: "destructive",
444
- onClick: () => setPendingGrant(grant),
445
- },
446
- ]}
447
- />
448
- </Stack>
388
+ {/* The collection names itself and counts itself (ADR 0169 §5), and the way to add to it
389
+ sits in its toolbar, between its name and its rows. */}
390
+ <DataView<GroupMemberRead>
391
+ title={strings.members}
392
+ variant="embedded"
393
+ repository={membersRepository}
394
+ columns={memberColumns}
395
+ rowActions={(member) => [
396
+ {
397
+ label: strings.removeMember,
398
+ variant: "destructive",
399
+ onClick: () => setPendingMember(member),
400
+ },
401
+ ]}
402
+ toolbarContent={
403
+ <Stack as="form" direction="row" gap={2} align="end" wrap onSubmit={onAddMember}>
404
+ <Field label={strings.userField} error={memberError}>
405
+ <Input
406
+ type="email"
407
+ value={memberQuery}
408
+ list={suggestionsId}
409
+ placeholder={strings.email}
410
+ onChange={(event) => setMemberQuery(event.target.value)}
411
+ required
412
+ />
413
+ </Field>
414
+ <datalist id={suggestionsId}>
415
+ {suggestions.map((user) => (
416
+ <option key={user.id} value={user.email} />
417
+ ))}
418
+ </datalist>
419
+ <Button type="submit" disabled={adding || memberQuery.trim() === ""}>
420
+ {adding ? strings.working : strings.addMember}
421
+ </Button>
422
+ </Stack>
423
+ }
424
+ />
425
+ <DataView<GrantRead>
426
+ title={strings.permissions}
427
+ variant="embedded"
428
+ repository={grantsRepository}
429
+ columns={grantColumns}
430
+ rowActions={(grant) => [
431
+ {
432
+ label: strings.revoke,
433
+ variant: "destructive",
434
+ onClick: () => setPendingGrant(grant),
435
+ },
436
+ ]}
437
+ toolbarContent={
438
+ <Stack as="form" direction="row" gap={2} align="end" wrap onSubmit={onGrant}>
439
+ <Field label={strings.permission} error={permissionError}>
440
+ <Input
441
+ value={permission}
442
+ onChange={(event) => setPermission(event.target.value)}
443
+ required
444
+ />
445
+ </Field>
446
+ <Button type="submit" disabled={granting}>
447
+ {granting ? strings.working : strings.grantPermission}
448
+ </Button>
449
+ </Stack>
450
+ }
451
+ />
452
+ {/* The group's own history from the audit trail, newest first (ADR 0169 §5). */}
453
+ {record !== null && <RecordHistory targetType="Group" targetId={record.id} />}
449
454
  </Stack>
450
455
  <ConfirmDialog
451
456
  open={deleteOpen}
@@ -34,7 +34,9 @@ function buildColumns(
34
34
  id: "member_count",
35
35
  header: strings.members,
36
36
  accessor: (g) => g.member_count,
37
- meta: { mobileSlot: "status", width: "sm" },
37
+ // Group sizes compared at a glance, each still printed (ADR 0169 §5).
38
+ bar: true,
39
+ meta: { mobileSlot: "status", width: "md" },
38
40
  },
39
41
  {
40
42
  id: "created_at",
@@ -292,7 +292,7 @@ export function ModuleAccessPanel({ subjectId, globalRank = null }: ModuleAccess
292
292
 
293
293
  return (
294
294
  <Stack gap={3}>
295
- <h2 data-terp="admin-section-title">{strings.moduleAccessTitle}</h2>
295
+ <h3 data-terp="admin-section-title">{strings.moduleAccessTitle}</h3>
296
296
  <span data-terp="tile-note">{strings.moduleAccessDescription}</span>
297
297
  {(loading || (settled < 0 && heldError === null)) && <LoadingState />}
298
298
  {!loading && error !== null && <Alert tone="danger">{error}</Alert>}
@@ -303,15 +303,12 @@ export function ModuleAccessPanel({ subjectId, globalRank = null }: ModuleAccess
303
303
  <Alert tone="danger">{heldError}</Alert>
304
304
  )}
305
305
  {orphaned.map((entry) => (
306
- <Stack key={`orphan:${entry.module}`} gap={2}>
307
- <Alert tone="warning">
308
- {strings.moduleAccessOrphaned
309
- .replace("{role}", entry.role ?? String(entry.role_rank))
310
- .replace("{module}", entry.module)}
311
- </Alert>
312
- <Stack direction="row" gap={2}>
313
- {/* The only action the declarations still permit here, so it is the only one
314
- offered — a strip would hold rungs the server would refuse to store. */}
306
+ <Alert
307
+ key={`orphan:${entry.module}`}
308
+ tone="warning"
309
+ actions={
310
+ // The only action the declarations still permit here, so it is the only one
311
+ // offered — a strip would hold rungs the server would refuse to store.
315
312
  <Button
316
313
  variant="danger"
317
314
  disabled={busy || settling}
@@ -321,8 +318,12 @@ export function ModuleAccessPanel({ subjectId, globalRank = null }: ModuleAccess
321
318
  >
322
319
  {strings.revoke}
323
320
  </Button>
324
- </Stack>
325
- </Stack>
321
+ }
322
+ >
323
+ {strings.moduleAccessOrphaned
324
+ .replace("{role}", entry.role ?? String(entry.role_rank))
325
+ .replace("{module}", entry.module)}
326
+ </Alert>
326
327
  ))}
327
328
  {!loading && settled >= 0 && error === null && assignable.length === 0 && (
328
329
  <Alert tone="info">{strings.moduleAccessNoneAssignable}</Alert>
@@ -0,0 +1,83 @@
1
+ import { useEffect, useState } from "react";
2
+
3
+ import type { components } from "@terpjs/contract";
4
+
5
+ import { Timeline } from "../Timeline";
6
+ import type { TimelineEvent } from "../Timeline";
7
+ import { useTerpClient } from "../TerpProvider";
8
+ import type { BadgeTone } from "../ui/Badge";
9
+ import { Card } from "../ui/Card";
10
+ import { unwrap } from "../unwrap";
11
+ import { useStrings } from "../uiText";
12
+ import type { TerpStrings } from "../uiText";
13
+
14
+ type AuditEventRead = components["schemas"]["AuditEventRead"];
15
+
16
+ /** How many of a record's events its screen shows: its recent history, not its whole trail. */
17
+ const RECENT = 10;
18
+
19
+ const ACTION_WORDS: Record<string, keyof TerpStrings> = {
20
+ created: "auditActionCreated",
21
+ updated: "auditActionUpdated",
22
+ deleted: "auditActionDeleted",
23
+ disclosed: "auditActionDisclosed",
24
+ };
25
+
26
+ const ACTION_TONES: Record<string, BadgeTone | undefined> = {
27
+ created: "success",
28
+ deleted: "danger",
29
+ disclosed: "info",
30
+ };
31
+
32
+ /** An audit action in the app's words, or as recorded where it is not one the framework names. */
33
+ export function auditActionWord(strings: TerpStrings, action: string): string {
34
+ const key = ACTION_WORDS[action];
35
+ const word = key === undefined ? undefined : strings[key];
36
+ return typeof word === "string" ? word : action;
37
+ }
38
+
39
+ /**
40
+ * A record's own history, from the audit trail: what happened to it and when, newest first, as
41
+ * a `Timeline` (ADR 0169 §5) — the trail narrowed to the record the screen is about.
42
+ *
43
+ * Context rather than content, so it fails quietly: a trail the caller cannot read, or one with
44
+ * nothing about this record yet, renders no section at all, and the screen around it is whole
45
+ * without it.
46
+ */
47
+ export function RecordHistory({ targetType, targetId }: { targetType: string; targetId: string }) {
48
+ const client = useTerpClient();
49
+ const strings = useStrings();
50
+ const [events, setEvents] = useState<readonly AuditEventRead[] | null>(null);
51
+ useEffect(() => {
52
+ const controller = new AbortController();
53
+ void (async () => {
54
+ try {
55
+ const page = unwrap(
56
+ await client.GET("/api/v1/audit/", {
57
+ params: { query: { target_type: targetType, target_id: targetId, limit: RECENT } },
58
+ signal: controller.signal,
59
+ }),
60
+ );
61
+ setEvents(page.items);
62
+ } catch {
63
+ // The history is context: a screen without it still works.
64
+ }
65
+ })();
66
+ return () => controller.abort();
67
+ }, [client, targetType, targetId]);
68
+ if (events === null || events.length === 0) {
69
+ return null;
70
+ }
71
+ const timeline: TimelineEvent[] = events.map((event) => ({
72
+ label: auditActionWord(strings, event.action),
73
+ when: event.created_at,
74
+ detail:
75
+ event.actor_id === null ? undefined : `${strings.actorColumn}: ${event.actor_id.slice(0, 8)}`,
76
+ tone: ACTION_TONES[event.action],
77
+ }));
78
+ return (
79
+ <Card title={strings.recordHistory}>
80
+ <Timeline label={strings.recordHistory} events={timeline} />
81
+ </Card>
82
+ );
83
+ }
@@ -12,6 +12,7 @@ import { useToast } from "../toast";
12
12
  import { Button } from "../ui/Button";
13
13
  import { Input } from "../ui/Input";
14
14
  import { Select } from "../ui/Select";
15
+ import { useErrorMessage } from "../errorMessages";
15
16
  import { useStrings } from "../uiText";
16
17
  import { unwrap } from "../unwrap";
17
18
 
@@ -30,6 +31,7 @@ export function UserCreate() {
30
31
  const client = useTerpClient();
31
32
  const navigate = useNavigate();
32
33
  const strings = useStrings();
34
+ const messageForCode = useErrorMessage();
33
35
  const toast = useToast();
34
36
  const [email, setEmail] = useState("");
35
37
  const [password, setPassword] = useState("");
@@ -73,7 +75,7 @@ export function UserCreate() {
73
75
  const { shown, leftover } = routeFieldErrors(error, RENDERED_FIELDS);
74
76
  setFieldErrors(shown);
75
77
  if (Object.keys(shown).length === 0 || leftover) {
76
- toast.warning(error instanceof Error ? error.message : strings.requestFailed);
78
+ toast.warning(messageForCode(error) ?? (error instanceof Error ? error.message : strings.requestFailed));
77
79
  }
78
80
  } finally {
79
81
  setCreating(false);
@@ -14,11 +14,13 @@ import { useToast } from "../toast";
14
14
  import { Button } from "../ui/Button";
15
15
  import { Input } from "../ui/Input";
16
16
  import { useFormatDateTime } from "../format";
17
+ import { useErrorMessage } from "../errorMessages";
17
18
  import { useStrings } from "../uiText";
18
19
  import { unwrap } from "../unwrap";
19
20
 
20
21
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
21
22
  import { ModuleAccessPanel } from "./ModuleAccessPanel";
23
+ import { RecordHistory } from "./RecordHistory";
22
24
  import { adminRoleLabel } from "./roles";
23
25
  import { useAccessLadder } from "./useAccessLadder";
24
26
 
@@ -33,6 +35,7 @@ export function UserDetail() {
33
35
  const userId = useDeclaredParam("userId");
34
36
  const client = useTerpClient();
35
37
  const strings = useStrings();
38
+ const messageForCode = useErrorMessage();
36
39
  const formatDateTime = useFormatDateTime();
37
40
  const toast = useToast();
38
41
  const [pendingLifecycle, setPendingLifecycle] = useState<PendingLifecycle | null>(null);
@@ -64,7 +67,7 @@ export function UserDetail() {
64
67
  const record = user.item;
65
68
 
66
69
  function failed(error: unknown): void {
67
- toast.warning(error instanceof Error ? error.message : strings.requestFailed);
70
+ toast.warning(messageForCode(error) ?? (error instanceof Error ? error.message : strings.requestFailed));
68
71
  }
69
72
 
70
73
  async function onConfirmLifecycle() {
@@ -170,7 +173,9 @@ export function UserDetail() {
170
173
  >
171
174
  {record !== null && (
172
175
  <Stack gap={6}>
176
+ {/* The account's facts as a ruled sheet (ADR 0169 §5): short, several, read across. */}
173
177
  <DetailList
178
+ layout="grid"
174
179
  items={[
175
180
  { label: strings.email, value: record.email },
176
181
  { label: strings.role, value: adminRoleLabel(rungs, record.role) },
@@ -184,6 +189,8 @@ export function UserDetail() {
184
189
  {/* The rung is chosen where the person is: this is the only screen that has a
185
190
  subject, and the global role above it is the floor every module strip sits on. */}
186
191
  <ModuleAccessPanel subjectId={record.id} globalRank={record.role} />
192
+ {/* The account's own history from the audit trail, newest first (ADR 0169 §5). */}
193
+ <RecordHistory targetType="User" targetId={record.id} />
187
194
  </Stack>
188
195
  )}
189
196
  <ConfirmDialog
@@ -39,6 +39,9 @@ function buildColumns(
39
39
  id: "is_active",
40
40
  header: strings.statusColumn,
41
41
  accessor: (u) => (u.is_active ? strings.statusActive : strings.statusDeactivated),
42
+ // A dot rather than a pill: most accounts are active, and a pill on every row is noise
43
+ // around the one that is not (ADR 0169 §5). The text stays the word.
44
+ status: (u) => (u.is_active ? "success" : "neutral"),
42
45
  meta: { mobileSlot: "status", width: "sm" },
43
46
  },
44
47
  {