@terpjs/react-core 0.18.0 → 0.20.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.
@@ -0,0 +1,349 @@
1
+ import { useEffect, useState } from "react";
2
+ import type { components } from "@terpjs/contract";
3
+
4
+ import { Alert } from "../ui/Alert";
5
+ import { Button } from "../ui/Button";
6
+ import { ConfirmDialog } from "../ConfirmDialog";
7
+ import { LoadingState } from "../LoadingState";
8
+ import { Stack } from "../layout";
9
+ import { TileGroup } from "../ui/TileGroup";
10
+ import { useTerpClient } from "../TerpProvider";
11
+ import { useStrings } from "../uiText";
12
+ import { useToast } from "../toast";
13
+ import { unwrap } from "../unwrap";
14
+
15
+ import { NO_ACCESS } from "./accessModel";
16
+ import type { ModuleRow } from "./accessModel";
17
+ import { tilesFor, topRung } from "./accessTiles";
18
+ import { useAccessLadder } from "./useAccessLadder";
19
+ import type { AdminRoleOption } from "./useAccessLadder";
20
+
21
+ type HeldModuleRole = components["schemas"]["HeldModuleRoleRead"];
22
+
23
+ /** What the panel is about to do, held while the confirmation is open. */
24
+ type Pending =
25
+ | { kind: "assign"; module: string; label: string; role: string; rank: number }
26
+ | { kind: "revoke"; module: string; label: string };
27
+
28
+ export interface ModuleAccessPanelProps {
29
+ /** The subject the rungs are being set for — a user id or a group id. */
30
+ subjectId: string;
31
+ /**
32
+ * The subject's rank everywhere, when it has one.
33
+ *
34
+ * A user does; a group does not, because ADR 0074 gives groups permissions rather than
35
+ * roles. It is display-only: a rung at or below it changes nothing, since the guard resolves
36
+ * a module rank as the *higher* of the two, and the strip says so instead of letting someone
37
+ * assign `viewer` to an editor and wonder why nothing happened.
38
+ */
39
+ globalRank?: number | null;
40
+ }
41
+
42
+ /** A failure's own message where it has one, so a 400 from the writer names what it refused. */
43
+ function failure(cause: unknown, fallback: string): string {
44
+ return cause instanceof Error ? cause.message : fallback;
45
+ }
46
+
47
+ /**
48
+ * The rung this subject holds in *this* module by its own name, or `null`.
49
+ *
50
+ * One reader, because the strip and the commit handler both need it and both got it subtly
51
+ * wrong when they each derived it: collapsing "no row" and "a row whose rank the app no longer
52
+ * declares" into the same value made the stale row unclearable, since committing `no access`
53
+ * then looked like committing what was already selected.
54
+ *
55
+ * A rung arriving through a group is excluded — that is a fact about the group, and the strip
56
+ * can only change what this subject was given directly.
57
+ */
58
+ function directRung(held: readonly HeldModuleRole[], module: string): HeldModuleRole | null {
59
+ return held.find((entry) => entry.module === module && entry.via.kind === "self") ?? null;
60
+ }
61
+
62
+ /** The declared rung a rank sits at, for the floor marker: the highest rung the rank clears. */
63
+ function rungAtOrBelow(rungs: readonly AdminRoleOption[], rank: number | null): string | null {
64
+ if (rank === null) return null;
65
+ const cleared = rungs.filter((rung) => rung.rank <= rank);
66
+ return cleared.length === 0 ? null : cleared[cleared.length - 1].name;
67
+ }
68
+
69
+ function ModuleStrip({
70
+ row,
71
+ held,
72
+ floor,
73
+ busy,
74
+ onPick,
75
+ }: {
76
+ row: ModuleRow;
77
+ held: HeldModuleRole[];
78
+ floor: string | null;
79
+ busy: boolean;
80
+ onPick: (row: ModuleRow, value: string) => void;
81
+ }) {
82
+ const strings = useStrings();
83
+ const direct = directRung(held, row.name);
84
+ const inherited = held.filter(
85
+ (entry) => entry.module === row.name && entry.via.kind !== "self",
86
+ );
87
+
88
+ return (
89
+ <Stack gap={2}>
90
+ <Stack direction="row" gap={2} align="center">
91
+ <strong>{row.label}</strong>
92
+ <code>{row.name}</code>
93
+ </Stack>
94
+ <TileGroup
95
+ label={row.label}
96
+ tiles={tilesFor(row, strings)}
97
+ // Three states, not two. No row selects the real `no access` tile; a live rung selects
98
+ // its own; and a rung whose rank the app no longer declares reports `role: null`, which
99
+ // selects *nothing* — with the stale note below saying why. Collapsing that third state
100
+ // into `no access` would claim the subject holds nothing while a row sits there doing
101
+ // nothing, which is the one case where saying so is the whole point.
102
+ value={direct === null ? NO_ACCESS : direct.role}
103
+ floor={floor}
104
+ disabled={busy}
105
+ onCommit={(value) => onPick(row, value)}
106
+ />
107
+ {floor !== null && (
108
+ <span data-terp="tile-note">
109
+ {strings.moduleAccessFloor.replace("{role}", floor)}
110
+ </span>
111
+ )}
112
+ {direct !== null && direct.stale.length > 0 && (
113
+ <Alert tone="warning">
114
+ {strings.moduleAccessStale.replace("{reason}", direct.stale.join("; "))}
115
+ </Alert>
116
+ )}
117
+ {inherited.map((entry) => (
118
+ <span key={`${entry.via.id}:${entry.role_rank}`} data-terp="tile-note">
119
+ {/* Provenance, because "why can this person do that?" is the question an
120
+ administrator has to be able to answer, and a strip that showed only the direct
121
+ row would answer it wrongly on exactly the accounts where it matters. */}
122
+ {strings.moduleAccessVia
123
+ .replace("{role}", entry.role ?? String(entry.role_rank))
124
+ .replace("{name}", entry.via.name ?? entry.via.id)}
125
+ </span>
126
+ ))}
127
+ </Stack>
128
+ );
129
+ }
130
+
131
+ /**
132
+ * Set a subject's role inside one module — the write half of the permission surface.
133
+ *
134
+ * It lives on the subject's own detail screen rather than on `/admin/access`, because that is
135
+ * the only place the choice has a subject (ADR 0121). The access screen explains what a rung
136
+ * *means*; this decides who holds one, and the tiles it offers are built from the same
137
+ * projection, so the explanation a reader saw there is the explanation they act on here.
138
+ *
139
+ * Only modules that opted in are listed. A module that refuses is not a gap the panel should
140
+ * explain — `/admin/access` lists it with its reason — and offering a control the server would
141
+ * refuse is worse than not offering one.
142
+ *
143
+ * Assigning the top rung is behind a confirmation, which is what makes the strip's manual
144
+ * activation load-bearing: arrowing across the tiles must not fire it.
145
+ */
146
+ export function ModuleAccessPanel({ subjectId, globalRank = null }: ModuleAccessPanelProps) {
147
+ const client = useTerpClient();
148
+ const strings = useStrings();
149
+ const toast = useToast();
150
+ const { rungs, modules, loading, error } = useAccessLadder(strings);
151
+ const [held, setHeld] = useState<HeldModuleRole[]>([]);
152
+ const [pending, setPending] = useState<Pending | null>(null);
153
+ const [busy, setBusy] = useState(false);
154
+ const [version, setVersion] = useState(0);
155
+ // The version whose read has actually landed. `-1` until the first one does, which is a
156
+ // state the rows alone cannot express: an empty `held` means "holds nothing" and "not yet
157
+ // asked" identically, and the strips would offer a choice against the wrong answer.
158
+ const [settled, setSettled] = useState(-1);
159
+ // Why the rungs could not be read, when they could not. Kept beside `settled` rather than
160
+ // folded into it: a read that failed is not a read that landed, and the strip must not
161
+ // become a control again on the strength of rows nobody could confirm.
162
+ //
163
+ // Terminal for the panel's lifetime, and there is deliberately no code to clear it. Nothing
164
+ // re-reads without a version bump, and only a write bumps one — which a panel showing no
165
+ // strips cannot produce. A reset here would be a line no test could reach, so the honest
166
+ // shape is not to have one: the operator leaves the screen and comes back, which remounts.
167
+ const [heldError, setHeldError] = useState<string | null>(null);
168
+
169
+ useEffect(() => {
170
+ let live = true;
171
+ void (async () => {
172
+ try {
173
+ const subject = unwrap(
174
+ await client.GET("/api/v1/access/subjects/{subject_id}", {
175
+ params: { path: { subject_id: subjectId } },
176
+ }),
177
+ );
178
+ if (live) {
179
+ setHeld(subject.module_roles);
180
+ setSettled(version);
181
+ }
182
+ } catch (cause: unknown) {
183
+ if (live) setHeldError(failure(cause, strings.requestFailed));
184
+ }
185
+ })();
186
+ return () => {
187
+ live = false;
188
+ };
189
+ // A version counter rather than a callback the writer invokes, which is the idiom the group
190
+ // screen already uses for the same job. The point is that *every* read happens inside this
191
+ // effect, so every read is covered by the `live` guard — a writer that set the rows itself
192
+ // could resolve after the screen was gone, or after a newer read had already landed.
193
+ //
194
+ // `toast` and `strings` are deliberately not dependencies: showing a message must not
195
+ // re-fetch, and neither must a language change.
196
+ // eslint-disable-next-line react-hooks/exhaustive-deps
197
+ }, [client, subjectId, version]);
198
+
199
+ // Between a write resolving and its re-read landing, the rows on screen are the *pre-write*
200
+ // answer — so the strip must not accept another choice against them. It used to: `busy`
201
+ // cleared when the request settled, one round trip before `held` caught up, and in that
202
+ // window a second commit was compared against the stale selection and silently dropped as
203
+ // "already selected".
204
+ const settling = settled !== version;
205
+ const assignable = modules.filter((row) => row.assignable);
206
+ // A rung held in a module that does not accept them — because it never did, or because a
207
+ // later release stopped — has nowhere to appear among the strips, and this panel is the only
208
+ // place it could ever be cleared. Dropping it silently is how a row nobody can explain
209
+ // outlives the release that made it meaningless; ADR 0121 says such a row is reported
210
+ // rather than filtered, and the strips alone cannot keep that promise.
211
+ const orphaned = held.filter(
212
+ (entry) =>
213
+ entry.via.kind === "self" &&
214
+ !assignable.some((row) => row.name === entry.module),
215
+ );
216
+ const floor = rungAtOrBelow(rungs, globalRank);
217
+
218
+ function onPick(row: ModuleRow, value: string) {
219
+ const entry = directRung(held, row.name);
220
+ const current = entry === null ? NO_ACCESS : entry.role;
221
+ // Committing the tile that is already selected is not a change, and a request that stores
222
+ // what is already stored would still write an audit row saying someone changed something.
223
+ // A stale row's `current` is `null`, which is not any tile's value — so `no access` is a
224
+ // real change there, which is what makes such a row clearable at all.
225
+ if (value === current) return;
226
+ if (value === NO_ACCESS) {
227
+ setPending({ kind: "revoke", module: row.name, label: row.label });
228
+ return;
229
+ }
230
+ const rung = rungs.find((option) => option.name === value);
231
+ if (rung === undefined) return;
232
+ if (value === topRung(row)) {
233
+ setPending({
234
+ kind: "assign",
235
+ module: row.name,
236
+ label: row.label,
237
+ role: value,
238
+ rank: rung.rank,
239
+ });
240
+ return;
241
+ }
242
+ void write(row.name, rung.rank);
243
+ }
244
+
245
+ async function write(module: string, rank: number | null) {
246
+ setBusy(true);
247
+ try {
248
+ if (rank === null) {
249
+ unwrap(
250
+ await client.DELETE("/api/v1/access/subjects/{subject_id}/module-roles/{module}", {
251
+ params: { path: { subject_id: subjectId, module } },
252
+ }),
253
+ );
254
+ } else {
255
+ unwrap(
256
+ await client.PUT("/api/v1/access/subjects/{subject_id}/module-roles/{module}", {
257
+ params: { path: { subject_id: subjectId, module } },
258
+ body: { role_rank: rank },
259
+ }),
260
+ );
261
+ }
262
+ setVersion((current) => current + 1);
263
+ toast.success(strings.saved);
264
+ } catch (cause: unknown) {
265
+ toast.warning(failure(cause, strings.requestFailed));
266
+ } finally {
267
+ setBusy(false);
268
+ setPending(null);
269
+ }
270
+ }
271
+
272
+ return (
273
+ <Stack gap={3}>
274
+ <h2 data-terp="admin-section-title">{strings.moduleAccessTitle}</h2>
275
+ <span data-terp="tile-note">{strings.moduleAccessDescription}</span>
276
+ {(loading || (settled < 0 && heldError === null)) && <LoadingState />}
277
+ {!loading && error !== null && <Alert tone="danger">{error}</Alert>}
278
+ {heldError !== null && (
279
+ // Shown *and* the strips stay inert. Offering a choice against rungs nobody could
280
+ // read is how someone changes the wrong tier believing it was the right one; on a
281
+ // permission surface, refusing to guess is the whole posture.
282
+ <Alert tone="danger">{heldError}</Alert>
283
+ )}
284
+ {orphaned.map((entry) => (
285
+ <Stack key={`orphan:${entry.module}`} gap={2}>
286
+ <Alert tone="warning">
287
+ {strings.moduleAccessOrphaned
288
+ .replace("{role}", entry.role ?? String(entry.role_rank))
289
+ .replace("{module}", entry.module)}
290
+ </Alert>
291
+ <Stack direction="row" gap={2}>
292
+ {/* The only action the declarations still permit here, so it is the only one
293
+ offered — a strip would hold rungs the server would refuse to store. */}
294
+ <Button
295
+ variant="danger"
296
+ disabled={busy || settling}
297
+ onClick={() =>
298
+ setPending({ kind: "revoke", module: entry.module, label: entry.module })
299
+ }
300
+ >
301
+ {strings.revoke}
302
+ </Button>
303
+ </Stack>
304
+ </Stack>
305
+ ))}
306
+ {!loading && settled >= 0 && error === null && assignable.length === 0 && (
307
+ <Alert tone="info">{strings.moduleAccessNoneAssignable}</Alert>
308
+ )}
309
+ {/* Only once the rungs are known. A strip built on rows that were never read shows
310
+ `no access` selected for a module where a rung is in fact held, which is a wrong
311
+ statement rather than merely an inert control — and it is the statement someone acts
312
+ on. During a *re*-read the strips stay put and go inert instead: those rows are the
313
+ previous answer, which is very nearly right, and flickering them away is worse. */}
314
+ {settled >= 0 && heldError === null && assignable.map((row) => (
315
+ <ModuleStrip
316
+ key={row.name}
317
+ row={row}
318
+ held={held}
319
+ floor={floor}
320
+ busy={busy || settling}
321
+ onPick={onPick}
322
+ />
323
+ ))}
324
+ <ConfirmDialog
325
+ open={pending !== null}
326
+ onOpenChange={(open) => {
327
+ if (!open) setPending(null);
328
+ }}
329
+ onConfirm={() => {
330
+ if (pending === null) return;
331
+ void write(pending.module, pending.kind === "assign" ? pending.rank : null);
332
+ }}
333
+ title={
334
+ pending?.kind === "assign"
335
+ ? strings.moduleAccessConfirmTitle
336
+ .replace("{role}", pending.role)
337
+ .replace("{module}", pending.label)
338
+ : strings.moduleAccessRevokeTitle.replace("{module}", pending?.label ?? "")
339
+ }
340
+ description={
341
+ pending?.kind === "assign" ? strings.moduleAccessConfirm : strings.moduleAccessRevoke
342
+ }
343
+ confirmLabel={strings.confirm}
344
+ destructive={pending?.kind === "assign"}
345
+ isPending={busy}
346
+ />
347
+ </Stack>
348
+ );
349
+ }
@@ -1,5 +1,5 @@
1
1
  import { useNavigate } from "@tanstack/react-router";
