@terpjs/react-core 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
3
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
+
5
+ import { TileGroup } from "./TileGroup";
6
+ import type { Tile } from "./TileGroup";
7
+
8
+ const TILES: Tile[] = [
9
+ { value: "none", label: "No access" },
10
+ { value: "viewer", label: "Viewer" },
11
+ { value: "editor", label: "Editor" },
12
+ { value: "admin", label: "Administrator", tone: "danger" },
13
+ ];
14
+
15
+ function setup(overrides: Partial<Parameters<typeof TileGroup>[0]> = {}) {
16
+ const onCommit = vi.fn();
17
+ render(
18
+ <TileGroup
19
+ label="Access in this module"
20
+ tiles={TILES}
21
+ value="viewer"
22
+ onCommit={onCommit}
23
+ {...overrides}
24
+ />,
25
+ );
26
+ return { onCommit };
27
+ }
28
+
29
+ afterEach(cleanup);
30
+
31
+ describe("TileGroup", () => {
32
+ it("is a radiogroup whose whole set of choices is visible at once", () => {
33
+ setup();
34
+ // The reason this is not a Select: every option is present without opening anything, so two
35
+ // of them can be compared. A dropdown hides that the choices exist at all.
36
+ expect(screen.getByRole("radiogroup", { name: "Access in this module" })).toBeInTheDocument();
37
+ expect(screen.getAllByRole("radio").map((tile) => tile.textContent)).toEqual([
38
+ "No access",
39
+ "Viewer",
40
+ "Editor",
41
+ "Administrator",
42
+ ]);
43
+ expect(screen.getByRole("radio", { name: "Viewer" })).toHaveAttribute("aria-checked", "true");
44
+ });
45
+
46
+ it("moves focus on arrow without committing, and commits on Space", () => {
47
+ // The load-bearing accessibility decision. A native radio group activates on arrow, and the
48
+ // most privileged tile here sits behind a confirmation — so automatic activation would fire
49
+ // that confirmation while someone was merely arrowing past it.
50
+ const { onCommit } = setup();
51
+ const viewer = screen.getByRole("radio", { name: "Viewer" });
52
+ viewer.focus();
53
+
54
+ fireEvent.keyDown(viewer, { key: "ArrowRight" });
55
+ expect(screen.getByRole("radio", { name: "Editor" })).toHaveFocus();
56
+ expect(onCommit).not.toHaveBeenCalled();
57
+
58
+ fireEvent.keyDown(screen.getByRole("radio", { name: "Editor" }), { key: "ArrowRight" });
59
+ expect(screen.getByRole("radio", { name: "Administrator" })).toHaveFocus();
60
+ expect(onCommit).not.toHaveBeenCalled();
61
+
62
+ fireEvent.keyDown(screen.getByRole("radio", { name: "Administrator" }), { key: " " });
63
+ expect(onCommit).toHaveBeenCalledExactlyOnceWith("admin");
64
+ });
65
+
66
+ it("commits on Enter as well, because both are confirm keys", () => {
67
+ const { onCommit } = setup();
68
+ const editor = screen.getByRole("radio", { name: "Editor" });
69
+ editor.focus();
70
+ fireEvent.keyDown(editor, { key: "Enter" });
71
+ expect(onCommit).toHaveBeenCalledExactlyOnceWith("editor");
72
+ });
73
+
74
+ it("wraps at the ends and jumps with Home/End", () => {
75
+ // A strip is a closed set: arrowing off the end and stopping dead reads as a broken control
76
+ // rather than as a boundary.
77
+ setup();
78
+ const first = screen.getByRole("radio", { name: "No access" });
79
+ first.focus();
80
+ fireEvent.keyDown(first, { key: "ArrowLeft" });
81
+ expect(screen.getByRole("radio", { name: "Administrator" })).toHaveFocus();
82
+
83
+ fireEvent.keyDown(screen.getByRole("radio", { name: "Administrator" }), { key: "Home" });
84
+ expect(screen.getByRole("radio", { name: "No access" })).toHaveFocus();
85
+
86
+ fireEvent.keyDown(screen.getByRole("radio", { name: "No access" }), { key: "End" });
87
+ expect(screen.getByRole("radio", { name: "Administrator" })).toHaveFocus();
88
+ });
89
+
90
+ it("keeps one tab stop, on the selection", () => {
91
+ // The roving tabindex: Tab reaches the group once and the arrows move within it, which is
92
+ // what a radiogroup is supposed to feel like. Four tab stops would make a strip of tiles
93
+ // slower to pass than a dropdown.
94
+ setup();
95
+ const stops = screen
96
+ .getAllByRole("radio")
97
+ .filter((tile) => tile.getAttribute("tabindex") === "0");
98
+ expect(stops.map((tile) => tile.textContent)).toEqual(["Viewer"]);
99
+ });
100
+
101
+ it("puts the tab stop on the first tile when nothing is selected", () => {
102
+ // A group with no selection still has to be reachable by Tab, and the strip's leftmost
103
+ // tile is where a reader expects to arrive — `No access` here, which is also the tile a
104
+ // reader who wants to take a rung away is looking for.
105
+ setup({ value: null });
106
+ const stops = screen
107
+ .getAllByRole("radio")
108
+ .filter((tile) => tile.getAttribute("tabindex") === "0");
109
+ expect(stops.map((tile) => tile.textContent)).toEqual(["No access"]);
110
+ });
111
+
112
+ it("commits nothing at all while the whole group is disabled", () => {
113
+ const { onCommit } = setup({ disabled: true });
114
+ const editor = screen.getByRole("radio", { name: "Editor" });
115
+ fireEvent.click(editor);
116
+ fireEvent.keyDown(editor, { key: "Enter" });
117
+ expect(onCommit).not.toHaveBeenCalled();
118
+ expect(screen.getByRole("radiogroup")).toHaveAttribute("aria-disabled", "true");
119
+ });
120
+
121
+ it("marks a floor distinctly from a selection", () => {
122
+ // Two different facts: what the caller picked, and what is in force anyway. A single visual
123
+ // state would conflate them, and the reader would think their choice was the whole story.
124
+ setup({ value: "viewer", floor: "editor" });
125
+ const picked = screen.getByRole("radio", { name: "Viewer" });
126
+ const inForce = screen.getByRole("radio", { name: "Editor" });
127
+
128
+ expect(picked).toHaveAttribute("data-selected", "true");
129
+ expect(picked).not.toHaveAttribute("data-floor");
130
+
131
+ expect(inForce).toHaveAttribute("data-floor", "true");
132
+ expect(inForce).toHaveAttribute("aria-checked", "false");
133
+ // The assertion that makes this test about *distinctness* rather than about presence. Added
134
+ // after a mutation that also stamped `data-selected` on the floor tile passed everything
135
+ // above it: marking the floor and marking it differently are two claims, and only the
136
+ // second is what stops a reader thinking the strip shows their own choice as in force.
137
+ expect(inForce).not.toHaveAttribute("data-selected");
138
+ });
139
+
140
+ it("renders what a rung hands over inside its own tile", () => {
141
+ // The delta belongs on the tile, not in a tooltip: choosing between rungs means comparing
142
+ // what each one buys, and a comparison you have to hover to make is not one.
143
+ setup({
144
+ tiles: [
145
+ { value: "viewer", label: "Viewer", body: <span>Bekijken: 12</span> },
146
+ { value: "editor", label: "Editor", body: <span>Wijzigen: 4</span> },
147
+ ],
148
+ });
149
+ expect(screen.getByText("Bekijken: 12")).toBeInTheDocument();
150
+ expect(screen.getByText("Wijzigen: 4")).toBeInTheDocument();
151
+ });
152
+
153
+ it("is a plain labelled group with no selection semantics when read-only", () => {
154
+ // A disabled radiogroup announces a set of radio buttons with none of them checked, which
155
+ // tells a screen-reader user they failed to choose something on a screen where there is
156
+ // nothing to choose. The description mode makes no such claim: the tiles are still there
157
+ // to be compared, and none of them pretends to be a control.
158
+ render(<TileGroup label="What each role may do" tiles={TILES} readOnly />);
159
+ expect(screen.getByRole("group", { name: "What each role may do" })).toBeInTheDocument();
160
+ expect(screen.queryByRole("radiogroup")).not.toBeInTheDocument();
161
+ expect(screen.queryAllByRole("radio")).toEqual([]);
162
+ // Every tile's content still reaches the reader — that is the whole point of the mode.
163
+ expect(screen.getByText("Administrator")).toBeInTheDocument();
164
+ });
165
+
166
+ it("carries no tab stop at all when read-only", () => {
167
+ // The counterpart claim: nothing here is a control, so nothing here is in the tab order.
168
+ // A roving tab stop over five unselectable tiles is five keystrokes that do nothing.
169
+ const { container } = render(
170
+ <TileGroup label="What each role may do" tiles={TILES} readOnly />,
171
+ );
172
+ expect(container.querySelectorAll("[tabindex]")).toHaveLength(0);
173
+ });
174
+
175
+ it("still marks the destructive rung when read-only, because the tone is the warning", () => {
176
+ render(<TileGroup label="What each role may do" tiles={TILES} readOnly />);
177
+ const tiles = [...document.querySelectorAll('[data-terp="tile"]')];
178
+ expect(tiles.map((tile) => tile.getAttribute("data-tone"))).toEqual([
179
+ null,
180
+ null,
181
+ null,
182
+ "danger",
183
+ ]);
184
+ });
185
+ });
@@ -0,0 +1,220 @@
1
+ import { useId, useRef, useState } from "react";
2
+ import type { KeyboardEvent, ReactNode } from "react";
3
+
4
+ import { injectTerpStyles } from "../styles";
5
+ import { useUiText } from "../uiText";
6
+ import type { UiText } from "../uiText";
7
+
8
+ injectTerpStyles();
9
+
10
+ /** One tile: a rung, and what reaching it hands over. */
11
+ export interface Tile {
12
+ value: string;
13
+ label: UiText;
14
+ /** What choosing this hands over. Rendered inside the tile, below the label. */
15
+ body?: ReactNode;
16
+ /**
17
+ * `danger` for a choice whose consequence is destructive. It carries the visual weight a
18
+ * subscription table would give its top plan, deliberately inverted: this control exists to
19
+ * bias *down*, so the most privileged rung is the one that looks like a decision.
20
+ */
21
+ tone?: "neutral" | "danger";
22
+ }
23
+
24
+ interface TileGroupBase {
25
+ /** Names the group for assistive technology. Required — an unlabelled group is unusable. */
26
+ label: UiText;
27
+ tiles: readonly Tile[];
28
+ }
29
+
30
+ /** The strip as a **control**: one tile is the current choice, and committing changes it. */
31
+ export interface TileChoiceProps extends TileGroupBase {
32
+ readOnly?: false;
33
+ /** The selected value, or `null` for none selected. */
34
+ value: string | null;
35
+ /**
36
+ * Called when a tile is *committed* — clicked, or focused and confirmed with Space/Enter.
37
+ * Never called by arrowing alone.
38
+ */
39
+ onCommit: (value: string) => void;
40
+ /**
41
+ * A value already reached some other way, marked as a floor rather than a selection. The
42
+ * caller's own choice may sit below it and the floor still applies, so a strip that showed
43
+ * only the direct selection would imply an authority the reader does not have.
44
+ */
45
+ floor?: string | null;
46
+ disabled?: boolean;
47
+ }
48
+
49
+ /**
50
+ * The strip as a **description**: the tiles explain what each rung hands over, and nothing in
51
+ * it is selectable.
52
+ *
53
+ * A separate mode rather than a disabled control, because the two are different claims. A
54
+ * disabled radiogroup announces a set of radio buttons with none of them checked — which tells
55
+ * a screen-reader user they have failed to choose something, on a screen where there is
56
+ * nothing to choose. This mode carries the same tiles with no selection semantics at all.
57
+ *
58
+ * It deliberately accepts no `value`: a highlighted tile that assistive technology cannot see
59
+ * is a sighted-only fact, and the type is what stops one being passed here. A screen that
60
+ * needs to show what someone *holds* wants the control, gated on whether the reader may
61
+ * change it.
62
+ */
63
+ export interface TileDescriptionProps extends TileGroupBase {
64
+ readOnly: true;
65
+ }
66
+
67
+ export type TileGroupProps = TileChoiceProps | TileDescriptionProps;
68
+
69
+ function TileContent({ tile }: { tile: Tile }) {
70
+ const resolve = useUiText();
71
+ return (
72
+ <>
73
+ <span data-terp="tile-label">{resolve(tile.label)}</span>
74
+ {tile.body !== undefined && <div data-terp="tile-body">{tile.body}</div>}
75
+ </>
76
+ );
77
+ }
78
+
79
+ function TileDescription({ label, tiles }: TileDescriptionProps) {
80
+ const resolve = useUiText();
81
+ return (
82
+ <div data-terp="tile-group" role="group" aria-label={resolve(label)}>
83
+ {tiles.map((tile) => (
84
+ <div
85
+ key={tile.value}
86
+ data-terp="tile"
87
+ data-tone={tile.tone === "danger" ? "danger" : undefined}
88
+ >
89
+ <TileContent tile={tile} />
90
+ </div>
91
+ ))}
92
+ </div>
93
+ );
94
+ }
95
+
96
+ function TileChoice({
97
+ label,
98
+ tiles,
99
+ value,
100
+ onCommit,
101
+ floor = null,
102
+ disabled = false,
103
+ }: TileChoiceProps) {
104
+ const resolve = useUiText();
105
+ const groupId = useId();
106
+ const refs = useRef<(HTMLDivElement | null)[]>([]);
107
+ const selectedIndex = tiles.findIndex((tile) => tile.value === value);
108
+ // Focus starts on the selection, or on the first tile when there is none.
109
+ const [focusIndex, setFocusIndex] = useState(() => (selectedIndex >= 0 ? selectedIndex : 0));
110
+
111
+ function moveTo(index: number) {
112
+ setFocusIndex(index);
113
+ refs.current[index]?.focus();
114
+ }
115
+
116
+ function step(from: number, delta: number) {
117
+ if (tiles.length === 0) return;
118
+ // Wraps, because a strip is a closed set: arrowing past the end of four tiles and stopping
119
+ // dead reads as a broken control rather than as a boundary.
120
+ moveTo((from + delta + tiles.length) % tiles.length);
121
+ }
122
+
123
+ function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
124
+ if (disabled) return;
125
+ // The tile the key actually reached, not the one state believes is focused. A keydown fires
126
+ // on the focused element and bubbles here, so the event target *is* the current tile —
127
+ // whereas `focusIndex` is a render-time value that can lag the DOM by a tick, and acting on
128
+ // it would arrow from the wrong place exactly when focus had just moved.
129
+ const target = refs.current.findIndex((node) => node === event.target);
130
+ const from = target === -1 ? focusIndex : target;
131
+
132
+ if (event.key === "ArrowRight" || event.key === "ArrowDown") {
133
+ event.preventDefault();
134
+ step(from, 1);
135
+ return;
136
+ }
137
+ if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
138
+ event.preventDefault();
139
+ step(from, -1);
140
+ return;
141
+ }
142
+ if (event.key === "Home") {
143
+ event.preventDefault();
144
+ moveTo(0);
145
+ return;
146
+ }
147
+ if (event.key === "End") {
148
+ event.preventDefault();
149
+ moveTo(tiles.length - 1);
150
+ return;
151
+ }
152
+ if (event.key === " " || event.key === "Enter") {
153
+ event.preventDefault();
154
+ const tile = tiles[from];
155
+ if (tile !== undefined) onCommit(tile.value);
156
+ }
157
+ }
158
+
159
+ return (
160
+ <div
161
+ data-terp="tile-group"
162
+ role="radiogroup"
163
+ aria-label={resolve(label)}
164
+ aria-disabled={disabled || undefined}
165
+ onKeyDown={onKeyDown}
166
+ >
167
+ {tiles.map((tile, index) => {
168
+ const selected = tile.value === value;
169
+ const isFloor = floor !== null && tile.value === floor;
170
+ return (
171
+ <div
172
+ key={tile.value}
173
+ id={`${groupId}-${tile.value}`}
174
+ ref={(node) => {
175
+ refs.current[index] = node;
176
+ }}
177
+ data-terp="tile"
178
+ data-selected={selected || undefined}
179
+ data-floor={isFloor || undefined}
180
+ data-tone={tile.tone === "danger" ? "danger" : undefined}
181
+ role="radio"
182
+ aria-checked={selected}
183
+ aria-disabled={disabled || undefined}
184
+ // The roving tab stop: one tile is reachable by Tab and the arrows move within the
185
+ // group, which is what a radiogroup is supposed to feel like.
186
+ tabIndex={index === focusIndex && !disabled ? 0 : -1}
187
+ onFocus={() => setFocusIndex(index)}
188
+ onClick={() => {
189
+ if (!disabled) onCommit(tile.value);
190
+ }}
191
+ >
192
+ <TileContent tile={tile} />
193
+ </div>
194
+ );
195
+ })}
196
+ </div>
197
+ );
198
+ }
199
+
200
+ /**
201
+ * The whole set of rungs as tiles — either as a control with **manual activation**, or as a
202
+ * description of what each rung hands over.
203
+ *
204
+ * A dropdown was the obvious control and it is the wrong one here: it hides that the options
205
+ * exist until you open it, and it makes two of them impossible to compare. The tiles borrow the
206
+ * shape of a plan picker, where "everything below, plus…" is the mechanic — and invert its
207
+ * rhetoric, because a plan picker exists to move you up a tier and this exists to help someone
208
+ * choose the smallest tier that works.
209
+ *
210
+ * Manual activation is the load-bearing accessibility decision of the control mode, not a
211
+ * detail. A native radio group activates on arrow: focus moves and the value changes together.
212
+ * Here the most privileged tile is behind a confirmation, so automatic activation would fire
213
+ * that confirmation while someone was merely arrowing past it — the roving-tabindex pattern
214
+ * with Space/Enter to commit is what makes the keyboard path match the pointer path.
215
+ * `Home`/`End` jump to the ends, which is what a strip of five or six tiles needs to be usable
216
+ * at all.
217
+ */
218
+ export function TileGroup(props: TileGroupProps) {
219
+ return props.readOnly === true ? <TileDescription {...props} /> : <TileChoice {...props} />;
220
+ }
@@ -0,0 +1,136 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
3
+ import { afterEach, describe, expect, it } from "vitest";
4
+
5
+ import { UiTextProvider } from "../uiText";
6
+ import { Checkbox } from "./Checkbox";
7
+ import { RadioGroup } from "./Radio";
8
+ import { Switch } from "./Switch";
9
+
10
+ afterEach(cleanup);
11
+
12
+ /**
13
+ * The three controls that label themselves, and therefore cannot use `Field`.
14
+ *
15
+ * Each renders its own `<label>` (or a `<fieldset>`/`<legend>`) around the input, so nesting
16
+ * one inside `Field` produces a `<label>` within a `<label>` — invalid HTML that browsers
17
+ * resolve by associating the control with the outer one, losing the field's label text. The
18
+ * envelope had to be given to them separately; these hold that "separately" did not become
19
+ * "differently".
20
+ */
21
+ describe.each([
22
+ ["Switch", "switch", (props: Record<string, unknown>) => <Switch label="Active" {...props} />],
23
+ [
24
+ "Checkbox",
25
+ "checkbox",
26
+ (props: Record<string, unknown>) => <Checkbox label="Active" {...props} />,
27
+ ],
28
+ ] as const)("%s hint and error", (_name, role, renderControl) => {
29
+ it("points the control at its hint, so a screen reader reaches text beside it", () => {
30
+ render(renderControl({ hint: "only affects new records" }));
31
+
32
+ const control = screen.getByRole(role, { name: "Active" });
33
+ const describedBy = control.getAttribute("aria-describedby");
34
+ expect(describedBy).toBeTruthy();
35
+ // Text beside a control is invisible to assistive technology unless something points at
36
+ // it — the association is the whole feature, not the rendering.
37
+ expect(document.getElementById(describedBy as string)).toHaveTextContent(
38
+ "only affects new records",
39
+ );
40
+ });
41
+
42
+ it("marks the control invalid and announces the error when one arrives", () => {
43
+ render(renderControl({ error: "you must accept this" }));
44
+
45
+ const control = screen.getByRole(role, { name: "Active" });
46
+ expect(control).toHaveAttribute("aria-invalid", "true");
47
+ // `role="alert"` is not redundant with aria-describedby: a description is read when focus
48
+ // reaches the control, which says nothing about an error that appears on submit, once
49
+ // focus has already left.
50
+ expect(screen.getByRole("alert")).toHaveTextContent("you must accept this");
51
+ });
52
+
53
+ it("adds to a caller's own description rather than replacing it", () => {
54
+ render(
55
+ renderControl({ hint: "field hint", "aria-describedby": "callers-own-node" }),
56
+ );
57
+
58
+ const control = screen.getByRole(role, { name: "Active" });
59
+ const ids = (control.getAttribute("aria-describedby") ?? "").split(" ");
60
+ expect(ids).toContain("callers-own-node");
61
+ expect(ids.length).toBe(2);
62
+ });
63
+
64
+ it("keeps its state when an error appears, because the wrapper is not conditional", () => {
65
+ // The regression this guards: rendering the wrapper only when there is a message changes
66
+ // the element type at that position, so React unmounts the label and mounts a fresh
67
+ // input. An uncontrolled control would lose what the user had done to it at exactly the
68
+ // moment the form told them something was wrong.
69
+ const { rerender } = render(renderControl({ defaultChecked: false }));
70
+ const control = screen.getByRole(role, { name: "Active" });
71
+ fireEvent.click(control);
72
+ expect(screen.getByRole(role, { name: "Active" })).toBeChecked();
73
+
74
+ rerender(renderControl({ defaultChecked: false, error: "required" }));
75
+
76
+ expect(screen.getByRole(role, { name: "Active" })).toBeChecked();
77
+ });
78
+ });
79
+
80
+ describe("RadioGroup hint and error", () => {
81
+ const OPTIONS = [
82
+ { value: "daily", label: "Daily" },
83
+ { value: "weekly", label: "Weekly" },
84
+ ];
85
+
86
+ it("describes and invalidates the GROUP, not each option", () => {
87
+ // The unanswered thing is the question, not any one radio. Describing each option would
88
+ // repeat the message on every arrow-key move through the group.
89
+ render(<RadioGroup label="Frequency" options={OPTIONS} error="choose one" />);
90
+
91
+ const group = screen.getByRole("group", { name: "Frequency" });
92
+ expect(group).toHaveAttribute("aria-invalid", "true");
93
+ const describedBy = group.getAttribute("aria-describedby");
94
+ expect(document.getElementById(describedBy as string)).toHaveTextContent("choose one");
95
+
96
+ for (const option of screen.getAllByRole("radio")) {
97
+ expect(option).not.toHaveAttribute("aria-invalid");
98
+ expect(option).not.toHaveAttribute("aria-describedby");
99
+ }
100
+ });
101
+
102
+ it("is the control of the three with a real error need", () => {
103
+ // A boolean cannot hold a value its type refuses, so a switch has little to be wrong
104
+ // about. A required radio group CAN be left unset, and before this prop that rejection
105
+ // had nowhere to go but a form-level summary that never names the question it is about.
106
+ render(<RadioGroup label="Frequency" options={OPTIONS} error="choose one" />);
107
+
108
+ expect(screen.queryByRole("radio", { checked: true })).toBeNull();
109
+ expect(screen.getByRole("alert")).toHaveTextContent("choose one");
110
+ });
111
+
112
+ it("renders no description at all when there is nothing to say", () => {
113
+ render(<RadioGroup label="Frequency" options={OPTIONS} />);
114
+
115
+ const group = screen.getByRole("group", { name: "Frequency" });
116
+ expect(group).not.toHaveAttribute("aria-describedby");
117
+ expect(group).not.toHaveAttribute("aria-invalid");
118
+ expect(screen.queryByRole("alert")).toBeNull();
119
+ });
120
+
121
+ it("resolves a translated hint descriptor", () => {
122
+ render(
123
+ <UiTextProvider
124
+ resolveText={(text) => (typeof text === "string" ? text : `translated:${text.id}`)}
125
+ >
126
+ <RadioGroup
127
+ label="Frequency"
128
+ options={OPTIONS}
129
+ hint={{ id: "billing.frequency.hint", message: "You can change this later" }}
130
+ />
131
+ </UiTextProvider>,
132
+ );
133
+
134
+ expect(screen.getByText("translated:billing.frequency.hint")).toBeInTheDocument();
135
+ });
136
+ });
@@ -0,0 +1,81 @@
1
+ import { useId } from "react";
2
+ import type { ReactNode } from "react";
3
+
4
+ import { useUiText } from "../uiText";
5
+ import type { UiText } from "../uiText";
6
+
7
+ /**
8
+ * The hint + error half of a form field, shared by `Field` and the three self-labelling
9
+ * controls (`Switch`, `Checkbox`, `RadioGroup`).
10
+ *
11
+ * It exists because those three cannot use `Field` at all. Each renders its own `<label>`
12
+ * (or, for the group, a `<fieldset>`/`<legend>`) around the input, and `Field` labels its
13
+ * child by wrapping it in a `<label>` — nesting the two produces a `<label>` inside a
14
+ * `<label>`, which HTML forbids and browsers resolve by associating the control with the
15
+ * outer one. So the envelope had to be given to them separately, and the point of sharing
16
+ * this is that "separately" does not become "differently": the ids, the
17
+ * `aria-describedby` composition, the `aria-invalid`, and the error's `role="alert"` are
18
+ * one implementation, not four that drift.
19
+ *
20
+ * On `role="alert"`: `aria-describedby` is read when focus reaches the control, which
21
+ * covers an error that was already there and covers nothing about one that arrives on
22
+ * submit — by then focus has left the field and the only thing that changed is a span
23
+ * nobody is pointed at. The two announce at different moments, and a submit-time
24
+ * rejection only has the second.
25
+ */
26
+ export interface ControlMessages {
27
+ /** True when an error is present — the caller puts this on `aria-invalid`. */
28
+ hasError: boolean;
29
+ /** The `aria-describedby` value for the control, or `undefined` when there is nothing to say. */
30
+ describedBy: string | undefined;
31
+ /** The rendered hint and error nodes, placed after the control by the caller. */
32
+ messages: ReactNode;
33
+ }
34
+
35
+ export function useControlMessages(
36
+ hint: UiText | undefined,
37
+ error: string | null | undefined,
38
+ ): ControlMessages {
39
+ const resolve = useUiText();
40
+ const baseId = useId();
41
+ const hasError = error !== undefined && error !== null;
42
+ const hintId = hint !== undefined ? `${baseId}-hint` : undefined;
43
+ const errorId = hasError ? `${baseId}-error` : undefined;
44
+ const describedBy =
45
+ [hintId, errorId].filter((id) => id !== undefined).join(" ") || undefined;
46
+
47
+ return {
48
+ hasError,
49
+ describedBy,
50
+ messages: (
51
+ <>
52
+ {hint !== undefined && (
53
+ <span id={hintId} data-terp="field-hint">
54
+ {resolve(hint)}
55
+ </span>
56
+ )}
57
+ {hasError && (
58
+ <span id={errorId} role="alert" data-terp="field-error">
59
+ {error}
60
+ </span>
61
+ )}
62
+ </>
63
+ ),
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Merge a caller's own `aria-describedby` with the field's, rather than replacing it.
69
+ *
70
+ * A control that already points at something keeps pointing at it: dropping the caller's
71
+ * value would silently remove a description they added deliberately, and an assistive
72
+ * technology would simply stop reading it with no error anywhere.
73
+ */
74
+ export function mergeDescribedBy(
75
+ own: string | undefined,
76
+ added: string | undefined,
77
+ ): string | undefined {
78
+ return (
79
+ [own, added].filter((id) => id !== undefined && id !== "").join(" ") || undefined
80
+ );
81
+ }