@terpjs/react-core 0.20.0 → 0.22.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 +2 -0
- package/package.json +2 -2
- package/src/RequireAuth.test.tsx +6 -0
- package/src/RequireAuth.tsx +34 -1
- package/src/RequireAuth.unreachable.test.tsx +137 -0
- package/src/TerpProvider.tsx +56 -5
- package/src/admin/GroupCreate.tsx +1 -1
- package/src/admin/UserCreate.tsx +1 -1
- package/src/bootstrap.test.tsx +16 -1
- package/src/dataview/DataView.test.tsx +27 -0
- package/src/dataview/DataView.tsx +10 -5
- package/src/dataview/DataViewPagination.tsx +17 -7
- package/src/dataview/hooks/useDataViewQuery.ts +15 -2
- package/src/fieldErrors.test.ts +54 -0
- package/src/{admin/fieldErrors.ts → fieldErrors.ts} +19 -2
- package/src/index.ts +3 -0
- package/src/locale.tsx +4 -0
- package/src/randomUuid.test.ts +78 -0
- package/src/randomUuid.ts +111 -0
- package/src/styles.test.ts +39 -0
- package/src/styles.ts +27 -5
- package/src/uiText.tsx +8 -0
package/README.md
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "0.22.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": {
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"@tanstack/react-router": "^1.170.32",
|
|
17
|
-
"@terpjs/contract": "^0.
|
|
17
|
+
"@terpjs/contract": "^0.22.0"
|
|
18
18
|
},
|
|
19
19
|
"peerDependencies": {
|
|
20
20
|
"react": "^19.0.0",
|
package/src/RequireAuth.test.tsx
CHANGED
|
@@ -28,6 +28,12 @@ function LogInOnMount() {
|
|
|
28
28
|
|
|
29
29
|
describe("RequireAuth", () => {
|
|
30
30
|
it("shows the fallback while signed out", async () => {
|
|
31
|
+
// A 401 is what a signed-out visitor's browser actually receives: an answer. Letting
|
|
32
|
+
// the fetch fail instead would model a dead backend, which is now a different view.
|
|
33
|
+
vi.stubGlobal(
|
|
34
|
+
"fetch",
|
|
35
|
+
vi.fn<typeof fetch>(async () => new Response("{}", { status: 401 })),
|
|
36
|
+
);
|
|
31
37
|
render(
|
|
32
38
|
<TerpProvider baseUrl="https://api.test">
|
|
33
39
|
<RequireAuth fallback={<span>please-sign-in</span>}>
|
package/src/RequireAuth.tsx
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
1
|
import type { ReactNode } from "react";
|
|
2
2
|
|
|
3
|
+
import { ErrorState } from "./ErrorState";
|
|
3
4
|
import { useAuth } from "./TerpProvider";
|
|
5
|
+
import { useStrings } from "./uiText";
|
|
4
6
|
|
|
5
7
|
export interface RequireAuthProps {
|
|
6
8
|
/** Rendered while no user is signed in (e.g. a login view). */
|
|
7
9
|
fallback: ReactNode;
|
|
8
10
|
/** Rendered while the provider is checking a persisted session (default: nothing). */
|
|
9
11
|
pending?: ReactNode;
|
|
12
|
+
/**
|
|
13
|
+
* Rendered when the boot session check got no answer at all — the backend did not
|
|
14
|
+
* respond, or the connection failed. Defaults to a stated failure, never to the
|
|
15
|
+
* login view: offering a sign-in form that cannot possibly succeed sends the reader
|
|
16
|
+
* to check their password for a problem that is not theirs.
|
|
17
|
+
*/
|
|
18
|
+
unreachable?: ReactNode;
|
|
10
19
|
children: ReactNode;
|
|
11
20
|
}
|
|
12
21
|
|
|
@@ -14,9 +23,33 @@ export interface RequireAuthProps {
|
|
|
14
23
|
* Render `children` only when a user is signed in, otherwise `fallback` (typically a login
|
|
15
24
|
* view). Pair with the router so the authenticated app mounts only once there is a session;
|
|
16
25
|
* the backend still enforces authorization on every request.
|
|
26
|
+
*
|
|
27
|
+
* Three states, not two. "Nobody is signed in" and "the server never answered" used to
|
|
28
|
+
* be the same branch, and because a fetch to a dead proxy target hangs instead of
|
|
29
|
+
* failing, the second one rendered `pending` — nothing — for as long as the page was
|
|
30
|
+
* open. A blank screen with an empty console is the least diagnosable failure the stack
|
|
31
|
+
* can produce, so it now says what happened.
|
|
17
32
|
*/
|
|
18
|
-
export function RequireAuth({
|
|
33
|
+
export function RequireAuth({
|
|
34
|
+
fallback,
|
|
35
|
+
pending = null,
|
|
36
|
+
unreachable,
|
|
37
|
+
children,
|
|
38
|
+
}: RequireAuthProps) {
|
|
19
39
|
const auth = useAuth();
|
|
40
|
+
const strings = useStrings();
|
|
20
41
|
if (auth.loading()) return <>{pending}</>;
|
|
42
|
+
if (auth.unreachable()) {
|
|
43
|
+
return (
|
|
44
|
+
<>
|
|
45
|
+
{unreachable ?? (
|
|
46
|
+
<ErrorState
|
|
47
|
+
title={strings.backendUnreachableTitle}
|
|
48
|
+
description={strings.backendUnreachableDescription}
|
|
49
|
+
/>
|
|
50
|
+
)}
|
|
51
|
+
</>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
21
54
|
return <>{auth.currentUser() !== null ? children : fallback}</>;
|
|
22
55
|
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
|
3
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
4
|
+
|
|
5
|
+
import { RequireAuth } from "./RequireAuth";
|
|
6
|
+
import { BOOT_REQUEST_TIMEOUT_MS, TerpProvider } from "./TerpProvider";
|
|
7
|
+
|
|
8
|
+
afterEach(() => {
|
|
9
|
+
cleanup();
|
|
10
|
+
vi.restoreAllMocks();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A dead backend used to be indistinguishable from a signed-out visitor, and worse
|
|
15
|
+
* than that: a fetch to a dead proxy target does not fail, it hangs, so the boot
|
|
16
|
+
* refresh never settled, `loading` stayed true and `RequireAuth` rendered its `pending`
|
|
17
|
+
* slot — nothing — for as long as the page stayed open. An empty `#root`, three console
|
|
18
|
+
* messages, zero errors, zero warnings.
|
|
19
|
+
*/
|
|
20
|
+
describe("a backend that does not answer the boot check", () => {
|
|
21
|
+
it("gives the boot request a deadline, so a hang becomes a failure", async () => {
|
|
22
|
+
// The mechanism, pinned at the wiring: without a signal there is nothing to make a
|
|
23
|
+
// hanging fetch settle, and every assertion below depends on it settling.
|
|
24
|
+
const timeout = vi.spyOn(AbortSignal, "timeout");
|
|
25
|
+
vi.stubGlobal(
|
|
26
|
+
"fetch",
|
|
27
|
+
vi.fn<typeof fetch>(async () => new Response("{}", { status: 401 })),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
render(
|
|
31
|
+
<TerpProvider baseUrl="https://api.test">
|
|
32
|
+
<RequireAuth fallback={<span>please-sign-in</span>}>
|
|
33
|
+
<span>app</span>
|
|
34
|
+
</RequireAuth>
|
|
35
|
+
</TerpProvider>,
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
await waitFor(() => expect(screen.getByText("please-sign-in")).toBeInTheDocument());
|
|
39
|
+
expect(timeout).toHaveBeenCalledWith(BOOT_REQUEST_TIMEOUT_MS);
|
|
40
|
+
expect(BOOT_REQUEST_TIMEOUT_MS).toBeGreaterThan(0);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("says so on the screen instead of offering a sign-in that cannot work", async () => {
|
|
44
|
+
// A rejected fetch is what an aborted one produces, and what a refused connection
|
|
45
|
+
// produces: no answer came back at all.
|
|
46
|
+
vi.stubGlobal(
|
|
47
|
+
"fetch",
|
|
48
|
+
vi.fn<typeof fetch>(async () => {
|
|
49
|
+
throw new TypeError("Failed to fetch");
|
|
50
|
+
}),
|
|
51
|
+
);
|
|
52
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
53
|
+
|
|
54
|
+
render(
|
|
55
|
+
<TerpProvider baseUrl="https://api.test">
|
|
56
|
+
<RequireAuth fallback={<span>please-sign-in</span>}>
|
|
57
|
+
<span>app</span>
|
|
58
|
+
</RequireAuth>
|
|
59
|
+
</TerpProvider>,
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
await waitFor(() =>
|
|
63
|
+
expect(screen.getByText(/cannot reach its server/i)).toBeInTheDocument(),
|
|
64
|
+
);
|
|
65
|
+
// Not the login view: a sign-in form that cannot possibly succeed sends the reader
|
|
66
|
+
// to check their own password for a problem that is not theirs.
|
|
67
|
+
expect(screen.queryByText("please-sign-in")).not.toBeInTheDocument();
|
|
68
|
+
expect(screen.queryByText("app")).not.toBeInTheDocument();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("is loud in the console too, naming the API it could not reach", async () => {
|
|
72
|
+
vi.stubGlobal(
|
|
73
|
+
"fetch",
|
|
74
|
+
vi.fn<typeof fetch>(async () => {
|
|
75
|
+
throw new TypeError("Failed to fetch");
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
79
|
+
|
|
80
|
+
render(
|
|
81
|
+
<TerpProvider baseUrl="https://api.test">
|
|
82
|
+
<RequireAuth fallback={<span>please-sign-in</span>}>
|
|
83
|
+
<span>app</span>
|
|
84
|
+
</RequireAuth>
|
|
85
|
+
</TerpProvider>,
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
await waitFor(() => expect(warn).toHaveBeenCalled());
|
|
89
|
+
const message = warn.mock.calls.map((call) => String(call[0])).join("\n");
|
|
90
|
+
expect(message).toContain("https://api.test");
|
|
91
|
+
expect(message).toContain("did not answer");
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("renders a caller's own unreachable view when it has one", async () => {
|
|
95
|
+
vi.stubGlobal(
|
|
96
|
+
"fetch",
|
|
97
|
+
vi.fn<typeof fetch>(async () => {
|
|
98
|
+
throw new TypeError("Failed to fetch");
|
|
99
|
+
}),
|
|
100
|
+
);
|
|
101
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
102
|
+
|
|
103
|
+
render(
|
|
104
|
+
<TerpProvider baseUrl="https://api.test">
|
|
105
|
+
<RequireAuth
|
|
106
|
+
fallback={<span>please-sign-in</span>}
|
|
107
|
+
unreachable={<span>our-own-message</span>}
|
|
108
|
+
>
|
|
109
|
+
<span>app</span>
|
|
110
|
+
</RequireAuth>
|
|
111
|
+
</TerpProvider>,
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
await waitFor(() => expect(screen.getByText("our-own-message")).toBeInTheDocument());
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("keeps 'nobody is signed in' a separate answer from 'nobody answered'", async () => {
|
|
118
|
+
// The distinction the old code could not make. A 401 IS an answer, so this must
|
|
119
|
+
// render the login view and never the failure — an assertion that only checked for
|
|
120
|
+
// the failure's absence would pass on a provider that showed nothing at all.
|
|
121
|
+
vi.stubGlobal(
|
|
122
|
+
"fetch",
|
|
123
|
+
vi.fn<typeof fetch>(async () => new Response("{}", { status: 401 })),
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
render(
|
|
127
|
+
<TerpProvider baseUrl="https://api.test">
|
|
128
|
+
<RequireAuth fallback={<span>please-sign-in</span>}>
|
|
129
|
+
<span>app</span>
|
|
130
|
+
</RequireAuth>
|
|
131
|
+
</TerpProvider>,
|
|
132
|
+
);
|
|
133
|
+
|
|
134
|
+
await waitFor(() => expect(screen.getByText("please-sign-in")).toBeInTheDocument());
|
|
135
|
+
expect(screen.queryByText(/cannot reach its server/i)).not.toBeInTheDocument();
|
|
136
|
+
});
|
|
137
|
+
});
|
package/src/TerpProvider.tsx
CHANGED
|
@@ -70,8 +70,34 @@ export interface TerpProviderProps {
|
|
|
70
70
|
children: ReactNode;
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
/**
|
|
74
|
+
* How long the boot session check waits for an answer before giving up.
|
|
75
|
+
*
|
|
76
|
+
* Loud on purpose, and the reason this number exists at all: a fetch to a dead proxy
|
|
77
|
+
* target does not fail, it *hangs*. The boot refresh therefore never settled, `loading`
|
|
78
|
+
* stayed true for the lifetime of the page, and `RequireAuth` rendered its `pending`
|
|
79
|
+
* slot — nothing, by default. The symptom was an empty `#root` with three console
|
|
80
|
+
* messages, zero errors and zero warnings: the single least diagnosable failure in the
|
|
81
|
+
* stack, for the most ordinary cause there is.
|
|
82
|
+
*
|
|
83
|
+
* Boot only, deliberately not a client-wide default. A file upload through the files
|
|
84
|
+
* capability legitimately runs longer than any timeout that would help here, so a
|
|
85
|
+
* blanket one would abort correct work to fix a diagnosis problem.
|
|
86
|
+
*/
|
|
87
|
+
export const BOOT_REQUEST_TIMEOUT_MS = 10_000;
|
|
88
|
+
|
|
89
|
+
/** An abort signal for one boot request, or undefined where the runtime has none. */
|
|
90
|
+
function bootTimeout(): AbortSignal | undefined {
|
|
91
|
+
// Guarded rather than assumed: this also runs under a test renderer and in SSR, and a
|
|
92
|
+
// missing AbortSignal.timeout must degrade to the old behaviour rather than throw
|
|
93
|
+
// during boot -- which would be a worse failure than the one being fixed.
|
|
94
|
+
return typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function"
|
|
95
|
+
? AbortSignal.timeout(BOOT_REQUEST_TIMEOUT_MS)
|
|
96
|
+
: undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
73
99
|
async function loadCurrentUser(client: TerpClient): Promise<CurrentUser> {
|
|
74
|
-
const { data, error } = await client.GET("/api/v1/me/", {});
|
|
100
|
+
const { data, error } = await client.GET("/api/v1/me/", { signal: bootTimeout() });
|
|
75
101
|
if (error || !data) {
|
|
76
102
|
throw new Error("failed to load the current user");
|
|
77
103
|
}
|
|
@@ -95,6 +121,11 @@ export function TerpProvider({
|
|
|
95
121
|
const [user, setUser] = useState<CurrentUser | null>(null);
|
|
96
122
|
const [loading, setLoading] = useState(true);
|
|
97
123
|
const [ssoError, setSsoError] = useState<unknown>(null);
|
|
124
|
+
const [unreachable, setUnreachable] = useState(false);
|
|
125
|
+
// Set by the refresh attempt, read by the boot effect. A rejected fetch means no
|
|
126
|
+
// answer came back at all; a resolved one carrying `error` means the backend
|
|
127
|
+
// answered "no session", which is a completely different thing to tell the reader.
|
|
128
|
+
const noAnswerRef = useRef(false);
|
|
98
129
|
|
|
99
130
|
// Captured once per provider lifetime (before the URL is cleaned), so a StrictMode
|
|
100
131
|
// double boot effect cannot replay the single-use OIDC state against the backend.
|
|
@@ -129,15 +160,21 @@ export function TerpProvider({
|
|
|
129
160
|
const existing = refreshInFlightRef.current;
|
|
130
161
|
if (existing) return existing;
|
|
131
162
|
const attempt = refreshClient
|
|
132
|
-
.POST("/api/v1/auth/refresh", {})
|
|
163
|
+
.POST("/api/v1/auth/refresh", { signal: bootTimeout() })
|
|
133
164
|
.then(({ data, error }) => {
|
|
165
|
+
// An answer arrived, whatever it said: the backend is reachable.
|
|
166
|
+
noAnswerRef.current = false;
|
|
134
167
|
if (error || !data) {
|
|
135
168
|
return null;
|
|
136
169
|
}
|
|
137
170
|
tokenRef.current = data.access_token;
|
|
138
171
|
return data.access_token;
|
|
139
172
|
})
|
|
140
|
-
.catch(() =>
|
|
173
|
+
.catch(() => {
|
|
174
|
+
// No answer: a refused connection, a dead proxy target, or the timeout above.
|
|
175
|
+
noAnswerRef.current = true;
|
|
176
|
+
return null;
|
|
177
|
+
})
|
|
141
178
|
.finally(() => {
|
|
142
179
|
refreshInFlightRef.current = null;
|
|
143
180
|
});
|
|
@@ -166,6 +203,7 @@ export function TerpProvider({
|
|
|
166
203
|
}
|
|
167
204
|
tokenRef.current = data.access_token;
|
|
168
205
|
const me = await loadCurrentUser(client);
|
|
206
|
+
setUnreachable(false);
|
|
169
207
|
setUser(me);
|
|
170
208
|
return me;
|
|
171
209
|
},
|
|
@@ -233,6 +271,18 @@ export function TerpProvider({
|
|
|
233
271
|
return;
|
|
234
272
|
}
|
|
235
273
|
await refresh();
|
|
274
|
+
if (noAnswerRef.current) {
|
|
275
|
+
// The console half of the same message. The screen tells whoever is looking at
|
|
276
|
+
// the app; this tells whoever has devtools open, which for this failure is the
|
|
277
|
+
// person most likely to be looking for it.
|
|
278
|
+
console.warn(
|
|
279
|
+
`[terp] the API at ${baseUrl} did not answer the boot session check within ` +
|
|
280
|
+
`${BOOT_REQUEST_TIMEOUT_MS}ms. Is the backend running, and is the dev ` +
|
|
281
|
+
"server's proxy target pointing at it? Nothing else will render until it " +
|
|
282
|
+
"answers.",
|
|
283
|
+
);
|
|
284
|
+
setUnreachable(true);
|
|
285
|
+
}
|
|
236
286
|
};
|
|
237
287
|
void boot().finally(() => {
|
|
238
288
|
if (!cancelled) setLoading(false);
|
|
@@ -240,7 +290,7 @@ export function TerpProvider({
|
|
|
240
290
|
return () => {
|
|
241
291
|
cancelled = true;
|
|
242
292
|
};
|
|
243
|
-
}, [completePendingSso, refresh]);
|
|
293
|
+
}, [baseUrl, completePendingSso, refresh]);
|
|
244
294
|
|
|
245
295
|
const auth = useMemo<AuthSession>(
|
|
246
296
|
() => ({
|
|
@@ -249,6 +299,7 @@ export function TerpProvider({
|
|
|
249
299
|
refresh,
|
|
250
300
|
currentUser: () => user,
|
|
251
301
|
loading: () => loading,
|
|
302
|
+
unreachable: () => unreachable,
|
|
252
303
|
// `module` names the module the action happens in, so a per-module rung can raise the
|
|
253
304
|
// answer. Omitted, the gate is the global rank exactly as before — which is the honest
|
|
254
305
|
// default for a screen that is not a module's own, and keeps every existing caller
|
|
@@ -263,7 +314,7 @@ export function TerpProvider({
|
|
|
263
314
|
)
|
|
264
315
|
: false,
|
|
265
316
|
}),
|
|
266
|
-
[login, logout, refresh, user, loading, thresholds],
|
|
317
|
+
[login, logout, refresh, user, loading, unreachable, thresholds],
|
|
267
318
|
);
|
|
268
319
|
|
|
269
320
|
const beginSso = useCallback(
|
|
@@ -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 "
|
|
18
|
+
import { routeFieldErrors } from "../fieldErrors";
|
|
19
19
|
|
|
20
20
|
const FORM_ID = "terp-admin-group-create";
|
|
21
21
|
|
package/src/admin/UserCreate.tsx
CHANGED
|
@@ -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 "
|
|
19
|
+
import { routeFieldErrors } from "../fieldErrors";
|
|
20
20
|
import { lowestRank } from "./roles";
|
|
21
21
|
import { useAccessLadder } from "./useAccessLadder";
|
|
22
22
|
|
package/src/bootstrap.test.tsx
CHANGED
|
@@ -1,13 +1,26 @@
|
|
|
1
1
|
// @vitest-environment jsdom
|
|
2
2
|
import { cleanup, screen, waitFor } from "@testing-library/react";
|
|
3
|
-
import { afterEach, describe, expect, it } from "vitest";
|
|
3
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
4
4
|
import { defineModuleManifest } from "@terpjs/contract";
|
|
5
5
|
|
|
6
6
|
import { collectModules, renderTerpApp } from "./bootstrap";
|
|
7
7
|
import { useErrorMessage } from "./errorMessages";
|
|
8
8
|
|
|
9
|
+
// A signed-out visitor's browser gets a 401 from the boot session check — an ANSWER.
|
|
10
|
+
// These tests used to model "signed out" by letting the fetch fail outright, which is
|
|
11
|
+
// the same state a dead backend produces, and the provider now tells those two apart:
|
|
12
|
+
// no answer at all renders the unreachable view rather than a login form that cannot
|
|
13
|
+
// work. So the fixture says what it means.
|
|
14
|
+
beforeEach(() => {
|
|
15
|
+
vi.stubGlobal(
|
|
16
|
+
"fetch",
|
|
17
|
+
vi.fn<typeof fetch>(async () => new Response("{}", { status: 401 })),
|
|
18
|
+
);
|
|
19
|
+
});
|
|
20
|
+
|
|
9
21
|
afterEach(() => {
|
|
10
22
|
cleanup();
|
|
23
|
+
vi.restoreAllMocks();
|
|
11
24
|
});
|
|
12
25
|
|
|
13
26
|
const notesModule = {
|
|
@@ -56,6 +69,7 @@ describe("renderTerpApp", () => {
|
|
|
56
69
|
|
|
57
70
|
renderTerpApp({
|
|
58
71
|
title: "Test",
|
|
72
|
+
baseUrl: "https://api.test",
|
|
59
73
|
modules: { "./modules/notes/module.tsx": notesModule },
|
|
60
74
|
rootElement: root,
|
|
61
75
|
});
|
|
@@ -93,6 +107,7 @@ describe("renderTerpApp", () => {
|
|
|
93
107
|
|
|
94
108
|
renderTerpApp({
|
|
95
109
|
title: "Test",
|
|
110
|
+
baseUrl: "https://api.test",
|
|
96
111
|
modules: { "./modules/notes/module.tsx": notesModule },
|
|
97
112
|
rootElement: root,
|
|
98
113
|
login: <ShowsAnError />,
|
|
@@ -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 (
|
|
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
|
}
|
|
@@ -9,14 +9,23 @@ import type { DataViewPaginationState } from "./hooks/useDataViewState";
|
|
|
9
9
|
|
|
10
10
|
export interface DataViewPaginationProps {
|
|
11
11
|
pagination: DataViewPaginationState;
|
|
12
|
-
|
|
12
|
+
/** How many rows match, or `undefined` while that is not known yet. */
|
|
13
|
+
totalCount: number | undefined;
|
|
13
14
|
onPaginationChange: (pagination: DataViewPaginationState) => void;
|
|
14
15
|
}
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
|
-
* The footer pagination bar: "X
|
|
18
|
+
* The footer pagination bar: "X-Y of Z results", the current page / page count, and
|
|
18
19
|
* first / prev / next / last controls (disabled at bounds; page controls hidden when
|
|
19
20
|
* there is only one page).
|
|
21
|
+
*
|
|
22
|
+
* **An unknown total renders as nothing, never as zero.** The bar used to compute its
|
|
23
|
+
* range from a `totalCount` that was `0` until the first query answered, so a fresh view
|
|
24
|
+
* asserted "0-0 of 0 results" underneath its own loading skeleton -- a count stated with
|
|
25
|
+
* authority, next to a placeholder admitting there is no data yet, and wrong as often as
|
|
26
|
+
* not. `useResource` drew this distinction in 0.17.0 ("unknown is a real answer and must
|
|
27
|
+
* not render as zero"); this is the same one, one component over. The bar keeps its box
|
|
28
|
+
* either way, so nothing moves when the number arrives.
|
|
20
29
|
*/
|
|
21
30
|
export function DataViewPagination({
|
|
22
31
|
pagination,
|
|
@@ -25,10 +34,11 @@ export function DataViewPagination({
|
|
|
25
34
|
}: DataViewPaginationProps) {
|
|
26
35
|
const { strings, format } = useDataViewText();
|
|
27
36
|
|
|
28
|
-
const
|
|
37
|
+
const known = totalCount !== undefined;
|
|
38
|
+
const pageCount = Math.max(1, Math.ceil((totalCount ?? 0) / pagination.pageSize));
|
|
29
39
|
const pageIndex = Math.min(pagination.pageIndex, pageCount - 1);
|
|
30
|
-
const from = totalCount === 0 ? 0 : pageIndex * pagination.pageSize + 1;
|
|
31
|
-
const to = Math.min(totalCount, (pageIndex + 1) * pagination.pageSize);
|
|
40
|
+
const from = !known || totalCount === 0 ? 0 : pageIndex * pagination.pageSize + 1;
|
|
41
|
+
const to = Math.min(totalCount ?? 0, (pageIndex + 1) * pagination.pageSize);
|
|
32
42
|
|
|
33
43
|
const goTo = (index: number) => onPaginationChange({ ...pagination, pageIndex: index });
|
|
34
44
|
const atFirst = pageIndex === 0;
|
|
@@ -36,7 +46,7 @@ export function DataViewPagination({
|
|
|
36
46
|
|
|
37
47
|
return (
|
|
38
48
|
<div data-terp="dataview-pagination">
|
|
39
|
-
<span>{format(strings.resultsRange, { from, to, total: totalCount })}</span>
|
|
49
|
+
<span>{known ? format(strings.resultsRange, { from, to, total: totalCount }) : null}</span>
|
|
40
50
|
{/* aria-disabled, not disabled, and the difference is where focus goes. Each of these
|
|
41
51
|
four buttons has a bound condition recomputed from what its own click just changed, so
|
|
42
52
|
pressing "next" until the last page disabled the very control the user was operating —
|
|
@@ -44,7 +54,7 @@ export function DataViewPagination({
|
|
|
44
54
|
keyboard user paging to the end lost their place in the document at the exact moment
|
|
45
55
|
they arrived. Kept focusable and announced as disabled instead, with the handler inert
|
|
46
56
|
on the bound; the sheet paints [aria-disabled="true"] identically to :disabled. */}
|
|
47
|
-
{pageCount > 1 && (
|
|
57
|
+
{known && pageCount > 1 && (
|
|
48
58
|
<span data-terp="dataview-pager">
|
|
49
59
|
<span>{format(strings.pageOf, { page: pageIndex + 1, pages: pageCount })}</span>
|
|
50
60
|
<button
|
|
@@ -4,7 +4,16 @@ import type { DataViewQuery, DataViewRepository } from "../types";
|
|
|
4
4
|
|
|
5
5
|
export interface UseDataViewQueryResult<T> {
|
|
6
6
|
rows: T[];
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* How many rows match, or `undefined` while that is genuinely not known yet -- before
|
|
9
|
+
* the first query answers, and after one fails.
|
|
10
|
+
*
|
|
11
|
+
* Not `0`, which is a different answer and a wrong one: a footer reading "0-0 of 0
|
|
12
|
+
* results" beside a loading skeleton states a fact the app has not been told. This is
|
|
13
|
+
* the same distinction `Resource.total` draws for `useResource` (0.17.0), one component
|
|
14
|
+
* over, and for the same reason -- unknown is a real answer and must not render as zero.
|
|
15
|
+
*/
|
|
16
|
+
totalCount: number | undefined;
|
|
8
17
|
/** True until the first page for this repository has resolved (skeleton state). */
|
|
9
18
|
isLoading: boolean;
|
|
10
19
|
/** True while any query is in flight (subtle refresh indicator; stale data stays). */
|
|
@@ -24,7 +33,7 @@ export function useDataViewQuery<T>(
|
|
|
24
33
|
query: DataViewQuery,
|
|
25
34
|
): UseDataViewQueryResult<T> {
|
|
26
35
|
const [rows, setRows] = useState<T[]>([]);
|
|
27
|
-
const [totalCount, setTotalCount] = useState(
|
|
36
|
+
const [totalCount, setTotalCount] = useState<number | undefined>(undefined);
|
|
28
37
|
const [isLoading, setIsLoading] = useState(true);
|
|
29
38
|
const [isFetching, setIsFetching] = useState(true);
|
|
30
39
|
const [error, setError] = useState<unknown>(null);
|
|
@@ -56,6 +65,10 @@ export function useDataViewQuery<T>(
|
|
|
56
65
|
if (!active || controller.signal.aborted) {
|
|
57
66
|
return;
|
|
58
67
|
}
|
|
68
|
+
// The count is not carried over from a previous success: a failed refetch knows
|
|
69
|
+
// nothing about how many rows match now, and saying the old number would be a
|
|
70
|
+
// guess presented as a fact.
|
|
71
|
+
setTotalCount(undefined);
|
|
59
72
|
setError(caught);
|
|
60
73
|
setIsLoading(false);
|
|
61
74
|
setIsFetching(false);
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { routeFieldErrors } from "./fieldErrors";
|
|
4
|
+
import { ApiError } from "./unwrap";
|
|
5
|
+
|
|
6
|
+
function failure(fields: Record<string, string>): ApiError {
|
|
7
|
+
return new ApiError("Kan niet opslaan.", { status: 422, code: "validation_failed", fields });
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
describe("routeFieldErrors", () => {
|
|
11
|
+
it("hands back the reasons this form actually renders", () => {
|
|
12
|
+
const { shown, leftover } = routeFieldErrors(
|
|
13
|
+
failure({ name: "Naam is verplicht.", description: "Te lang." }),
|
|
14
|
+
["name", "description"],
|
|
15
|
+
);
|
|
16
|
+
expect(shown).toEqual({ name: "Naam is verplicht.", description: "Te lang." });
|
|
17
|
+
expect(leftover).toBe(false);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it("reports a reason naming a field the form has no input for", () => {
|
|
21
|
+
// The whole point of the second return value. Without it a caller writes "if there
|
|
22
|
+
// are fields, set them and return", and a reason it cannot show sets state nobody
|
|
23
|
+
// reads AND suppresses the toast — the user presses Save and nothing happens at all.
|
|
24
|
+
const { shown, leftover } = routeFieldErrors(
|
|
25
|
+
failure({ name: "Naam is verplicht.", tenant_id: "Onbekende organisatie." }),
|
|
26
|
+
["name"],
|
|
27
|
+
);
|
|
28
|
+
expect(shown).toEqual({ name: "Naam is verplicht." });
|
|
29
|
+
expect(leftover).toBe(true);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("reports leftover even when it can show nothing at all", () => {
|
|
33
|
+
// The worst case for the naive version: every reason is unshowable, so `shown` is
|
|
34
|
+
// empty and a caller keying off "did we set any fields" falls through correctly only
|
|
35
|
+
// because `leftover` said so.
|
|
36
|
+
const { shown, leftover } = routeFieldErrors(failure({ tenant_id: "Onbekend." }), ["name"]);
|
|
37
|
+
expect(shown).toEqual({});
|
|
38
|
+
expect(leftover).toBe(true);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("treats a failure that names no field as nothing to route", () => {
|
|
42
|
+
const { shown, leftover } = routeFieldErrors(failure({}), ["name"]);
|
|
43
|
+
expect(shown).toEqual({});
|
|
44
|
+
expect(leftover).toBe(false);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("is inert for anything that is not an ApiError", () => {
|
|
48
|
+
// A thrown string, a TypeError from the caller's own code: there is nothing to read,
|
|
49
|
+
// and guessing would put a message under a field the server never mentioned.
|
|
50
|
+
for (const thrown of [new Error("boom"), "boom", null, undefined]) {
|
|
51
|
+
expect(routeFieldErrors(thrown, ["name"])).toEqual({ shown: {}, leftover: false });
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ApiError } from "
|
|
1
|
+
import { ApiError } from "./unwrap";
|
|
2
2
|
|
|
3
3
|
/** What a form should do with a failure: what to put on inputs, and whether anything is left over. */
|
|
4
4
|
export interface RoutedFieldErrors {
|
|
@@ -24,7 +24,24 @@ export interface RoutedFieldErrors {
|
|
|
24
24
|
* copy. `GroupDetail` already had it right by naming its one key and falling through to the toast
|
|
25
25
|
* when the server named a different one; this is that discipline, for a form with several.
|
|
26
26
|
*
|
|
27
|
-
*
|
|
27
|
+
* Public since 0.22.0, on the condition its previous note set: it becomes package surface when
|
|
28
|
+
* something outside `admin/` needs it, and an app wiring `ApiError.fields` into its own forms is
|
|
29
|
+
* that. Copying it is what produces the hole above, because the leftover branch is the half a
|
|
30
|
+
* reader does not know to write.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* const RENDERED = ["name", "description"];
|
|
35
|
+
* try {
|
|
36
|
+
* await unwrap(client.POST("/api/v1/groups/", { body }));
|
|
37
|
+
* } catch (error) {
|
|
38
|
+
* const { shown, leftover } = routeFieldErrors(error, RENDERED);
|
|
39
|
+
* setFieldErrors(shown);
|
|
40
|
+
* if (leftover || Object.keys(shown).length === 0) {
|
|
41
|
+
* toast.error(message(error)); // never leave the user with nothing
|
|
42
|
+
* }
|
|
43
|
+
* }
|
|
44
|
+
* ```
|
|
28
45
|
*/
|
|
29
46
|
export function routeFieldErrors(
|
|
30
47
|
error: unknown,
|
package/src/index.ts
CHANGED
|
@@ -158,6 +158,9 @@ export { Markdown } from "./ui/Markdown";
|
|
|
158
158
|
export type { MarkdownProps } from "./ui/Markdown";
|
|
159
159
|
export { saveBlob, useEndpointDownload, fetchDownload, downloadUrl } from "./download";
|
|
160
160
|
export { copyText, useCopyToClipboard, COPIED_FEEDBACK_MS } from "./clipboard";
|
|
161
|
+
export { routeFieldErrors } from "./fieldErrors";
|
|
162
|
+
export type { RoutedFieldErrors } from "./fieldErrors";
|
|
163
|
+
export { randomUuid, RandomUuidUnavailableError } from "./randomUuid";
|
|
161
164
|
export type { CopyToClipboard } from "./clipboard";
|
|
162
165
|
export type { DownloadTarget } from "./download";
|
|
163
166
|
export { Heading, Text, Code, Link } from "./typography";
|
package/src/locale.tsx
CHANGED
|
@@ -192,6 +192,10 @@ export const LOCALE_NL: LocaleCatalog = {
|
|
|
192
192
|
moduleNavigationLabel: "Modulenavigatie",
|
|
193
193
|
moreActions: "Meer acties",
|
|
194
194
|
errorTitle: "Er is iets misgegaan.",
|
|
195
|
+
backendUnreachableTitle: "De applicatie kan de server niet bereiken.",
|
|
196
|
+
backendUnreachableDescription:
|
|
197
|
+
"Er kwam geen antwoord van de API. Mogelijk start deze nog op, of staat "
|
|
198
|
+
+ "hij uit. Vernieuw de pagina zodra hij draait.",
|
|
195
199
|
confirm: "Bevestigen",
|
|
196
200
|
cancel: "Annuleren",
|
|
197
201
|
successTitle: "Gelukt",
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { randomUuid, RandomUuidUnavailableError } from "./randomUuid";
|
|
4
|
+
|
|
5
|
+
const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
6
|
+
|
|
7
|
+
/** Swap the ambient `crypto` for the duration of a case. */
|
|
8
|
+
function withCrypto(replacement: unknown): void {
|
|
9
|
+
vi.stubGlobal("crypto", replacement);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
afterEach(() => {
|
|
13
|
+
vi.unstubAllGlobals();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe("randomUuid", () => {
|
|
17
|
+
it("uses the native generator where the context is secure", () => {
|
|
18
|
+
const randomUUID = vi.fn(() => "11111111-2222-4333-8444-555555555555");
|
|
19
|
+
withCrypto({ randomUUID, getRandomValues: vi.fn() });
|
|
20
|
+
expect(randomUuid()).toBe("11111111-2222-4333-8444-555555555555");
|
|
21
|
+
expect(randomUUID).toHaveBeenCalledOnce();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it("produces a well-formed v4 with randomUUID absent, as on an http origin", () => {
|
|
25
|
+
// The case the whole module exists for. crypto.randomUUID is secure-context-only and
|
|
26
|
+
// lib.dom declares it unconditionally, so this shape type-checks and throws a
|
|
27
|
+
// synchronous TypeError in a browser -- and never on localhost, so no test sees it.
|
|
28
|
+
const real = globalThis.crypto;
|
|
29
|
+
withCrypto({ getRandomValues: real.getRandomValues.bind(real) });
|
|
30
|
+
for (let i = 0; i < 50; i += 1) {
|
|
31
|
+
expect(randomUuid()).toMatch(V4);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("pins the version and variant bits rather than emitting 128 loose bits", () => {
|
|
36
|
+
// Without the two masks the value merely looks like a UUID, and anything reading its
|
|
37
|
+
// version field gets a nonsense answer. Feed all-zero and all-one bytes: the only
|
|
38
|
+
// digits that must not follow the input are those two.
|
|
39
|
+
for (const fill of [0x00, 0xff]) {
|
|
40
|
+
withCrypto({
|
|
41
|
+
getRandomValues: (array: Uint8Array) => {
|
|
42
|
+
array.fill(fill);
|
|
43
|
+
return array;
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
const value = randomUuid();
|
|
47
|
+
expect(value).toMatch(V4);
|
|
48
|
+
expect(value[14], "the version nibble is always 4").toBe("4");
|
|
49
|
+
expect("89ab", "the variant nibble is 8, 9, a or b").toContain(value[19]);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it("does not repeat itself", () => {
|
|
54
|
+
const real = globalThis.crypto;
|
|
55
|
+
withCrypto({ getRandomValues: real.getRandomValues.bind(real) });
|
|
56
|
+
const seen = new Set(Array.from({ length: 500 }, () => randomUuid()));
|
|
57
|
+
expect(seen.size).toBe(500);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("refuses rather than falling back to a weaker source", () => {
|
|
61
|
+
// No Math.random path, deliberately: a UUID standing in for an idempotency key is a
|
|
62
|
+
// value a collision corrupts, so quietly degrading its entropy to keep the call site
|
|
63
|
+
// quiet is the "it worked" this seam exists to refuse.
|
|
64
|
+
withCrypto(undefined);
|
|
65
|
+
expect(() => randomUuid()).toThrow(RandomUuidUnavailableError);
|
|
66
|
+
|
|
67
|
+
withCrypto({});
|
|
68
|
+
expect(() => randomUuid()).toThrow(RandomUuidUnavailableError);
|
|
69
|
+
|
|
70
|
+
withCrypto({ randomUUID: "not a function", getRandomValues: undefined });
|
|
71
|
+
expect(() => randomUuid()).toThrow(RandomUuidUnavailableError);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("says why it refused", () => {
|
|
75
|
+
withCrypto(undefined);
|
|
76
|
+
expect(() => randomUuid()).toThrow(/crypto.randomUUID nor crypto.getRandomValues/);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generating a UUID, once, for everyone.
|
|
3
|
+
*
|
|
4
|
+
* `crypto.randomUUID` is not the API it looks like. `lib.dom` declares it
|
|
5
|
+
* unconditionally on `Crypto`, and it exists only in a **secure context** — so on a
|
|
6
|
+
* plain-http origin that is not localhost, `crypto.randomUUID()` is a call on
|
|
7
|
+
* `undefined`. That throws a **synchronous** `TypeError`, TypeScript reports nothing
|
|
8
|
+
* because as far as its type says the method is there, and a test suite running on
|
|
9
|
+
* localhost never sees it either: localhost *is* a secure context, so the whole class is
|
|
10
|
+
* invisible to the type checker, to review, and to CI at once.
|
|
11
|
+
*
|
|
12
|
+
* Same shape as the clipboard seam, and the same argument (ADR 0096 §3): a browser API
|
|
13
|
+
* with a footgun, wrapped once. What makes it worth a seam rather than a lesson is that
|
|
14
|
+
* the platform routes you here — the idempotency capability's contract is a
|
|
15
|
+
* **client-generated** `Idempotency-Key` header, so an app wiring retry-safety reaches
|
|
16
|
+
* for exactly this method — and the topology it breaks in is the one Terp itself ships:
|
|
17
|
+
* the compose files publish plain http, so any deployment reached by hostname rather than
|
|
18
|
+
* localhost is an insecure context.
|
|
19
|
+
*
|
|
20
|
+
* **The fallback never weakens the value.** `crypto.getRandomValues` is *not*
|
|
21
|
+
* secure-context-gated and is available wherever `crypto` is, so an insecure context
|
|
22
|
+
* still gets a cryptographically random v4 — assembled here rather than by the missing
|
|
23
|
+
* method. There is deliberately no `Math.random` path: a UUID standing in for an
|
|
24
|
+
* idempotency key or an optimistic row id is a value collisions corrupt, and silently
|
|
25
|
+
* degrading its entropy to keep a call site quiet is the kind of "it worked" the clipboard
|
|
26
|
+
* seam exists to refuse. With no `crypto` at all this throws, because there is nothing
|
|
27
|
+
* honest left to return.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** Two hex digits per byte, precomputed: the formatting is 16 lookups, not 16 `padStart`s. */
|
|
31
|
+
const HEX_BYTE = Array.from({ length: 256 }, (_, byte) => (byte + 0x100).toString(16).slice(1));
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* No source of cryptographic randomness is reachable, so no UUID can be produced.
|
|
35
|
+
*
|
|
36
|
+
* Thrown rather than papered over with `Math.random`: see the module docstring. In a
|
|
37
|
+
* browser this means `crypto` itself is missing, which is a far older environment than the
|
|
38
|
+
* insecure-context case this module exists for — that one is handled and never reaches
|
|
39
|
+
* here.
|
|
40
|
+
*/
|
|
41
|
+
export class RandomUuidUnavailableError extends Error {
|
|
42
|
+
constructor() {
|
|
43
|
+
super(
|
|
44
|
+
"No cryptographic randomness is available: neither crypto.randomUUID nor " +
|
|
45
|
+
"crypto.getRandomValues could be reached. A UUID is not generated from a weaker " +
|
|
46
|
+
"source, because the values it stands in for are ones a collision corrupts.",
|
|
47
|
+
);
|
|
48
|
+
this.name = "RandomUuidUnavailableError";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A cryptographically random v4 UUID, in every context — secure or not.
|
|
54
|
+
*
|
|
55
|
+
* Use it instead of `crypto.randomUUID()`:
|
|
56
|
+
*
|
|
57
|
+
* ```ts
|
|
58
|
+
* const key = randomUuid();
|
|
59
|
+
* await unwrap(client.POST("/api/v1/invoices/", { body, headers: { "Idempotency-Key": key } }));
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* Uses `crypto.randomUUID` where it exists and assembles the same thing from
|
|
63
|
+
* `crypto.getRandomValues` where it does not, so the entropy is identical either way and
|
|
64
|
+
* only the assembly moves. Throws {@link RandomUuidUnavailableError} when neither is
|
|
65
|
+
* reachable.
|
|
66
|
+
*/
|
|
67
|
+
export function randomUuid(): string {
|
|
68
|
+
// Read through globalThis: `crypto` as a bare global is a ReferenceError where it is
|
|
69
|
+
// absent, and the point of this function is to answer that question rather than raise it.
|
|
70
|
+
const source: Crypto | undefined = globalThis.crypto;
|
|
71
|
+
if (source === undefined) {
|
|
72
|
+
throw new RandomUuidUnavailableError();
|
|
73
|
+
}
|
|
74
|
+
if (typeof source.randomUUID === "function") {
|
|
75
|
+
return source.randomUUID();
|
|
76
|
+
}
|
|
77
|
+
if (typeof source.getRandomValues !== "function") {
|
|
78
|
+
throw new RandomUuidUnavailableError();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const bytes = source.getRandomValues(new Uint8Array(16));
|
|
82
|
+
// The two fields RFC 9562 fixes: version 4 in the high nibble of octet 6, and the
|
|
83
|
+
// variant's `10` in the top bits of octet 8. Without these the value is 128 random bits
|
|
84
|
+
// that merely look like a UUID, and anything parsing its version reads a nonsense one.
|
|
85
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
86
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
87
|
+
|
|
88
|
+
const hex = (index: number): string => HEX_BYTE[bytes[index]];
|
|
89
|
+
return (
|
|
90
|
+
hex(0) +
|
|
91
|
+
hex(1) +
|
|
92
|
+
hex(2) +
|
|
93
|
+
hex(3) +
|
|
94
|
+
"-" +
|
|
95
|
+
hex(4) +
|
|
96
|
+
hex(5) +
|
|
97
|
+
"-" +
|
|
98
|
+
hex(6) +
|
|
99
|
+
hex(7) +
|
|
100
|
+
"-" +
|
|
101
|
+
hex(8) +
|
|
102
|
+
hex(9) +
|
|
103
|
+
"-" +
|
|
104
|
+
hex(10) +
|
|
105
|
+
hex(11) +
|
|
106
|
+
hex(12) +
|
|
107
|
+
hex(13) +
|
|
108
|
+
hex(14) +
|
|
109
|
+
hex(15)
|
|
110
|
+
);
|
|
111
|
+
}
|
package/src/styles.test.ts
CHANGED
|
@@ -986,6 +986,45 @@ describe("cascade structure", () => {
|
|
|
986
986
|
expect(base.slice(headerAt, base.indexOf("}", headerAt))).toContain("align-items: center");
|
|
987
987
|
});
|
|
988
988
|
|
|
989
|
+
it("keeps the page band one row: trail, description and actions", () => {
|
|
990
|
+
// Measured in Chromium at a 1024px viewport, against these exact declarations, with a
|
|
991
|
+
// description too long for the space left beside the trail:
|
|
992
|
+
//
|
|
993
|
+
// flex: 1 1 auto -> band 76px tall, h1 at top 0, description 1024px wide on its own
|
|
994
|
+
// line, actions on a THIRD line, and no ellipsis anywhere
|
|
995
|
+
// flex: 1 1 0 -> band 48px (the header's height), h1 / description / actions all
|
|
996
|
+
// on one row, description ellipsised
|
|
997
|
+
//
|
|
998
|
+
// Page.tsx promises the second ("badges and description sit after the title and actions
|
|
999
|
+
// at the right edge, all on that one line") and the sheet shipped the first. The
|
|
1000
|
+
// description already declared min-width: 0, overflow: hidden and text-overflow, so the
|
|
1001
|
+
// truncation looked wired -- but flex collects items into lines using HYPOTHETICAL main
|
|
1002
|
+
// sizes and only shrinks what is already on a line, so an auto basis wraps the box before
|
|
1003
|
+
// any of those three can run. This is the same defect card-heading fixed, one component
|
|
1004
|
+
// over; that test records the same argument from the other end.
|
|
1005
|
+
const base = layerBody("terp.base");
|
|
1006
|
+
const headingAt = base.indexOf('[data-terp="page-heading"] {');
|
|
1007
|
+
expect(headingAt, "page-heading should have a base rule").toBeGreaterThan(-1);
|
|
1008
|
+
const heading = base.slice(headingAt, base.indexOf("}", headingAt));
|
|
1009
|
+
expect(heading, "an auto basis wraps the action cluster onto its own line").toContain(
|
|
1010
|
+
"flex: 1 1 0",
|
|
1011
|
+
);
|
|
1012
|
+
expect(heading, "min-width: 0 is what lets an unbreakable title shrink").toContain(
|
|
1013
|
+
"min-width: 0",
|
|
1014
|
+
);
|
|
1015
|
+
// The lead line needs the same, one level in: nowrap makes its max-content the whole
|
|
1016
|
+
// sentence, so an auto basis breaks the heading's own line before it can ellipsise.
|
|
1017
|
+
const descAt = base.indexOf('[data-terp="page-description"] {');
|
|
1018
|
+
expect(descAt, "page-description should have a base rule").toBeGreaterThan(-1);
|
|
1019
|
+
const description = base.slice(descAt, base.indexOf("}", descAt));
|
|
1020
|
+
expect(description, "an auto basis gives the lead line its own row").toContain("flex: 1 1 0");
|
|
1021
|
+
// And the three declarations that do the truncating, which are only reachable from a
|
|
1022
|
+
// line the box actually shares.
|
|
1023
|
+
expect(description).toContain("min-width: 0");
|
|
1024
|
+
expect(description).toContain("white-space: nowrap");
|
|
1025
|
+
expect(description).toContain("text-overflow: ellipsis");
|
|
1026
|
+
});
|
|
1027
|
+
|
|
989
1028
|
it("gives the breadcrumb trail one line box, leaf included", () => {
|
|
990
1029
|
// The trail is a row of items that get CENTRED, so two line heights in it are two
|
|
991
1030
|
// baselines. The leaf declared 1.3 while its ancestors inherited `normal`: measured at
|
package/src/styles.ts
CHANGED
|
@@ -1983,14 +1983,25 @@ textarea[data-terp="input"] {
|
|
|
1983
1983
|
min-width: 0;
|
|
1984
1984
|
}
|
|
1985
1985
|
/* The band's left group: the trail (whose leaf is the h1), then badges, then the lead line.
|
|
1986
|
-
|
|
1987
|
-
|
|
1986
|
+
A base size of ZERO, and that is the whole of what keeps the band one row. The comment
|
|
1987
|
+
here used to claim a flex of 1 1 auto with min-width: 0 was what let the lead line truncate
|
|
1988
|
+
instead of pushing the action cluster off the row, and it is the same mistake Card made
|
|
1989
|
+
and fixed (see card-heading, and the test that records the measurement): flex collects
|
|
1990
|
+
items into lines using their HYPOTHETICAL main sizes, and only then shrinks what is on a
|
|
1991
|
+
line. With an auto basis the heading's hypothetical size is the max-content width of a
|
|
1992
|
+
trail AND a sentence, so with the band's flex-wrap the heading takes the line and the
|
|
1993
|
+
actions wrap underneath -- and the description, having reached its own line, has room and
|
|
1994
|
+
never ellipsises. Neither of the two things the comment promised actually held.
|
|
1995
|
+
|
|
1996
|
+
min-width: 0 stays, for the other half: a flex item's automatic minimum is its content's,
|
|
1997
|
+
so a long unbreakable title would otherwise refuse to shrink past it. Both are asserted in
|
|
1998
|
+
styles.test.ts, because dropping either brings a different half of the bug back. */
|
|
1988
1999
|
[data-terp="page-heading"] {
|
|
1989
2000
|
display: flex;
|
|
1990
2001
|
flex-wrap: wrap;
|
|
1991
2002
|
align-items: center;
|
|
1992
2003
|
gap: var(--space-2) var(--space-3);
|
|
1993
|
-
flex: 1 1
|
|
2004
|
+
flex: 1 1 0;
|
|
1994
2005
|
min-width: 0;
|
|
1995
2006
|
}
|
|
1996
2007
|
/* The single h1 of the view, and now also the trail's current crumb: one node instead of two
|
|
@@ -2025,10 +2036,15 @@ textarea[data-terp="input"] {
|
|
|
2025
2036
|
}
|
|
2026
2037
|
/* The lead line: one short sentence about the page, truncated rather than wrapped, because
|
|
2027
2038
|
the band has a height and prose that wraps would set it. A page whose explanation does not
|
|
2028
|
-
fit on one line is describing its body, and that belongs in the body.
|
|
2039
|
+
fit on one line is describing its body, and that belongs in the body.
|
|
2040
|
+
|
|
2041
|
+
Zero basis for the same reason the heading has one, one level in: nowrap makes this box's
|
|
2042
|
+
max-content the whole unwrapped sentence, so an auto basis breaks the heading's line before
|
|
2043
|
+
any of the three declarations below get a chance to run. The truncation is only reachable
|
|
2044
|
+
from a line the box actually shares. */
|
|
2029
2045
|
[data-terp="page-description"] {
|
|
2030
2046
|
margin: 0;
|
|
2031
|
-
flex: 1 1
|
|
2047
|
+
flex: 1 1 0;
|
|
2032
2048
|
min-width: 0;
|
|
2033
2049
|
color: var(--color-fg-subtle);
|
|
2034
2050
|
font-size: var(--font-size-sm);
|
|
@@ -3159,6 +3175,10 @@ th[data-terp="dataview-actions-cell"] > span {
|
|
|
3159
3175
|
/* The bar reads only the inline half of the cell padding, with --space-2
|
|
3160
3176
|
vertically, so its left edge stays flush with the first cell's text at either
|
|
3161
3177
|
density — the same bargain the toolbar strikes at the other end of the box. */
|
|
3178
|
+
/* min-height is what lets the bar say nothing. While the total is unknown the range span
|
|
3179
|
+
is empty and the pager is absent, so without a floor the bar collapses to its padding and
|
|
3180
|
+
the whole footer jumps the moment the count lands -- which is the layout shift the
|
|
3181
|
+
fixed-height skeleton above it exists to avoid. One line box of the bar's own type. */
|
|
3162
3182
|
[data-terp="dataview-pagination"] {
|
|
3163
3183
|
display: flex;
|
|
3164
3184
|
align-items: center;
|
|
@@ -3166,6 +3186,8 @@ th[data-terp="dataview-actions-cell"] > span {
|
|
|
3166
3186
|
gap: var(--space-3);
|
|
3167
3187
|
flex-wrap: wrap;
|
|
3168
3188
|
padding-block: var(--space-2);
|
|
3189
|
+
min-height: calc(var(--font-size-sm) * var(--font-line-height-base) + 2 * var(--space-2));
|
|
3190
|
+
box-sizing: border-box;
|
|
3169
3191
|
font-size: var(--font-size-sm);
|
|
3170
3192
|
color: var(--color-fg-subtle);
|
|
3171
3193
|
}
|
package/src/uiText.tsx
CHANGED
|
@@ -98,6 +98,10 @@ export interface TerpStrings {
|
|
|
98
98
|
moreActions: string;
|
|
99
99
|
/** Default {@link ErrorState} title. */
|
|
100
100
|
errorTitle: string;
|
|
101
|
+
/** Title shown by `RequireAuth` when the backend did not answer the boot check. */
|
|
102
|
+
backendUnreachableTitle: string;
|
|
103
|
+
/** Explanation shown with {@link TerpStrings.backendUnreachableTitle}. */
|
|
104
|
+
backendUnreachableDescription: string;
|
|
101
105
|
/** Default confirm-button label of {@link ConfirmDialog}. */
|
|
102
106
|
confirm: string;
|
|
103
107
|
/** Default cancel-button label of {@link ConfirmDialog}. */
|
|
@@ -333,6 +337,10 @@ export const DEFAULT_STRINGS: TerpStrings = {
|
|
|
333
337
|
moduleNavigationLabel: "Module navigation",
|
|
334
338
|
moreActions: "More actions",
|
|
335
339
|
errorTitle: "Something went wrong.",
|
|
340
|
+
backendUnreachableTitle: "The application cannot reach its server.",
|
|
341
|
+
backendUnreachableDescription:
|
|
342
|
+
"No answer came back from the API. It may still be starting, or stopped. "
|
|
343
|
+
+ "Reload once it is running.",
|
|
336
344
|
confirm: "Confirm",
|
|
337
345
|
cancel: "Cancel",
|
|
338
346
|
successTitle: "Success",
|