2
- import { useState } from "react";
2
+ import { useEffect, useState } from "react";
3
3
  import type { FormEvent } from "react";
4
4
 
5
5
  import { Field } from "../Field";
@@ -17,7 +17,8 @@ import { unwrap } from "../unwrap";
17
17
 
18
18
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
19
19
  import { routeFieldErrors } from "./fieldErrors";
20
- import { adminRoleOptions } from "./roles";
20
+ import { lowestRank } from "./roles";
21
+ import { useAccessLadder } from "./useAccessLadder";
21
22
 
22
23
  const FORM_ID = "terp-admin-user-create";
23
24
 
@@ -32,10 +33,19 @@ export function UserCreate() {
32
33
  const toast = useToast();
33
34
  const [email, setEmail] = useState("");
34
35
  const [password, setPassword] = useState("");
35
- const [role, setRole] = useState("10");
36
+ // Empty until the declared ladder arrives. The literal "10" this replaced was the
37
+ // packaged viewer rank, so an app whose lowest rung is 5 was provisioning accounts a tier
38
+ // above its own floor — and one that does not declare 10 at all was provisioning at a rank
39
+ // the server would refuse.
40
+ const [role, setRole] = useState("");
36
41
  const [creating, setCreating] = useState(false);
37
42
  const [fieldErrors, setFieldErrors] = useState<Readonly<Record<string, string>>>({});
38
- const roles = adminRoleOptions(strings);
43
+ const { rungs, loading: ladderLoading } = useAccessLadder(strings);
44
+
45
+ useEffect(() => {
46
+ const lowest = lowestRank(rungs);
47
+ if (role === "" && lowest !== null) setRole(String(lowest));
48
+ }, [rungs, role]);
39
49
 
40
50
  async function onSubmit(event: FormEvent) {
41
51
  event.preventDefault();
@@ -90,7 +100,7 @@ export function UserCreate() {
90
100
  type="submit"
91
101
  form={FORM_ID}
92
102
  icon={<Icon name="plus" />}
93
- disabled={creating}
103
+ disabled={creating || ladderLoading || role === ""}
94
104
  >
95
105
  {creating ? strings.working : strings.provisionUser}
96
106
  </Button>
@@ -129,7 +139,7 @@ export function UserCreate() {
129
139
  `String(rank)` is the option value and `role` stays a string until the POST body
130
140
  coerces it. The typed half has its exhibit in an app that owns an enum. */}
131
141
  <Select
132
- options={roles.map((option) => ({
142
+ options={rungs.map((option) => ({
133
143
  value: String(option.rank),
134
144
  label: option.label,
135
145
  }))}
@@ -5,7 +5,7 @@ import { ConfirmDialog } from "../ConfirmDialog";
5
5
  import { DetailPage } from "../DetailPage";
6
6
  import { Field } from "../Field";
7
7
  import { Icon } from "../icons";
8
- import { DetailList } from "../layout";
8
+ import { DetailList, Stack } from "../layout";
9
9
  import { PageActions } from "../PageActions";
10
10
  import { useDeclaredParam } from "../router";
11
11
  import { useTerpClient } from "../TerpProvider";
@@ -18,7 +18,9 @@ import { useStrings } from "../uiText";
18
18
  import { unwrap } from "../unwrap";
19
19
 
20
20
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
21
- import { adminRoleLabel, adminRoleOptions } from "./roles";
21
+ import { ModuleAccessPanel } from "./ModuleAccessPanel";
22
+ import { adminRoleLabel } from "./roles";
23
+ import { useAccessLadder } from "./useAccessLadder";
22
24
 
23
25
  type UserRead = components["schemas"]["UserRead"];
24
26
 
@@ -38,7 +40,7 @@ export function UserDetail() {
38
40
  const [resetOpen, setResetOpen] = useState(false);
39
41
  const [resetPassword, setResetPassword] = useState("");
40
42
  const [resetting, setResetting] = useState(false);
41
- const roles = adminRoleOptions(strings);
43
+ const { rungs } = useAccessLadder(strings);
42
44
 
43
45
  useEffect(() => {
44
46
  setPendingLifecycle(null);
@@ -114,7 +116,7 @@ export function UserDetail() {
114
116
  }
115
117
 
116
118
  const pendingRole = pendingLifecycle?.kind === "role"
117
- ? adminRoleLabel(strings, pendingLifecycle.rank)
119
+ ? adminRoleLabel(rungs, pendingLifecycle.rank)
118
120
  : "";
119
121
  const lifecycleDescription = pendingLifecycle?.kind === "role"
120
122
  ? strings.changeRoleConfirm.replace("{role}", pendingRole)
@@ -144,7 +146,7 @@ export function UserDetail() {
144
146
  </Button>
145
147
  }
146
148
  overflow={[
147
- ...roles
149
+ ...rungs
148
150
  .filter((option) => option.rank !== record.role)
149
151
  .map((option) => ({
150
152
  label: strings.makeRole.replace("{role}", option.label.toLowerCase()),
@@ -167,17 +169,22 @@ export function UserDetail() {
167
169
  ) : undefined}
168
170
  >
169
171
  {record !== null && (
170
- <DetailList
171
- items={[
172
- { label: strings.email, value: record.email },
173
- { label: strings.role, value: adminRoleLabel(strings, record.role) },
174
- {
175
- label: strings.statusColumn,
176
- value: record.is_active ? strings.statusActive : strings.statusDeactivated,
177
- },
178
- { label: strings.createdColumn, value: formatDateTime(record.created_at) },
179
- ]}
180
- />
172
+ <Stack gap={6}>
173
+ <DetailList
174
+ items={[
175
+ { label: strings.email, value: record.email },
176
+ { label: strings.role, value: adminRoleLabel(rungs, record.role) },
177
+ {
178
+ label: strings.statusColumn,
179
+ value: record.is_active ? strings.statusActive : strings.statusDeactivated,
180
+ },
181
+ { label: strings.createdColumn, value: formatDateTime(record.created_at) },
182
+ ]}
183
+ />
184
+ {/* The rung is chosen where the person is: this is the only screen that has a
185
+ subject, and the global role above it is the floor every module strip sits on. */}
186
+ <ModuleAccessPanel subjectId={record.id} globalRank={record.role} />
187
+ </Stack>
181
188
  )}
182
189
  <ConfirmDialog
183
190
  open={pendingLifecycle !== null}
@@ -15,13 +15,16 @@ import type { TerpStrings } from "../uiText";
15
15
  import { unwrap } from "../unwrap";
16
16
 
17
17
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
18
+ import type { AdminRoleOption } from "./roles";
18
19
  import { adminRoleLabel } from "./roles";
20
+ import { useAccessLadder } from "./useAccessLadder";
19
21
 
20
22
  type UserRead = components["schemas"]["UserRead"];
21
23
 
22
24
  function buildColumns(
23
25
  strings: TerpStrings,
24
26
  formatDate: (value: string) => string,
27
+ rungs: readonly AdminRoleOption[],
25
28
  ): DataViewColumn<UserRead>[] {
26
29
  return [
27
30
  { id: "email", header: strings.email, accessor: (u) => u.email, meta: { mobileSlot: "title" } },
@@ -29,7 +32,7 @@ function buildColumns(
29
32
  id: "role",
30
33
  header: strings.role,
31
34
  accessor: (u) => u.role,
32
- cell: (u) => adminRoleLabel(strings, u.role),
35
+ cell: (u) => adminRoleLabel(rungs, u.role),
33
36
  meta: { mobileSlot: "subtitle", width: "xs" },
34
37
  },
35
38
  {
@@ -60,9 +63,12 @@ export function UsersAdmin() {
60
63
  const serverQuery = useServerDataView({ initialPageSize: 10 });
61
64
 
62
65
  const formatDate = useFormatDate();
66
+ // The ladder the app declares, so a rank renders under the name its author gave it rather
67
+ // than under whichever of three literals this file used to carry.
68
+ const { rungs } = useAccessLadder(strings);
63
69
  const columns = useMemo(
64
- () => buildColumns(strings, formatDate),
65
- [strings, formatDate],
70
+ () => buildColumns(strings, formatDate, rungs),
71
+ [strings, formatDate, rungs],
66
72
  );
67
73
  const repository = useMemo(
68
74
  () =>