@terpjs/react-core 0.21.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/admin/GroupCreate.tsx +1 -1
- package/src/admin/UserCreate.tsx +1 -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/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/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",
|
|
@@ -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
|
|
|
@@ -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";
|
|
@@ -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
|
}
|