@terpjs/react-core 0.25.0 → 0.28.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 +31 -7
- package/package.json +6 -5
- package/src/Field.test.tsx +95 -1
- package/src/Field.tsx +70 -1
- package/src/LoginView.test.tsx +33 -0
- package/src/LoginView.tsx +36 -23
- package/src/Meter.test.tsx +304 -0
- package/src/Meter.tsx +159 -0
- package/src/QuietActions.test.tsx +118 -0
- package/src/QuietActions.tsx +75 -0
- package/src/UserMenu.test.tsx +23 -0
- package/src/UserMenu.tsx +9 -1
- package/src/admin/AuditLogAdmin.tsx +1 -1
- package/src/admin/admin.test.tsx +57 -5
- package/src/admin/module.tsx +9 -6
- package/src/bootstrap.test.tsx +1 -1
- package/src/bootstrap.tsx +2 -1
- package/src/dataview/DataView.test.tsx +70 -0
- package/src/dataview/README.md +5 -3
- package/src/dataview/index.ts +1 -1
- package/src/dataview/internal.tsx +76 -19
- package/src/dataview/types.ts +9 -35
- package/src/errorMessages.test.tsx +21 -0
- package/src/errorMessages.tsx +33 -19
- package/src/index.ts +7 -3
- package/src/locale.test.tsx +35 -0
- package/src/locale.tsx +62 -4
- package/src/markers.test.ts +33 -11
- package/src/ssr.test.tsx +18 -0
- package/src/styles.test.ts +341 -33
- package/src/styles.ts +546 -71
- package/src/testing.test.tsx +162 -0
- package/src/testing.ts +84 -0
- package/src/tokens.guard.test.ts +11 -6
- package/src/ui/controlMessages.tsx +27 -14
- package/src/uiText.literals.test.ts +19 -6
- package/src/uiText.test.tsx +54 -2
- package/src/uiText.tsx +166 -6
- package/vitest.setup.ts +7 -20
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
import type { ReactNode } from "react";
|
|
5
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
6
|
+
|
|
7
|
+
import { ConfirmDialog } from "./ConfirmDialog";
|
|
8
|
+
import { installDialogPolyfill } from "./testing";
|
|
9
|
+
import { Combobox } from "./ui/Combobox";
|
|
10
|
+
|
|
11
|
+
afterEach(cleanup);
|
|
12
|
+
|
|
13
|
+
// The setup file has already installed the polyfill here — the same call a generated app's
|
|
14
|
+
// setup file makes — so these tests drive it the way an app's test would: with key events.
|
|
15
|
+
// ConfirmDialog's own tests (feedback.test.tsx) dispatch `cancel` by hand to reach its
|
|
16
|
+
// handler; whether an Escape ever produces that event is the step this file exists to hold.
|
|
17
|
+
|
|
18
|
+
function OwnedDialog(props: {
|
|
19
|
+
onOpenChange: (open: boolean) => void;
|
|
20
|
+
isPending?: boolean;
|
|
21
|
+
description?: ReactNode;
|
|
22
|
+
}) {
|
|
23
|
+
const [open, setOpen] = useState(true);
|
|
24
|
+
return (
|
|
25
|
+
<ConfirmDialog
|
|
26
|
+
open={open}
|
|
27
|
+
onOpenChange={(next) => {
|
|
28
|
+
props.onOpenChange(next);
|
|
29
|
+
setOpen(next);
|
|
30
|
+
}}
|
|
31
|
+
onConfirm={() => {}}
|
|
32
|
+
title="Delete this record?"
|
|
33
|
+
description={props.description}
|
|
34
|
+
isPending={props.isPending}
|
|
35
|
+
/>
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A bare dialog in the document, removed again by the caller. */
|
|
40
|
+
function bareDialog(): HTMLDialogElement {
|
|
41
|
+
return document.body.appendChild(document.createElement("dialog"));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
describe("installDialogPolyfill", () => {
|
|
45
|
+
it("dismisses a ConfirmDialog on Escape, through the cancel event a browser fires", () => {
|
|
46
|
+
const onOpenChange = vi.fn();
|
|
47
|
+
render(<OwnedDialog onOpenChange={onOpenChange} />);
|
|
48
|
+
|
|
49
|
+
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
|
|
50
|
+
|
|
51
|
+
expect(onOpenChange).toHaveBeenCalledWith(false);
|
|
52
|
+
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("keeps a pending ConfirmDialog open on Escape, because it cancels that event", () => {
|
|
56
|
+
const onOpenChange = vi.fn();
|
|
57
|
+
render(<OwnedDialog onOpenChange={onOpenChange} isPending />);
|
|
58
|
+
|
|
59
|
+
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
|
|
60
|
+
|
|
61
|
+
// Closing regardless of the cancel would hide the dialog while its owner still holds it
|
|
62
|
+
// open — a test of the pending guard that could not fail.
|
|
63
|
+
expect(onOpenChange).not.toHaveBeenCalled();
|
|
64
|
+
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("leaves the dialog open when a control inside it takes the Escape", () => {
|
|
68
|
+
// A Combobox cancels its own Escape to close its option list. That is not a close request
|
|
69
|
+
// in a browser (measured in Chromium), so the first Escape closes the list and only the
|
|
70
|
+
// second reaches the dialog.
|
|
71
|
+
const onOpenChange = vi.fn();
|
|
72
|
+
render(
|
|
73
|
+
<OwnedDialog
|
|
74
|
+
onOpenChange={onOpenChange}
|
|
75
|
+
description={
|
|
76
|
+
<Combobox
|
|
77
|
+
aria-label="Group"
|
|
78
|
+
options={[
|
|
79
|
+
{ value: "a", label: "Alpha" },
|
|
80
|
+
{ value: "b", label: "Beta" },
|
|
81
|
+
]}
|
|
82
|
+
/>
|
|
83
|
+
}
|
|
84
|
+
/>,
|
|
85
|
+
);
|
|
86
|
+
const input = screen.getByRole("combobox", { name: /Group/ });
|
|
87
|
+
fireEvent.focus(input);
|
|
88
|
+
expect(input).toHaveAttribute("aria-expanded", "true");
|
|
89
|
+
|
|
90
|
+
fireEvent.keyDown(input, { key: "Escape" });
|
|
91
|
+
expect(input).toHaveAttribute("aria-expanded", "false");
|
|
92
|
+
expect(onOpenChange).not.toHaveBeenCalled();
|
|
93
|
+
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
|
94
|
+
|
|
95
|
+
fireEvent.keyDown(input, { key: "Escape" });
|
|
96
|
+
expect(onOpenChange).toHaveBeenCalledWith(false);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it("closes a modal nobody handles on Escape, and on no other key", () => {
|
|
100
|
+
const dialog = bareDialog();
|
|
101
|
+
try {
|
|
102
|
+
const closed = vi.fn();
|
|
103
|
+
dialog.addEventListener("close", closed);
|
|
104
|
+
dialog.showModal();
|
|
105
|
+
|
|
106
|
+
fireEvent.keyDown(dialog, { key: "Enter" });
|
|
107
|
+
expect(dialog.open).toBe(true);
|
|
108
|
+
|
|
109
|
+
fireEvent.keyDown(dialog, { key: "Escape" });
|
|
110
|
+
expect(dialog.open).toBe(false);
|
|
111
|
+
expect(closed).toHaveBeenCalledTimes(1);
|
|
112
|
+
} finally {
|
|
113
|
+
dialog.remove();
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("asks only the topmost modal, and skips one that has left the document", () => {
|
|
118
|
+
const lower = bareDialog();
|
|
119
|
+
const upper = bareDialog();
|
|
120
|
+
try {
|
|
121
|
+
const asked: string[] = [];
|
|
122
|
+
lower.addEventListener("cancel", () => asked.push("lower"));
|
|
123
|
+
upper.addEventListener("cancel", () => asked.push("upper"));
|
|
124
|
+
lower.showModal();
|
|
125
|
+
upper.showModal();
|
|
126
|
+
|
|
127
|
+
fireEvent.keyDown(document.body, { key: "Escape" });
|
|
128
|
+
expect(asked).toEqual(["upper"]);
|
|
129
|
+
expect(lower.open).toBe(true);
|
|
130
|
+
|
|
131
|
+
// Opened again and then removed while open. A browser takes it out of the top layer with
|
|
132
|
+
// the removal (measured in Chromium), so the next Escape belongs to the one beneath.
|
|
133
|
+
upper.showModal();
|
|
134
|
+
upper.remove();
|
|
135
|
+
fireEvent.keyDown(document.body, { key: "Escape" });
|
|
136
|
+
expect(asked).toEqual(["upper", "lower"]);
|
|
137
|
+
expect(lower.open).toBe(false);
|
|
138
|
+
} finally {
|
|
139
|
+
lower.remove();
|
|
140
|
+
upper.remove();
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("stands aside where the environment already implements showModal", () => {
|
|
145
|
+
const proto = HTMLDialogElement.prototype;
|
|
146
|
+
const installed = { showModal: proto.showModal, close: proto.close };
|
|
147
|
+
const native = {
|
|
148
|
+
showModal: function showModal() {},
|
|
149
|
+
close: function close() {},
|
|
150
|
+
};
|
|
151
|
+
proto.showModal = native.showModal;
|
|
152
|
+
proto.close = native.close;
|
|
153
|
+
try {
|
|
154
|
+
installDialogPolyfill();
|
|
155
|
+
expect(proto.showModal).toBe(native.showModal);
|
|
156
|
+
expect(proto.close).toBe(native.close);
|
|
157
|
+
} finally {
|
|
158
|
+
proto.showModal = installed.showModal;
|
|
159
|
+
proto.close = installed.close;
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
});
|
package/src/testing.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit-test support for the components in this package, published at the
|
|
3
|
+
* `@terpjs/react-core/testing` subpath rather than the package root, so none of it arrives in
|
|
4
|
+
* an app's production code through the import every screen already has (ADR 0155). Its two
|
|
5
|
+
* callers are the vitest setup files: this package's own, and the one every generated app
|
|
6
|
+
* ships.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Give jsdom enough of the native `<dialog>` modal API for `ConfirmDialog` to open, confirm
|
|
11
|
+
* and dismiss under a unit test the way it does in a browser.
|
|
12
|
+
*
|
|
13
|
+
* jsdom implements the element and its `open` attribute but not `showModal()` or `close()`,
|
|
14
|
+
* and `ConfirmDialog` — the one dialog an app may render — calls both, so without this any
|
|
15
|
+
* test that opens one throws `showModal is not a function`.
|
|
16
|
+
*
|
|
17
|
+
* What it reproduces, each measured against Chromium's own implementation:
|
|
18
|
+
*
|
|
19
|
+
* - `showModal()` sets `open`; `close()` clears it and fires `close`.
|
|
20
|
+
* - **Escape fires a cancelable `cancel` at the topmost open modal, and closes it unless that
|
|
21
|
+
* event is cancelled.** This is the one that matters: `ConfirmDialog`'s Escape handling
|
|
22
|
+
* lives in its `cancel` handler, which cancels the event and asks its owner to close —
|
|
23
|
+
* or, while `isPending`, cancels it and does nothing. Without this, a test pressing
|
|
24
|
+
* Escape would see nothing happen, and a test of the pending state would pass whether
|
|
25
|
+
* or not the guard worked.
|
|
26
|
+
* - An Escape `keydown` whose default was prevented is not a close request — so a
|
|
27
|
+
* `Combobox` inside the dialog, which cancels its own Escape to close its option list,
|
|
28
|
+
* closes that list and leaves the dialog open, as it does in a browser.
|
|
29
|
+
* - Only the topmost modal is asked, and a modal removed from the document while open has
|
|
30
|
+
* left the top layer, so it is skipped rather than handed an Escape meant for the one
|
|
31
|
+
* beneath it.
|
|
32
|
+
*
|
|
33
|
+
* What it does NOT reproduce, so a test must not rely on it: focus (a browser moves focus
|
|
34
|
+
* into the dialog on open and back to the opener on close), inertness of the page behind a
|
|
35
|
+
* modal, the backdrop, and the event timing (`close` fires synchronously here, a task later
|
|
36
|
+
* in a browser). An Escape whose propagation is stopped before it reaches `window` is also
|
|
37
|
+
* missed here, where a browser would still close, and `close()` on a dialog that is not open
|
|
38
|
+
* still fires `close` here, where a browser does nothing. Those belong to the Playwright
|
|
39
|
+
* suite, which runs a real browser.
|
|
40
|
+
*
|
|
41
|
+
* A no-op wherever `HTMLDialogElement` is absent (a node-environment test file sharing the
|
|
42
|
+
* setup file) or already has `showModal` — an environment with a real one owns the whole
|
|
43
|
+
* modal contract, Escape included, and a second implementation beside it would hand every
|
|
44
|
+
* Escape to the dialog twice. Calling it again is therefore harmless.
|
|
45
|
+
*/
|
|
46
|
+
export function installDialogPolyfill(): void {
|
|
47
|
+
if (typeof HTMLDialogElement === "undefined") {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const proto = HTMLDialogElement.prototype as {
|
|
51
|
+
showModal?: (this: HTMLDialogElement) => void;
|
|
52
|
+
close?: (this: HTMLDialogElement) => void;
|
|
53
|
+
};
|
|
54
|
+
if (typeof proto.showModal === "function") {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The top layer, in the order its modals were opened: the last one still in the document
|
|
59
|
+
// is the one Escape reaches. A Set keeps insertion order, and forgetting a dialog that was
|
|
60
|
+
// never shown is a no-op rather than a case to guard.
|
|
61
|
+
const topLayer = new Set<HTMLDialogElement>();
|
|
62
|
+
|
|
63
|
+
proto.showModal = function showModal() {
|
|
64
|
+
this.setAttribute("open", "");
|
|
65
|
+
topLayer.add(this);
|
|
66
|
+
};
|
|
67
|
+
proto.close = function close() {
|
|
68
|
+
this.removeAttribute("open");
|
|
69
|
+
topLayer.delete(this);
|
|
70
|
+
this.dispatchEvent(new Event("close"));
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// Bubble phase on `window`, the last stop before a browser's own default handling, so a
|
|
74
|
+
// component inside the dialog that cancels its Escape has already had the chance to.
|
|
75
|
+
window.addEventListener("keydown", (event) => {
|
|
76
|
+
if (event.key !== "Escape" || event.defaultPrevented) {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const topmost = [...topLayer].filter((dialog) => dialog.isConnected).at(-1);
|
|
80
|
+
if (topmost?.dispatchEvent(new Event("cancel", { cancelable: true }))) {
|
|
81
|
+
topmost.close();
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
package/src/tokens.guard.test.ts
CHANGED
|
@@ -103,15 +103,17 @@ const UNREAD_TOKENS: Record<string, string[]> = {
|
|
|
103
103
|
// still catches the sixteenth. `--color-sidebar-` stays above because it makes a narrower
|
|
104
104
|
// claim worth keeping: that family is read in full.
|
|
105
105
|
//
|
|
106
|
-
// None of these
|
|
107
|
-
// ahead of its consumers —
|
|
106
|
+
// None of these fourteen is a defect on its own. They are a published vocabulary that shipped
|
|
107
|
+
// ahead of its consumers — three surface tokens, three borders, one interactive state, a
|
|
108
108
|
// five-step chart ramp and two neutrals — and the point of booking them is that the list can
|
|
109
|
-
// only shrink from here, so wiring one is visible and adding a
|
|
109
|
+
// only shrink from here, so wiring one is visible and adding a fifteenth has to argue.
|
|
110
|
+
//
|
|
111
|
+
// --color-bg-surface came off it when the surface model went back to filling its in-flow
|
|
112
|
+
// blocks: card, hubcard-body, profile-card, resource-list-row, empty-state, dataview-card and
|
|
113
|
+
// the full DataView's frame all name it now. That is the shrink this list was booked for.
|
|
110
114
|
"--color-": [
|
|
111
115
|
"--color-bg-canvas",
|
|
112
|
-
"--color-bg-inset",
|
|
113
116
|
"--color-bg-raised",
|
|
114
|
-
"--color-bg-surface",
|
|
115
117
|
"--color-border-default",
|
|
116
118
|
"--color-border-strong",
|
|
117
119
|
"--color-border-subtle",
|
|
@@ -145,7 +147,10 @@ const BARE_TYPE_LITERALS: Record<string, Record<string, number>> = {
|
|
|
145
147
|
// naming a token would pin it to whatever that header uses TODAY. The UA stylesheet resets
|
|
146
148
|
// letter-spacing on form controls, so inheritance has to be asked for explicitly — the
|
|
147
149
|
// header and its button were rendering two different treatments side by side until it was.
|
|
148
|
-
|
|
150
|
+
//
|
|
151
|
+
// One `0` retired when page-title took --font-letter-spacing-tight: the leaf is set at lg now,
|
|
152
|
+
// and the tight step is worth a third of a pixel there where at sm it was worth nothing.
|
|
153
|
+
"letter-spacing": { "0": 3, "0.04em": 1, "0.06em": 1, inherit: 1 },
|
|
149
154
|
};
|
|
150
155
|
|
|
151
156
|
describe("design tokens", () => {
|
|
@@ -47,20 +47,33 @@ export function useControlMessages(
|
|
|
47
47
|
return {
|
|
48
48
|
hasError,
|
|
49
49
|
describedBy,
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
50
|
+
// One box around both, and it is rendered ONLY when there is something to say.
|
|
51
|
+
// That condition is the whole of why this is safe: an envelope emitted
|
|
52
|
+
// unconditionally would add a grid row and a gap to every field in every app that
|
|
53
|
+
// carries neither a hint nor an error, which is most of them, and the change would
|
|
54
|
+
// arrive as a few pixels of drift on screens nobody touched. With the guard, a field
|
|
55
|
+
// with no messages renders exactly the DOM it rendered before.
|
|
56
|
+
//
|
|
57
|
+
// What the box buys is FieldRow. There, a field spans three shared lines -- label,
|
|
58
|
+
// control, messages -- and two loose spans would take two of them, so a field with
|
|
59
|
+
// both a hint and an error would push its own messages line down and every other
|
|
60
|
+
// field's with it. As one box they occupy the third line together and stack inside
|
|
61
|
+
// it, which is also the arrangement they already had.
|
|
62
|
+
messages:
|
|
63
|
+
hint === undefined && !hasError ? null : (
|
|
64
|
+
<div data-terp="field-messages">
|
|
65
|
+
{hint !== undefined && (
|
|
66
|
+
<span id={hintId} data-terp="field-hint">
|
|
67
|
+
{resolve(hint)}
|
|
68
|
+
</span>
|
|
69
|
+
)}
|
|
70
|
+
{hasError && (
|
|
71
|
+
<span id={errorId} role="alert" data-terp="field-error">
|
|
72
|
+
{error}
|
|
73
|
+
</span>
|
|
74
|
+
)}
|
|
75
|
+
</div>
|
|
76
|
+
),
|
|
64
77
|
};
|
|
65
78
|
}
|
|
66
79
|
|
|
@@ -160,7 +160,7 @@ describe("user-facing strings", () => {
|
|
|
160
160
|
).toEqual([]);
|
|
161
161
|
});
|
|
162
162
|
|
|
163
|
-
it("never defaults a UiText prop
|
|
163
|
+
it("never defaults a UiText prop, or fills a table of them, with a bare string", () => {
|
|
164
164
|
// The subtler half, and the one that looks fine in review. A `UiText` prop defaulted to
|
|
165
165
|
// `"Select date"` IS overridable — and still untranslatable: a plain string resolves
|
|
166
166
|
// as-is, so an app that does not pass the prop shows English in every locale. The fix is
|
|
@@ -181,9 +181,20 @@ describe("user-facing strings", () => {
|
|
|
181
181
|
// (`const { value, onChange, removeLabel = "Remove", ...rest } = props`) was
|
|
182
182
|
// invisible, and became visible only when the line was split for unrelated reasons.
|
|
183
183
|
// A check that a reformat can switch on and off is not a check.
|
|
184
|
-
|
|
184
|
+
//
|
|
185
|
+
// And a property as well as a default (`:` beside `=`), which is the shape a whole
|
|
186
|
+
// second string table takes. DataView's strings were an interface of `UiText` keys
|
|
187
|
+
// with an object of English values under it, in one file, and this check read every
|
|
188
|
+
// line of it without a finding, because a table entry is `searchPlaceholder: "Search…"`
|
|
189
|
+
// and the check only knew `=`. Every one of those strings rendered in English under
|
|
190
|
+
// every locale, and the completeness guard in locale.test.tsx could not see them
|
|
191
|
+
// either, because they were not in the table it walks.
|
|
192
|
+
for (const assignment of line.matchAll(/(\w+)\s*([=:])\s*"([A-Za-z][^"]*)"/g)) {
|
|
185
193
|
if (uiTextProps.has(assignment[1]!)) {
|
|
186
|
-
offenders.push(
|
|
194
|
+
offenders.push(
|
|
195
|
+
`${file}:${index + 1} ${assignment[1]}${assignment[2] === ":" ? ":" : " ="} ` +
|
|
196
|
+
`"${assignment[3]}"`,
|
|
197
|
+
);
|
|
187
198
|
}
|
|
188
199
|
}
|
|
189
200
|
});
|
|
@@ -191,9 +202,11 @@ describe("user-facing strings", () => {
|
|
|
191
202
|
|
|
192
203
|
expect(
|
|
193
204
|
offenders,
|
|
194
|
-
"a UiText prop defaulted to a plain string
|
|
195
|
-
"
|
|
196
|
-
"
|
|
205
|
+
"a UiText prop defaulted to a plain string — or a table of plain strings under an " +
|
|
206
|
+
"interface of UiText keys — renders that string in every locale for any app that does " +
|
|
207
|
+
"not override it: the prop is translatable and its default is not. Leave the default " +
|
|
208
|
+
"`undefined` and fall back to a TerpStrings key at the use site; a set of defaults " +
|
|
209
|
+
"belongs in TerpStrings itself, where every locale catalog must translate it.",
|
|
197
210
|
).toEqual([]);
|
|
198
211
|
});
|
|
199
212
|
});
|
package/src/uiText.test.tsx
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// @vitest-environment jsdom
|
|
2
2
|
import { cleanup, render, screen } from "@testing-library/react";
|
|
3
|
-
import { afterEach, describe, expect, it } from "vitest";
|
|
3
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
4
|
+
import { defineModuleManifest } from "@terpjs/contract";
|
|
5
|
+
import type { FrameworkText, UiText } from "@terpjs/contract";
|
|
4
6
|
|
|
5
7
|
import { Page } from "./Page";
|
|
6
8
|
import { ResourceList } from "./ResourceList";
|
|
7
9
|
import { TerpProvider } from "./TerpProvider";
|
|
8
|
-
import { resolveUiText, resolveUiTextNode, UiTextProvider } from "./uiText";
|
|
10
|
+
import { resolveUiText, resolveUiTextNode, UiTextProvider, useUiText } from "./uiText";
|
|
9
11
|
|
|
10
12
|
afterEach(cleanup);
|
|
11
13
|
|
|
@@ -105,3 +107,53 @@ describe("UiTextProvider", () => {
|
|
|
105
107
|
expect(screen.getByText("Nog niets.")).toBeInTheDocument();
|
|
106
108
|
});
|
|
107
109
|
});
|
|
110
|
+
|
|
111
|
+
describe("FrameworkText", () => {
|
|
112
|
+
function Label({ text }: { text: UiText | FrameworkText }) {
|
|
113
|
+
const resolve = useUiText();
|
|
114
|
+
return <span>{resolve(text)}</span>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
it("reads the active framework strings and never reaches the app's resolver", () => {
|
|
118
|
+
// The app's resolver is the one that treats a descriptor's `message` as source-locale text,
|
|
119
|
+
// which is exactly what framework copy is not. Handed a FrameworkText, this one would say so.
|
|
120
|
+
const appResolver = vi.fn((text: UiText) =>
|
|
121
|
+
typeof text === "string" ? text : `app:${text.id}`,
|
|
122
|
+
);
|
|
123
|
+
render(
|
|
124
|
+
<UiTextProvider strings={{ admin: "Beheer" }} resolveText={appResolver}>
|
|
125
|
+
<Label text={{ framework: "admin" }} />
|
|
126
|
+
</UiTextProvider>,
|
|
127
|
+
);
|
|
128
|
+
expect(screen.getByText("Beheer")).toBeInTheDocument();
|
|
129
|
+
expect(appResolver).not.toHaveBeenCalled();
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("refuses a key the table does not have, including one it only inherits", () => {
|
|
133
|
+
// Cast past the type on purpose: this is the manifest a typecheck never saw.
|
|
134
|
+
const misspelt = { framework: "admn" } as unknown as FrameworkText;
|
|
135
|
+
expect(() => render(<Label text={misspelt} />)).toThrow(
|
|
136
|
+
/FrameworkText names "admn", which is not a framework string/,
|
|
137
|
+
);
|
|
138
|
+
const inherited = { framework: "toString" } as unknown as FrameworkText;
|
|
139
|
+
expect(() => render(<Label text={inherited} />)).toThrow(/names "toString"/);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("is a typecheck error for a key the table does not have", () => {
|
|
143
|
+
// The directive is the test, and `tsc --noEmit` is what runs it: it fails as unused the
|
|
144
|
+
// moment a misspelt key compiles, as one would if the key were widened to `string`. The
|
|
145
|
+
// assertion below only proves the literal is still an ordinary manifest at runtime.
|
|
146
|
+
const manifest = defineModuleManifest({
|
|
147
|
+
name: "typo",
|
|
148
|
+
routes: [],
|
|
149
|
+
nav: [
|
|
150
|
+
{
|
|
151
|
+
// @ts-expect-error "admn" is not a TerpStrings key.
|
|
152
|
+
label: { framework: "admn" },
|
|
153
|
+
to: "/",
|
|
154
|
+
},
|
|
155
|
+
],
|
|
156
|
+
});
|
|
157
|
+
expect(manifest.nav).toHaveLength(1);
|
|
158
|
+
});
|
|
159
|
+
});
|
package/src/uiText.tsx
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import { createContext, useCallback, useContext, useMemo } from "react";
|
|
2
2
|
import type { ReactNode } from "react";
|
|
3
|
-
import type { UiText } from "@terpjs/contract";
|
|
3
|
+
import type { FrameworkText, UiText } from "@terpjs/contract";
|
|
4
4
|
|
|
5
5
|
export type { UiText } from "@terpjs/contract";
|
|
6
6
|
|
|
7
|
+
// The keys a manifest's `FrameworkText` may name are this table's, so a misspelt one is a
|
|
8
|
+
// typecheck error where the manifest is written rather than an empty label on screen.
|
|
9
|
+
declare module "@terpjs/contract" {
|
|
10
|
+
interface TerpFrameworkStrings extends TerpStrings {}
|
|
11
|
+
}
|
|
12
|
+
|
|
7
13
|
/**
|
|
8
14
|
* A piece of user-facing text: either a plain string (used as-is) or a message
|
|
9
15
|
* descriptor — a stable `id` for a translation catalog plus the source-language
|
|
@@ -281,6 +287,8 @@ export interface TerpStrings {
|
|
|
281
287
|
whenColumn: string;
|
|
282
288
|
/** Audit admin: expanded row's payload heading. */
|
|
283
289
|
details: string;
|
|
290
|
+
/** Audit admin: expanded row's label for the request that caused the event. */
|
|
291
|
+
requestLabel: string;
|
|
284
292
|
/** Generic success toast after a saved mutation. */
|
|
285
293
|
saved: string;
|
|
286
294
|
/** Generic failure toast when a request did not go through. */
|
|
@@ -303,6 +311,91 @@ export interface TerpStrings {
|
|
|
303
311
|
selectDate: string;
|
|
304
312
|
/** DateRangePicker: trigger text before a range is chosen. */
|
|
305
313
|
selectDateRange: string;
|
|
314
|
+
// DataView. Framework copy like everything above, so a locale catalog translates it and the
|
|
315
|
+
// completeness check requires it; `DataView`'s per-instance `strings` prop still wins. Kept
|
|
316
|
+
// apart from the similar keys above (`loading`, `errorTitle`, `moreActions`,
|
|
317
|
+
// `clearSelection`) on purpose: the English differs, and a translation may too.
|
|
318
|
+
/** DataView: the search box's placeholder and accessible name. */
|
|
319
|
+
dataViewSearchPlaceholder: string;
|
|
320
|
+
/** DataView: clears the search box. */
|
|
321
|
+
dataViewClearSearch: string;
|
|
322
|
+
/** DataView: the toolbar action that resets the caller's filters. */
|
|
323
|
+
dataViewClearFilters: string;
|
|
324
|
+
/** DataView: the column-settings menu trigger. */
|
|
325
|
+
dataViewViewOptions: string;
|
|
326
|
+
/** DataView: heading of the column list inside the column-settings menu. */
|
|
327
|
+
dataViewColumns: string;
|
|
328
|
+
/** DataView: moves a column earlier; prefixed to the column's name. */
|
|
329
|
+
dataViewMoveUp: string;
|
|
330
|
+
/** DataView: moves a column later; prefixed to the column's name. */
|
|
331
|
+
dataViewMoveDown: string;
|
|
332
|
+
/** DataView: switches to the table layout. */
|
|
333
|
+
dataViewTableView: string;
|
|
334
|
+
/** DataView: switches to the card layout. */
|
|
335
|
+
dataViewCardView: string;
|
|
336
|
+
/** DataView: the page-size selector. */
|
|
337
|
+
dataViewPageSize: string;
|
|
338
|
+
/** DataView: the footer's result range; `{from}`, `{to}` and `{total}` are replaced. */
|
|
339
|
+
dataViewResultsRange: string;
|
|
340
|
+
/** DataView: the footer's page position; `{page}` and `{pages}` are replaced. */
|
|
341
|
+
dataViewPageOf: string;
|
|
342
|
+
/** DataView: pagination, to the first page. */
|
|
343
|
+
dataViewFirstPage: string;
|
|
344
|
+
/** DataView: pagination, one page back. */
|
|
345
|
+
dataViewPreviousPage: string;
|
|
346
|
+
/** DataView: pagination, one page forward. */
|
|
347
|
+
dataViewNextPage: string;
|
|
348
|
+
/** DataView: pagination, to the last page. */
|
|
349
|
+
dataViewLastPage: string;
|
|
350
|
+
/** DataView: the header checkbox that selects every row on the page. */
|
|
351
|
+
dataViewSelectAllPage: string;
|
|
352
|
+
/** DataView: a row's selection checkbox. */
|
|
353
|
+
dataViewSelectRow: string;
|
|
354
|
+
/** DataView: the selection count; `{count}` is replaced. */
|
|
355
|
+
dataViewSelected: string;
|
|
356
|
+
/** DataView: widens the selection to every result; `{total}` is replaced. */
|
|
357
|
+
dataViewSelectAllResults: string;
|
|
358
|
+
/** DataView: clears the row selection. */
|
|
359
|
+
dataViewClearSelection: string;
|
|
360
|
+
/** DataView: the row-action and batch-action overflow trigger. */
|
|
361
|
+
dataViewMoreActions: string;
|
|
362
|
+
/** DataView: the actions column header. */
|
|
363
|
+
dataViewActions: string;
|
|
364
|
+
/** DataView: a row's open button; `{label}` is replaced by the record's name. */
|
|
365
|
+
dataViewOpenRow: string;
|
|
366
|
+
/** DataView: opens a row's detail panel. */
|
|
367
|
+
dataViewExpandRow: string;
|
|
368
|
+
/** DataView: closes a row's detail panel. */
|
|
369
|
+
dataViewCollapseRow: string;
|
|
370
|
+
/** DataView: the empty state when the caller passes no `emptyMessage`. */
|
|
371
|
+
dataViewEmpty: string;
|
|
372
|
+
/** DataView: the first load's placeholder. */
|
|
373
|
+
dataViewLoading: string;
|
|
374
|
+
/** DataView: shown while a refetch replaces rows already on screen. */
|
|
375
|
+
dataViewRefreshing: string;
|
|
376
|
+
/** DataView: the error state's title. */
|
|
377
|
+
dataViewErrorTitle: string;
|
|
378
|
+
/** DataView: a column's resize handle; prefixed to the column's name. */
|
|
379
|
+
dataViewResizeColumn: string;
|
|
380
|
+
// The wording for the platform's own `AppError` codes, which `useErrorMessage` shows in place
|
|
381
|
+
// of the backend's `detail`. An app's `errorMessages` map still wins for any code it names,
|
|
382
|
+
// including these; a code neither side words falls back to the `detail`.
|
|
383
|
+
/** Error code `bad_request`. */
|
|
384
|
+
errorCodeBadRequest: string;
|
|
385
|
+
/** Error code `validation_failed`. */
|
|
386
|
+
errorCodeValidationFailed: string;
|
|
387
|
+
/** Error code `invalid_token`. */
|
|
388
|
+
errorCodeInvalidToken: string;
|
|
389
|
+
/** Error code `authentication_required`. */
|
|
390
|
+
errorCodeAuthenticationRequired: string;
|
|
391
|
+
/** Error code `permission_denied`. */
|
|
392
|
+
errorCodePermissionDenied: string;
|
|
393
|
+
/** Error code `not_found`. */
|
|
394
|
+
errorCodeNotFound: string;
|
|
395
|
+
/** Error code `conflict`. */
|
|
396
|
+
errorCodeConflict: string;
|
|
397
|
+
/** Error code `stale_data`. */
|
|
398
|
+
errorCodeStaleData: string;
|
|
306
399
|
}
|
|
307
400
|
|
|
308
401
|
export const DEFAULT_STRINGS: TerpStrings = {
|
|
@@ -439,8 +532,48 @@ export const DEFAULT_STRINGS: TerpStrings = {
|
|
|
439
532
|
targetColumn: "Target",
|
|
440
533
|
whenColumn: "When",
|
|
441
534
|
details: "Details",
|
|
535
|
+
requestLabel: "Request",
|
|
442
536
|
saved: "Saved",
|
|
443
537
|
requestFailed: "The request failed. Try again.",
|
|
538
|
+
dataViewSearchPlaceholder: "Search…",
|
|
539
|
+
dataViewClearSearch: "Clear search",
|
|
540
|
+
dataViewClearFilters: "Clear filters",
|
|
541
|
+
dataViewViewOptions: "View options",
|
|
542
|
+
dataViewColumns: "Columns",
|
|
543
|
+
dataViewMoveUp: "Move up",
|
|
544
|
+
dataViewMoveDown: "Move down",
|
|
545
|
+
dataViewTableView: "Table view",
|
|
546
|
+
dataViewCardView: "Card view",
|
|
547
|
+
dataViewPageSize: "Rows per page",
|
|
548
|
+
dataViewResultsRange: "{from}–{to} of {total} results",
|
|
549
|
+
dataViewPageOf: "Page {page} of {pages}",
|
|
550
|
+
dataViewFirstPage: "First page",
|
|
551
|
+
dataViewPreviousPage: "Previous page",
|
|
552
|
+
dataViewNextPage: "Next page",
|
|
553
|
+
dataViewLastPage: "Last page",
|
|
554
|
+
dataViewSelectAllPage: "Select all rows on this page",
|
|
555
|
+
dataViewSelectRow: "Select row",
|
|
556
|
+
dataViewSelected: "{count} selected",
|
|
557
|
+
dataViewSelectAllResults: "Select all {total} results",
|
|
558
|
+
dataViewClearSelection: "Clear selection",
|
|
559
|
+
dataViewMoreActions: "More actions",
|
|
560
|
+
dataViewActions: "Actions",
|
|
561
|
+
dataViewOpenRow: "Open details: {label}",
|
|
562
|
+
dataViewExpandRow: "Expand row",
|
|
563
|
+
dataViewCollapseRow: "Collapse row",
|
|
564
|
+
dataViewEmpty: "Nothing to show.",
|
|
565
|
+
dataViewLoading: "Loading…",
|
|
566
|
+
dataViewRefreshing: "Refreshing…",
|
|
567
|
+
dataViewErrorTitle: "Could not load data.",
|
|
568
|
+
dataViewResizeColumn: "Resize column",
|
|
569
|
+
errorCodeBadRequest: "The request could not be processed.",
|
|
570
|
+
errorCodeValidationFailed: "Some fields are invalid. Check the form and try again.",
|
|
571
|
+
errorCodeInvalidToken: "Your session is invalid. Sign in again.",
|
|
572
|
+
errorCodeAuthenticationRequired: "Sign in to continue.",
|
|
573
|
+
errorCodePermissionDenied: "You do not have permission to do this.",
|
|
574
|
+
errorCodeNotFound: "This item could not be found.",
|
|
575
|
+
errorCodeConflict: "This conflicts with the current state. Refresh and try again.",
|
|
576
|
+
errorCodeStaleData: "This item was changed by someone else. Refresh and try again.",
|
|
444
577
|
};
|
|
445
578
|
|
|
446
579
|
interface UiTextContextValue {
|
|
@@ -459,7 +592,9 @@ export interface UiTextProviderProps {
|
|
|
459
592
|
/**
|
|
460
593
|
* Custom {@link UiText} resolver — the hook for a real i18n runtime: pass a
|
|
461
594
|
* function that looks descriptors up in the active locale's catalog
|
|
462
|
-
* (falling back to `message`). Defaults to {@link resolveUiText}.
|
|
595
|
+
* (falling back to `message`). Defaults to {@link resolveUiText}. It is handed the app's
|
|
596
|
+
* strings and descriptors only: a manifest's `FrameworkText` is answered from `strings`
|
|
597
|
+
* before it is reached (see {@link useUiText}).
|
|
463
598
|
*/
|
|
464
599
|
resolveText?: ResolveUiText;
|
|
465
600
|
children: ReactNode;
|
|
@@ -488,10 +623,35 @@ export function useStrings(): TerpStrings {
|
|
|
488
623
|
return useContext(UiTextContext).strings;
|
|
489
624
|
}
|
|
490
625
|
|
|
491
|
-
/**
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
626
|
+
/**
|
|
627
|
+
* The active {@link UiText} resolver — call it on any `UiText` prop before rendering, and on a
|
|
628
|
+
* manifest's navigation label, which may also be a {@link FrameworkText}.
|
|
629
|
+
*
|
|
630
|
+
* A `FrameworkText` is answered here, from the same table {@link useStrings} returns, and never
|
|
631
|
+
* reaches the resolver a provider was given. That resolver is the app's: `LocaleProvider`'s
|
|
632
|
+
* treats a descriptor's `message` as the app's source-locale text and looks every other locale
|
|
633
|
+
* up in the app's messages, and framework copy is neither. A key the table does not have
|
|
634
|
+
* throws rather than rendering an empty label; the type already refuses one, so this is what
|
|
635
|
+
* holds a manifest the typecheck never saw.
|
|
636
|
+
*/
|
|
637
|
+
export function useUiText(): (text: UiText | FrameworkText) => string {
|
|
638
|
+
const { strings, resolveText } = useContext(UiTextContext);
|
|
639
|
+
return useCallback(
|
|
640
|
+
(text: UiText | FrameworkText) => {
|
|
641
|
+
if (typeof text === "string" || !("framework" in text)) {
|
|
642
|
+
return resolveText(text);
|
|
643
|
+
}
|
|
644
|
+
if (!Object.hasOwn(strings, text.framework)) {
|
|
645
|
+
throw new Error(
|
|
646
|
+
`FrameworkText names "${text.framework}", which is not a framework string. ` +
|
|
647
|
+
"Name a TerpStrings key (for example \"admin\"); an app's own copy is a " +
|
|
648
|
+
"{ id, message } descriptor in frontend/i18n.json.",
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
return strings[text.framework];
|
|
652
|
+
},
|
|
653
|
+
[strings, resolveText],
|
|
654
|
+
);
|
|
495
655
|
}
|
|
496
656
|
|
|
497
657
|
/** Props for {@link Trans}: one stable catalog id and its source-language fallback. */
|