@terpjs/react-core 0.16.0 → 0.17.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 +4 -3
- package/package.json +2 -2
- package/src/Disclosure.test.tsx +106 -0
- package/src/Disclosure.tsx +104 -0
- package/src/bootstrap.test.tsx +49 -0
- package/src/bootstrap.tsx +23 -0
- package/src/clipboard.test.ts +158 -0
- package/src/clipboard.ts +165 -0
- package/src/dataview/DataView.test.tsx +49 -0
- package/src/dataview/DataView.tsx +16 -0
- package/src/dataview/DataViewCardList.tsx +4 -2
- package/src/dataview/DataViewTable.tsx +19 -6
- package/src/index.ts +7 -2
- package/src/layout.test.tsx +80 -1
- package/src/layout.tsx +143 -6
- package/src/layoutContract.test.tsx +1 -0
- package/src/layoutContract.ts +1 -0
- package/src/markers.test.ts +4 -0
- package/src/styles.test.ts +193 -1
- package/src/styles.ts +254 -11
- package/src/theme.test.tsx +30 -0
- package/src/theme.tsx +17 -0
- package/src/tokens.guard.test.ts +1 -1
- package/src/useResource.test.tsx +56 -0
- package/src/useResource.ts +49 -4
package/README.md
CHANGED
|
@@ -157,8 +157,8 @@ rather write code than check in a file. Each governed archetype's body slot then
|
|
|
157
157
|
components — `standard`: hub bodies hold `HubCard` only; overview bodies hold
|
|
158
158
|
`DataView` / `ResourceList` / `ModuleNav` / `Stack` / `Card` / `Divider` / `Text` plus
|
|
159
159
|
the framework states (`EmptyState` / `ErrorState` / `LoadingState` / `Alert`) and
|
|
160
|
-
`ConfirmDialog`; detail bodies hold `DetailList` / `
|
|
161
|
-
`DataView` / `Card` / `Grid` / `Divider` / `Text` plus the same states. The asymmetry is
|
|
160
|
+
`ConfirmDialog`; detail bodies hold `DetailList` / `DetailListGroup` / `Stack` / `Tabs` /
|
|
161
|
+
`ModuleNav` / `DataView` / `Card` / `Grid` / `Divider` / `Text` plus the same states. The asymmetry is
|
|
162
162
|
deliberate and pinned by tests rather than left to the table: `Grid` joins **detail**
|
|
163
163
|
bodies only (an overview body is a collection, and a grid of summary cards is a hub,
|
|
164
164
|
which has its own archetype), while `Heading` joins **neither** — a heading in a governed
|
|
@@ -236,7 +236,8 @@ token spacing scale, so spacing is themed centrally):
|
|
|
236
236
|
| `Grid` | The two-dimensional primitive, and the one that lifts a real ceiling — a two-column form could not be expressed at all before it. `columns` takes a fixed 1–4 or `"auto"` (the default), which reflows to whatever the **container** can hold with no breakpoint anywhere; `minColumn` is the track floor for `auto`; `gap` indexes the spacing scale; `align` is a closed four. Renders no inline style. No `span`, and therefore no twelve-column option — a span system needs a child component to carry it. |
|
|
237
237
|
| `Card` | A token-styled frame (a border, a radius and padding — no fill, so the page's canvas shows through) grouping one block of a page — the sanctioned visual separation between sections. Optional header row: `title` (semantic `<h3>`), muted `description`, `actions` slot — and the slot stays on the title's line whether or not there is a description, which took a rule: a content-sized heading is as wide as its longest line, and flex breaks lines on that width before it shrinks anything. `variant="plain"` keeps the heading and drops the box, for a titled region inside something that is already a surface — a section whose body is a `DataView` gets a border inside a border otherwise. There is no separate `Section` or `Surface`: both are this element with declarations removed. |
|
|
238
238
|
| `Divider` | A rule between groups, as a semantic `<hr>` so the separation reaches the accessibility tree — `Separator` under its other name, shipped once. `orientation="vertical"` takes its height from its flex or grid line rather than inventing one, so it works between the items of a row `Stack` and is zero-height in a block parent. |
|
|
239
|
-
| `DetailList` | Token-styled label/value pairs as a semantic `<dl>` (record metadata, expanded-row summaries). A real grid: `layout="aligned"` puts every label in a shared column so the values line up, `"stacked"` puts the label above its value, and `columns` takes two pairs per row. Tracks are floored at zero and long values wrap, so a 64-character digest no longer pushes the list past its container. Both non-inline layouts mute their label to the small, regular step — at the value's own size and weight a card of labelled values is a wall of bold text — and space their rows so a pair groups; `gap` moves that distance on the spacing scale, and it is the **row** gap, since the column gap is the label-to-value distance.
|
|
239
|
+
| `DetailList` | Token-styled label/value pairs as a semantic `<dl>` (record metadata, expanded-row summaries). A real grid: `layout="aligned"` puts every label in a shared column so the values line up, `"stacked"` puts the label above its value, and `columns` takes two pairs per row. Tracks are floored at zero and long values wrap, so a 64-character digest no longer pushes the list past its container. Both non-inline layouts mute their label to the small, regular step — at the value's own size and weight a card of labelled values is a wall of bold text — and space their rows so a pair groups; `gap` moves that distance on the spacing scale, and it is the **row** gap, since the column gap is the label-to-value distance. One pair can leave the shared column with `full`, which spans it across every track with its label above its value — the escape that stops a single wide value (a paragraph, a payload) from forcing the list to split in two, since two lists measure two label columns. `columns` also takes `"auto"`, which follows the **container** rather than the viewport: a pair is at least 9rem of label and 13rem of value, each floor capped at a share of the track so one pair always fits a narrow panel instead of overflowing it. The closed one-or-two keep the reflow at the framework's viewport cutover, where `Grid` deliberately does not for a fixed count. |
|
|
240
|
+
| `DetailListGroup` | Several `DetailList`s that share **one** measured label column. A card that shows a record in sections renders a list per section — the sections have their own headings and their own order, and one `<dl>` cannot carry that — and each list then measures its own label column, so the values in each land on a different vertical line: four lists, four gutters, on one card. The group owns the track list and each aligned list inside becomes a `subgrid` of it, so every label in every list is measured against the same track. Explicit rather than something `Card` infers from its children: a card that wants two different label widths has to be able to say so, and a card has no business knowing about `<dl>` tracks. Children other than lists span the whole group (a `Heading` between two sections, a `Divider`), which is the other half of why it is a wrapper. It shares the measure for `layout="aligned"` at the default single column — a `columns={2}` list keeps its own four tracks rather than being quietly folded into two — above the viewport cutover, and it degrades to exactly today's output where `subgrid` is unsupported. |
|
|
240
241
|
| `Heading` | A section heading inside a page body — `h2`–`h4`, with `size` a **separate** choice from `level` so a visually small `h2` is expressible without picking the wrong element. No level 1: `Page` renders the single `h1` of every routed view. |
|
|
241
242
|
| `Text` | Body copy with themeable ink — `tone` (default / muted / subtle), `size`, and an enumerable `measure` that caps the line length in `ch`. What a bare `<p>` in a module cannot be, since a bare element carries no marker for a rule to reach. |
|
|
242
243
|
| `Code` | An identifier or a snippet in the mono family. `block` wraps it in a focusable `<pre>`, which is what preserves the whitespace and what makes a long line scrollable by keyboard. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@terpjs/react-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.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.16",
|
|
17
|
-
"@terpjs/contract": "^0.
|
|
17
|
+
"@terpjs/contract": "^0.17.0"
|
|
18
18
|
},
|
|
19
19
|
"peerDependencies": {
|
|
20
20
|
"react": "^19.0.0",
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
//
|
|
3
|
+
// What each hand-roll of this control had to get right on its own: the button says whether
|
|
4
|
+
// it is open, names the region it controls, and that region exists to be named. Those three
|
|
5
|
+
// are the whole reason a component is worth more here than a `<details>` recipe, so they are
|
|
6
|
+
// what these tests hold.
|
|
7
|
+
|
|
8
|
+
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
|
9
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
10
|
+
|
|
11
|
+
import { Disclosure } from "./Disclosure";
|
|
12
|
+
|
|
13
|
+
afterEach(cleanup);
|
|
14
|
+
|
|
15
|
+
describe("Disclosure", () => {
|
|
16
|
+
it("wires the toggle to the region it reveals", () => {
|
|
17
|
+
render(
|
|
18
|
+
<Disclosure label="Technical details">
|
|
19
|
+
<p>the payload</p>
|
|
20
|
+
</Disclosure>,
|
|
21
|
+
);
|
|
22
|
+
const toggle = screen.getByRole("button", { name: "Technical details" });
|
|
23
|
+
expect(toggle.getAttribute("aria-expanded")).toBe("false");
|
|
24
|
+
|
|
25
|
+
fireEvent.click(toggle);
|
|
26
|
+
|
|
27
|
+
expect(toggle.getAttribute("aria-expanded")).toBe("true");
|
|
28
|
+
const panel = screen.getByText("the payload").closest("[data-terp='disclosure-panel']");
|
|
29
|
+
// The join a hand-roll forgets: without it a screen reader reaches the button and has
|
|
30
|
+
// no way to find what it opened.
|
|
31
|
+
expect(toggle.getAttribute("aria-controls")).toBe(panel?.getAttribute("id"));
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("does not render the panel while closed", () => {
|
|
35
|
+
// Unmounted, not hidden. Hidden content stays in the accessibility tree unless every
|
|
36
|
+
// branch remembers `hidden`, and it keeps doing whatever it renders — a disclosure over
|
|
37
|
+
// a live log then costs its work on every screen that has one, for a region nobody
|
|
38
|
+
// opened.
|
|
39
|
+
render(
|
|
40
|
+
<Disclosure label="Technical details">
|
|
41
|
+
<p>the payload</p>
|
|
42
|
+
</Disclosure>,
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
expect(screen.queryByText("the payload")).toBeNull();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("opens on first render when asked", () => {
|
|
49
|
+
render(
|
|
50
|
+
<Disclosure label="Technical details" defaultOpen>
|
|
51
|
+
<p>the payload</p>
|
|
52
|
+
</Disclosure>,
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
expect(screen.getByText("the payload")).toBeTruthy();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("lets the caller own the state", () => {
|
|
59
|
+
const onOpenChange = vi.fn();
|
|
60
|
+
render(
|
|
61
|
+
<Disclosure label="Technical details" open={false} onOpenChange={onOpenChange}>
|
|
62
|
+
<p>the payload</p>
|
|
63
|
+
</Disclosure>,
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
fireEvent.click(screen.getByRole("button", { name: "Technical details" }));
|
|
67
|
+
|
|
68
|
+
// Reported, not applied: a controlled disclosure shows what the prop says, which is the
|
|
69
|
+
// same invariant the controlled Combobox keeps.
|
|
70
|
+
expect(onOpenChange).toHaveBeenCalledWith(true);
|
|
71
|
+
expect(screen.queryByText("the payload")).toBeNull();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("gives two disclosures on one screen different region ids", () => {
|
|
75
|
+
// `useId` rather than a module counter: two instances sharing an id would point every
|
|
76
|
+
// `aria-controls` at the first panel, and the second control would silently describe
|
|
77
|
+
// somebody else's content.
|
|
78
|
+
render(
|
|
79
|
+
<>
|
|
80
|
+
<Disclosure label="First" defaultOpen>
|
|
81
|
+
<p>one</p>
|
|
82
|
+
</Disclosure>
|
|
83
|
+
<Disclosure label="Second" defaultOpen>
|
|
84
|
+
<p>two</p>
|
|
85
|
+
</Disclosure>
|
|
86
|
+
</>,
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
const [first, second] = screen.getAllByRole("button");
|
|
90
|
+
expect(first.getAttribute("aria-controls")).not.toBe(second.getAttribute("aria-controls"));
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("marks itself open so the stylesheet can reach the state", () => {
|
|
94
|
+
const { container } = render(
|
|
95
|
+
<Disclosure label="Technical details">
|
|
96
|
+
<p>the payload</p>
|
|
97
|
+
</Disclosure>,
|
|
98
|
+
);
|
|
99
|
+
const root = container.querySelector("[data-terp='disclosure']");
|
|
100
|
+
expect(root?.hasAttribute("data-open")).toBe(false);
|
|
101
|
+
|
|
102
|
+
fireEvent.click(screen.getByRole("button", { name: "Technical details" }));
|
|
103
|
+
|
|
104
|
+
expect(root?.hasAttribute("data-open")).toBe(true);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One labelled toggle over one region — progressive disclosure for a single value.
|
|
3
|
+
*
|
|
4
|
+
* ADR 0099 refused an `Accordion` ("a policy over a disclosure set, and there is no
|
|
5
|
+
* disclosure set to apply it to") and a `Collapsible` ("nothing in the framework has
|
|
6
|
+
* anything to collapse"), and both readings still hold: `<details>`/`<summary>` are not
|
|
7
|
+
* restricted elements, so an app was never blocked — only unstyled and unwired.
|
|
8
|
+
*
|
|
9
|
+
* What changed is that the framework turned out to own **half** of this pattern. Row
|
|
10
|
+
* disclosure has a home (`DataView`'s `renderExpanded`); the single value next to it had
|
|
11
|
+
* none, so "Technical details" was hand-built out of a `Button` carrying `aria-expanded`
|
|
12
|
+
* and a body toggled beside it — twice, independently, in two codebases, each rewiring
|
|
13
|
+
* the same three attributes. That is the "written twice" evidence ADR 0099's own
|
|
14
|
+
* amendment accepted for `Combobox multiple`, and this is the narrow thing it justifies:
|
|
15
|
+
* not a set, not a policy over one, just the control both hand-rolls actually were.
|
|
16
|
+
*
|
|
17
|
+
* **Not `<details>`.** Its open/close is the browser's, not React's, so a controlled
|
|
18
|
+
* `open` fights the element; its `::marker` styling is still uneven across engines; and
|
|
19
|
+
* `<summary>` is a focusable non-button whose keyboard contract differs per platform. A
|
|
20
|
+
* button and a region cost three attributes and behave the same everywhere — and the
|
|
21
|
+
* three attributes are precisely what each hand-roll had to get right on its own.
|
|
22
|
+
*
|
|
23
|
+
* **Controlled or not, but not both.** With `open` supplied the caller owns the state and
|
|
24
|
+
* `onOpenChange` reports intent; with neither, the component keeps its own. Passing
|
|
25
|
+
* `open` without `onOpenChange` yields a panel that cannot be closed, so that combination
|
|
26
|
+
* is refused by the type rather than discovered in a browser — the same discriminated
|
|
27
|
+
* union `Combobox multiple` uses for the same reason.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { useCallback, useId, useState } from "react";
|
|
31
|
+
import type { ReactNode } from "react";
|
|
32
|
+
|
|
33
|
+
import { ChevronDownGlyph, ChevronRightGlyph } from "./dataview/glyphs";
|
|
34
|
+
import { injectTerpStyles } from "./styles";
|
|
35
|
+
import { useUiText } from "./uiText";
|
|
36
|
+
import type { UiText } from "./uiText";
|
|
37
|
+
|
|
38
|
+
injectTerpStyles();
|
|
39
|
+
|
|
40
|
+
interface DisclosureBase {
|
|
41
|
+
/** The toggle's own copy — always the app's, so this component ships no strings. */
|
|
42
|
+
label: UiText;
|
|
43
|
+
/** What the toggle reveals. Rendered only while open. */
|
|
44
|
+
children: ReactNode;
|
|
45
|
+
/** Open on first render, for the uncontrolled case. Ignored when `open` is supplied. */
|
|
46
|
+
defaultOpen?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type DisclosureProps = DisclosureBase &
|
|
50
|
+
(
|
|
51
|
+
| { open: boolean; onOpenChange: (open: boolean) => void }
|
|
52
|
+
| { open?: undefined; onOpenChange?: (open: boolean) => void }
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The panel is unmounted while closed rather than hidden.
|
|
57
|
+
*
|
|
58
|
+
* Hidden content stays in the accessibility tree unless every branch remembers
|
|
59
|
+
* `hidden`, and it keeps running whatever it renders — a disclosure over a live log or a
|
|
60
|
+
* heavy diff then costs its work on every screen that has one, permanently, for a region
|
|
61
|
+
* nobody has opened. Unmounting is also what the row-disclosure half already does.
|
|
62
|
+
*/
|
|
63
|
+
export function Disclosure({
|
|
64
|
+
label,
|
|
65
|
+
children,
|
|
66
|
+
defaultOpen = false,
|
|
67
|
+
open,
|
|
68
|
+
onOpenChange,
|
|
69
|
+
}: DisclosureProps) {
|
|
70
|
+
const resolve = useUiText();
|
|
71
|
+
const panelId = useId();
|
|
72
|
+
const [uncontrolled, setUncontrolled] = useState(defaultOpen);
|
|
73
|
+
const controlled = open !== undefined;
|
|
74
|
+
const isOpen = controlled ? open : uncontrolled;
|
|
75
|
+
|
|
76
|
+
const toggle = useCallback(() => {
|
|
77
|
+
const next = !isOpen;
|
|
78
|
+
if (!controlled) setUncontrolled(next);
|
|
79
|
+
onOpenChange?.(next);
|
|
80
|
+
}, [controlled, isOpen, onOpenChange]);
|
|
81
|
+
|
|
82
|
+
return (
|
|
83
|
+
<div data-terp="disclosure" data-open={isOpen || undefined}>
|
|
84
|
+
<button
|
|
85
|
+
type="button"
|
|
86
|
+
data-terp="disclosure-toggle"
|
|
87
|
+
aria-expanded={isOpen}
|
|
88
|
+
aria-controls={panelId}
|
|
89
|
+
onClick={toggle}
|
|
90
|
+
>
|
|
91
|
+
{isOpen ? <ChevronDownGlyph /> : <ChevronRightGlyph />}
|
|
92
|
+
<span>{resolve(label)}</span>
|
|
93
|
+
</button>
|
|
94
|
+
{/* `role="group"` rather than `region`: a region is a landmark, and a screen with
|
|
95
|
+
four "Technical details" disclosures would put four unnamed landmarks in the
|
|
96
|
+
rotor. The button's `aria-controls` is what ties the two together. */}
|
|
97
|
+
{isOpen && (
|
|
98
|
+
<div id={panelId} data-terp="disclosure-panel" role="group">
|
|
99
|
+
{children}
|
|
100
|
+
</div>
|
|
101
|
+
)}
|
|
102
|
+
</div>
|
|
103
|
+
);
|
|
104
|
+
}
|
package/src/bootstrap.test.tsx
CHANGED
|
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
|
|
4
4
|
import { defineModuleManifest } from "@terpjs/contract";
|
|
5
5
|
|
|
6
6
|
import { collectModules, renderTerpApp } from "./bootstrap";
|
|
7
|
+
import { useErrorMessage } from "./errorMessages";
|
|
7
8
|
|
|
8
9
|
afterEach(() => {
|
|
9
10
|
cleanup();
|
|
@@ -65,6 +66,54 @@ describe("renderTerpApp", () => {
|
|
|
65
66
|
root.remove();
|
|
66
67
|
});
|
|
67
68
|
|
|
69
|
+
it("registers the app's error copy, including codes it invented", async () => {
|
|
70
|
+
// Fourth instance of one shape: a seam that is exported, documented and unreachable
|
|
71
|
+
// from the one call that owns everything between the root and the router. An app that
|
|
72
|
+
// wanted its own wording -- or any wording for a code its own backend defines -- had to
|
|
73
|
+
// abandon renderTerpApp for TerpProvider + buildAppRouter.
|
|
74
|
+
//
|
|
75
|
+
// Asserted through the login fallback rather than a route, because the provider has to
|
|
76
|
+
// sit above RequireAuth to be worth anything: a signed-out screen shows errors too.
|
|
77
|
+
//
|
|
78
|
+
// Mutation: delete the ErrorMessagesProvider from bootstrap.tsx and both assertions
|
|
79
|
+
// below go red -- the first because the app code is gone, the second because the
|
|
80
|
+
// built-in default comes back.
|
|
81
|
+
const root = document.createElement("div");
|
|
82
|
+
document.body.appendChild(root);
|
|
83
|
+
|
|
84
|
+
function ShowsAnError() {
|
|
85
|
+
const describe = useErrorMessage();
|
|
86
|
+
return (
|
|
87
|
+
<>
|
|
88
|
+
<p>{describe({ code: "crosswalk_locked" })}</p>
|
|
89
|
+
<p>{describe({ code: "not_found" })}</p>
|
|
90
|
+
</>
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
renderTerpApp({
|
|
95
|
+
title: "Test",
|
|
96
|
+
modules: { "./modules/notes/module.tsx": notesModule },
|
|
97
|
+
rootElement: root,
|
|
98
|
+
login: <ShowsAnError />,
|
|
99
|
+
errorMessages: {
|
|
100
|
+
crosswalk_locked: "That value table is published and cannot be edited.",
|
|
101
|
+
not_found: "Niets gevonden.",
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
await waitFor(() =>
|
|
106
|
+
expect(
|
|
107
|
+
screen.getByText("That value table is published and cannot be edited."),
|
|
108
|
+
).toBeInTheDocument(),
|
|
109
|
+
);
|
|
110
|
+
// And an override of a built-in code wins over DEFAULT_ERROR_MESSAGES, which is the
|
|
111
|
+
// half that would still look fine if the map were merged the wrong way round.
|
|
112
|
+
expect(screen.getByText("Niets gevonden.")).toBeInTheDocument();
|
|
113
|
+
expect(screen.queryByText("This item could not be found.")).not.toBeInTheDocument();
|
|
114
|
+
root.remove();
|
|
115
|
+
});
|
|
116
|
+
|
|
68
117
|
it("forwards the layout declaration to buildAppRouter", () => {
|
|
69
118
|
// Same shape as the navGroups test below, for the same reason: the forwarding is one line in
|
|
70
119
|
// a hand-written enumeration, and a missing line leaves every gate on the declaration green
|
package/src/bootstrap.tsx
CHANGED
|
@@ -12,6 +12,8 @@ import { AdminHub } from "./admin/AdminHub";
|
|
|
12
12
|
import { adminModule } from "./admin/module";
|
|
13
13
|
import { resolveLayoutDeclaration } from "./layoutDeclaration";
|
|
14
14
|
import type { LayoutDeclaration } from "./layoutDeclaration";
|
|
15
|
+
import { ErrorMessagesProvider } from "./errorMessages";
|
|
16
|
+
import type { ErrorMessages } from "./errorMessages";
|
|
15
17
|
import { LocaleProvider } from "./locale";
|
|
16
18
|
import { installPreviewBridge } from "./previewBridge";
|
|
17
19
|
import type { LocaleCatalog } from "./locale";
|
|
@@ -118,6 +120,22 @@ export interface RenderTerpAppOptions {
|
|
|
118
120
|
* a slot that existed and was unreachable from the entry point every app uses.
|
|
119
121
|
*/
|
|
120
122
|
headerActions?: ReactNode;
|
|
123
|
+
/**
|
|
124
|
+
* Per-code overrides and additions for the error copy an app shows
|
|
125
|
+
* ({@link ErrorMessagesProvider}), merged over {@link DEFAULT_ERROR_MESSAGES}.
|
|
126
|
+
*
|
|
127
|
+
* The provider, the hook and the default map were all exported and there was no way to
|
|
128
|
+
* register a map from the one-call bootstrap, which owns everything between the root and
|
|
129
|
+
* the router. So an app that wanted its own wording for a code -- or any wording at all
|
|
130
|
+
* for a code its own backend modules define -- had to abandon `renderTerpApp` for
|
|
131
|
+
* `TerpProvider` + `buildAppRouter`.
|
|
132
|
+
*
|
|
133
|
+
* Fourth instance of the shape `headerActions` names above, and the one that decided this
|
|
134
|
+
* is a class of defect rather than three oversights: a seam that exists, is documented,
|
|
135
|
+
* and cannot be reached from the entry point every app uses. Reaching it is not a
|
|
136
|
+
* capability an app should have to leave the front door to get.
|
|
137
|
+
*/
|
|
138
|
+
errorMessages?: ErrorMessages;
|
|
121
139
|
/** Footer line under the content; default: a muted line with the app title. */
|
|
122
140
|
footer?: ReactNode;
|
|
123
141
|
/**
|
|
@@ -367,6 +385,10 @@ export function renderTerpApp(options: RenderTerpAppOptions): void {
|
|
|
367
385
|
sourceLocale={options.sourceLocale}
|
|
368
386
|
>
|
|
369
387
|
<TerpProvider baseUrl={options.baseUrl ?? ""} ssoCallbackPath={options.ssoCallbackPath}>
|
|
388
|
+
{/* Inside the locale provider, because the copy it carries is app copy and an
|
|
389
|
+
app that localises its own messages resolves them from the active locale.
|
|
390
|
+
Outside the router, because a route component is exactly what reads it. */}
|
|
391
|
+
<ErrorMessagesProvider messages={options.errorMessages ?? {}}>
|
|
370
392
|
<ToastProvider>
|
|
371
393
|
<RequireAuth
|
|
372
394
|
fallback={
|
|
@@ -381,6 +403,7 @@ export function renderTerpApp(options: RenderTerpAppOptions): void {
|
|
|
381
403
|
<RouterProvider router={router} />
|
|
382
404
|
</RequireAuth>
|
|
383
405
|
</ToastProvider>
|
|
406
|
+
</ErrorMessagesProvider>
|
|
384
407
|
</TerpProvider>
|
|
385
408
|
</LocaleProvider>
|
|
386
409
|
</ThemeProvider>
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
//
|
|
3
|
+
// The defect this module exists for is not "copying is hard" — it is that the failure was
|
|
4
|
+
// SILENT and unreachable by any check. `navigator.clipboard` is typed as always present and
|
|
5
|
+
// is absent outside a secure context, so the call throws synchronously, before a promise
|
|
6
|
+
// exists, and neither a `.catch` nor a `try` around an `await` sees it.
|
|
7
|
+
//
|
|
8
|
+
// So the tests that matter are the negative ones: the insecure context must not throw, must
|
|
9
|
+
// not resolve as success, and must reach the fallback that still works there.
|
|
10
|
+
|
|
11
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
12
|
+
|
|
13
|
+
import { COPIED_FEEDBACK_MS, copyText, useCopyToClipboard } from "./clipboard";
|
|
14
|
+
|
|
15
|
+
const original = Object.getOwnPropertyDescriptor(globalThis.navigator, "clipboard");
|
|
16
|
+
|
|
17
|
+
function setClipboard(value: unknown): void {
|
|
18
|
+
Object.defineProperty(globalThis.navigator, "clipboard", {
|
|
19
|
+
value,
|
|
20
|
+
configurable: true,
|
|
21
|
+
writable: true,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
afterEach(() => {
|
|
26
|
+
if (original) Object.defineProperty(globalThis.navigator, "clipboard", original);
|
|
27
|
+
else setClipboard(undefined);
|
|
28
|
+
vi.restoreAllMocks();
|
|
29
|
+
vi.useRealTimers();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe("copyText", () => {
|
|
33
|
+
it("uses the async API when it is there", async () => {
|
|
34
|
+
const writeText = vi.fn().mockResolvedValue(undefined);
|
|
35
|
+
setClipboard({ writeText });
|
|
36
|
+
|
|
37
|
+
await expect(copyText("hello")).resolves.toBe(true);
|
|
38
|
+
expect(writeText).toHaveBeenCalledWith("hello");
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("does not throw when navigator.clipboard is undefined", async () => {
|
|
42
|
+
// The whole reason for this module. On a plain-http origin the property is absent, so
|
|
43
|
+
// `navigator.clipboard.writeText(...)` is a property read on undefined — a synchronous
|
|
44
|
+
// TypeError that escapes every handler a caller would think to write. lib.dom types the
|
|
45
|
+
// property as present, so nothing warns first.
|
|
46
|
+
setClipboard(undefined);
|
|
47
|
+
const execCommand = vi.fn().mockReturnValue(true);
|
|
48
|
+
Object.defineProperty(document, "execCommand", { value: execCommand, configurable: true });
|
|
49
|
+
|
|
50
|
+
await expect(copyText("hello")).resolves.toBe(true);
|
|
51
|
+
expect(execCommand).toHaveBeenCalledWith("copy");
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("reports a refusal instead of resolving as success", async () => {
|
|
55
|
+
// The other half of "silent": a copy that did not happen must be distinguishable from
|
|
56
|
+
// one that did, or a caller has nothing to react to and the button lies again.
|
|
57
|
+
setClipboard(undefined);
|
|
58
|
+
Object.defineProperty(document, "execCommand", {
|
|
59
|
+
value: vi.fn().mockReturnValue(false),
|
|
60
|
+
configurable: true,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
await expect(copyText("hello")).resolves.toBe(false);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("falls back when the API is present and rejects", async () => {
|
|
67
|
+
// A permissions policy, a document without focus, a declined prompt: the object is
|
|
68
|
+
// there and the write is refused. The fallback sometimes still works, and finding out
|
|
69
|
+
// costs one detached element.
|
|
70
|
+
setClipboard({ writeText: vi.fn().mockRejectedValue(new Error("denied")) });
|
|
71
|
+
const execCommand = vi.fn().mockReturnValue(true);
|
|
72
|
+
Object.defineProperty(document, "execCommand", { value: execCommand, configurable: true });
|
|
73
|
+
|
|
74
|
+
await expect(copyText("hello")).resolves.toBe(true);
|
|
75
|
+
expect(execCommand).toHaveBeenCalled();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("treats a partial clipboard object as absent", async () => {
|
|
79
|
+
// Older WebViews expose `navigator.clipboard` without `writeText`. A `!= null` guard
|
|
80
|
+
// passes that and then throws on the call — which is the original bug wearing a
|
|
81
|
+
// slightly different hat.
|
|
82
|
+
setClipboard({});
|
|
83
|
+
Object.defineProperty(document, "execCommand", {
|
|
84
|
+
value: vi.fn().mockReturnValue(true),
|
|
85
|
+
configurable: true,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
await expect(copyText("hello")).resolves.toBe(true);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("copies nothing successfully", async () => {
|
|
92
|
+
const writeText = vi.fn();
|
|
93
|
+
setClipboard({ writeText });
|
|
94
|
+
|
|
95
|
+
await expect(copyText("")).resolves.toBe(true);
|
|
96
|
+
// Clearing a field and copying it is not an error, and a toast saying otherwise would
|
|
97
|
+
// be shown to somebody who did nothing wrong.
|
|
98
|
+
expect(writeText).not.toHaveBeenCalled();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("leaves no textarea behind when the fallback throws", async () => {
|
|
102
|
+
setClipboard(undefined);
|
|
103
|
+
Object.defineProperty(document, "execCommand", {
|
|
104
|
+
value: vi.fn().mockImplementation(() => {
|
|
105
|
+
throw new Error("not allowed");
|
|
106
|
+
}),
|
|
107
|
+
configurable: true,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
await expect(copyText("hello")).resolves.toBe(false);
|
|
111
|
+
expect(document.querySelectorAll("textarea")).toHaveLength(0);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
describe("useCopyToClipboard", () => {
|
|
116
|
+
it("says it worked, then stops saying so", async () => {
|
|
117
|
+
// A copy has no visible result — the clipboard is somewhere else — so a control that
|
|
118
|
+
// does not acknowledge is indistinguishable from a broken one.
|
|
119
|
+
vi.useFakeTimers();
|
|
120
|
+
setClipboard({ writeText: vi.fn().mockResolvedValue(undefined) });
|
|
121
|
+
const { renderHook, act } = await import("@testing-library/react");
|
|
122
|
+
|
|
123
|
+
const { result } = renderHook(() => useCopyToClipboard());
|
|
124
|
+
expect(result.current.copied).toBe(false);
|
|
125
|
+
|
|
126
|
+
await act(async () => {
|
|
127
|
+
await result.current.copy("hello");
|
|
128
|
+
});
|
|
129
|
+
expect(result.current.copied).toBe(true);
|
|
130
|
+
expect(result.current.failed).toBe(false);
|
|
131
|
+
|
|
132
|
+
act(() => {
|
|
133
|
+
vi.advanceTimersByTime(COPIED_FEEDBACK_MS + 1);
|
|
134
|
+
});
|
|
135
|
+
expect(result.current.copied).toBe(false);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("keeps a refusal separate from the resting state", async () => {
|
|
139
|
+
// `failed` is not `copied === false`: a control that has never been pressed and one
|
|
140
|
+
// that has just been refused would otherwise look identical.
|
|
141
|
+
setClipboard(undefined);
|
|
142
|
+
Object.defineProperty(document, "execCommand", {
|
|
143
|
+
value: vi.fn().mockReturnValue(false),
|
|
144
|
+
configurable: true,
|
|
145
|
+
});
|
|
146
|
+
const { renderHook, act } = await import("@testing-library/react");
|
|
147
|
+
|
|
148
|
+
const { result } = renderHook(() => useCopyToClipboard());
|
|
149
|
+
expect(result.current.failed).toBe(false);
|
|
150
|
+
|
|
151
|
+
await act(async () => {
|
|
152
|
+
await result.current.copy("hello");
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
expect(result.current.failed).toBe(true);
|
|
156
|
+
expect(result.current.copied).toBe(false);
|
|
157
|
+
});
|
|
158
|
+
});
|