@terpjs/react-core 0.30.0 → 0.32.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.
Files changed (82) hide show
  1. package/README.md +35 -14
  2. package/package.json +5 -5
  3. package/src/DashboardPage.tsx +34 -0
  4. package/src/Field.test.tsx +26 -1
  5. package/src/Field.tsx +15 -5
  6. package/src/HubPage.tsx +7 -2
  7. package/src/ModuleNav.test.tsx +29 -1
  8. package/src/ModuleNav.tsx +5 -1
  9. package/src/Page.test.tsx +192 -0
  10. package/src/Page.tsx +141 -55
  11. package/src/PageActions.test.tsx +64 -3
  12. package/src/PageActions.tsx +40 -15
  13. package/src/PageSequence.tsx +114 -0
  14. package/src/Stat.test.tsx +376 -0
  15. package/src/Stat.tsx +316 -0
  16. package/src/Timeline.test.tsx +74 -0
  17. package/src/Timeline.tsx +71 -0
  18. package/src/admin/AdminHub.tsx +233 -78
  19. package/src/admin/AuditLogAdmin.tsx +3 -1
  20. package/src/admin/GroupCreate.tsx +3 -1
  21. package/src/admin/GroupDetail.tsx +72 -67
  22. package/src/admin/GroupsAdmin.tsx +3 -1
  23. package/src/admin/ModuleAccessPanel.tsx +13 -12
  24. package/src/admin/RecordHistory.tsx +88 -0
  25. package/src/admin/UserCreate.tsx +3 -1
  26. package/src/admin/UserDetail.tsx +8 -1
  27. package/src/admin/UsersAdmin.tsx +3 -0
  28. package/src/admin/admin.test.tsx +389 -19
  29. package/src/bootstrap.test.tsx +31 -7
  30. package/src/bootstrap.tsx +30 -4
  31. package/src/charts/BarChart.tsx +74 -0
  32. package/src/charts/ProportionBar.tsx +118 -0
  33. package/src/charts/StatusHistory.tsx +75 -0
  34. package/src/charts/TrendChart.tsx +232 -0
  35. package/src/charts/charts.test.tsx +409 -0
  36. package/src/charts/scale.ts +103 -0
  37. package/src/currentInView.ts +28 -0
  38. package/src/dataview/DataView.test.tsx +303 -1
  39. package/src/dataview/DataView.tsx +53 -3
  40. package/src/dataview/DataViewCardList.tsx +21 -13
  41. package/src/dataview/DataViewTable.tsx +5 -6
  42. package/src/dataview/DataViewToolbar.tsx +4 -1
  43. package/src/dataview/README.md +18 -0
  44. package/src/dataview/index.ts +1 -0
  45. package/src/dataview/internal.tsx +112 -5
  46. package/src/dataview/types.ts +39 -10
  47. package/src/errorMessages.test.tsx +17 -0
  48. package/src/errorMessages.tsx +18 -0
  49. package/src/format.ts +15 -0
  50. package/src/index.ts +24 -1
  51. package/src/layout.manifest.json +2 -9
  52. package/src/layout.manifest.test.ts +4 -2
  53. package/src/layout.test.tsx +74 -6
  54. package/src/layout.tsx +85 -25
  55. package/src/layoutContract.test.tsx +239 -1
  56. package/src/layoutContract.ts +131 -5
  57. package/src/layoutDeclaration.test.ts +31 -10
  58. package/src/layoutDeclaration.ts +9 -4
  59. package/src/locale.tsx +28 -3
  60. package/src/markers.test.ts +70 -2
  61. package/src/router.test.tsx +15 -3
  62. package/src/router.tsx +11 -2
  63. package/src/ssr.test.tsx +18 -0
  64. package/src/styles.test.ts +288 -190
  65. package/src/styles.ts +1379 -361
  66. package/src/theme.test.tsx +44 -18
  67. package/src/theme.themes.test.ts +22 -2
  68. package/src/theme.tsx +22 -14
  69. package/src/themes.ts +39 -4
  70. package/src/tokens.guard.test.ts +13 -15
  71. package/src/typography.tsx +5 -1
  72. package/src/ui/Alert.test.tsx +24 -1
  73. package/src/ui/Alert.tsx +10 -1
  74. package/src/ui/Card.tsx +5 -4
  75. package/src/ui/Tabs.test.tsx +44 -0
  76. package/src/ui/Tabs.tsx +5 -2
  77. package/src/ui/Tooltip.test.tsx +171 -2
  78. package/src/ui/Tooltip.tsx +144 -8
  79. package/src/ui/controlMessages.tsx +20 -7
  80. package/src/uiText.test.tsx +16 -0
  81. package/src/uiText.tsx +105 -7
  82. package/src/viewerTimeZone.ts +15 -0
@@ -4,7 +4,7 @@ import { vi } from "vitest";
4
4
  import { afterEach, describe, expect, it } from "vitest";
5
5
 
6
6
  import { Button } from "./Button";
7
- import { Tooltip } from "./Tooltip";
7
+ import { Tooltip, placeBubble } from "./Tooltip";
8
8
 
9
9
  afterEach(cleanup);
10
10
 
@@ -57,7 +57,8 @@ describe("Tooltip", () => {
57
57
  </Tooltip>,
58
58
  );
59
59
  const tooltip = screen.getByRole("tooltip");
60
- const anchor = tooltip.parentElement!;
60
+ // The trigger's parent, not the bubble's: the bubble is portalled to the body.
61
+ const anchor = screen.getByRole("button", { name: "Help" }).parentElement!;
61
62
  fireEvent.mouseLeave(anchor);
62
63
  // Still open partway through the grace period...
63
64
  act(() => {
@@ -80,4 +81,172 @@ describe("Tooltip", () => {
80
81
  vi.useRealTimers();
81
82
  }
82
83
  });
84
+
85
+ it("renders the bubble outside its anchor, so no scroll container can clip it", () => {
86
+ // An absolutely positioned child of the anchor was clipped by any ancestor whose overflow
87
+ // was not visible, whatever its z-index -- a tooltip in a DataView cell was cut off at the
88
+ // table's edge. Portalled, the bubble has no ancestor but the body. The description link
89
+ // survives the move: aria-describedby is by id, not by position in the tree.
90
+ // Mutation: render the bubble inside the anchor again, and the first assertion fails.
91
+ render(
92
+ <div data-testid="scroller">
93
+ <Tooltip content="More information" defaultOpen>
94
+ <Button>Help</Button>
95
+ </Tooltip>
96
+ </div>,
97
+ );
98
+ const tooltip = screen.getByRole("tooltip");
99
+ expect(tooltip.parentElement).toBe(document.body);
100
+ expect(screen.getByTestId("scroller")).not.toContainElement(tooltip);
101
+ expect(screen.getByRole("button", { name: "Help" })).toHaveAccessibleDescription(
102
+ "More information",
103
+ );
104
+ });
105
+
106
+ it("renders the bubble inside its trigger's dialog, the one place above the top layer", () => {
107
+ // A modal dialog is in the top layer, and a bubble portalled to the body painted behind it
108
+ // and its backdrop whatever its z-index -- measured in Chromium. Inside the dialog it is
109
+ // painted with it.
110
+ // Mutation: portal to the body again, and the bubble's parent is the body.
111
+ render(
112
+ <dialog open data-testid="dialog">
113
+ <Tooltip content="More information" defaultOpen>
114
+ <Button>Help</Button>
115
+ </Tooltip>
116
+ </dialog>,
117
+ );
118
+ expect(screen.getByRole("tooltip").parentElement).toBe(screen.getByTestId("dialog"));
119
+ });
120
+
121
+ it("is placed again when its text changes while it is open", () => {
122
+ // "Copy" becoming "Copied to clipboard" under the pointer: the bubble grows, and a bubble
123
+ // placed for the short text ran past the window's right edge.
124
+ // Mutation: drop the text from the placement's dependencies, and the long bubble keeps the
125
+ // left it was given for "Copy".
126
+ const original = HTMLElement.prototype.getBoundingClientRect;
127
+ HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) {
128
+ const marker = this.getAttribute("data-terp");
129
+ if (marker === "tooltip-anchor") {
130
+ return { left: 900, right: 960, top: 300, bottom: 336, width: 60, height: 36 } as DOMRect;
131
+ }
132
+ if (marker === "tooltip") {
133
+ const width = (this.textContent ?? "").length * 10;
134
+ return { left: 0, right: width, top: 0, bottom: 40, width, height: 40 } as DOMRect;
135
+ }
136
+ return original.call(this);
137
+ };
138
+ try {
139
+ const { rerender } = render(
140
+ <Tooltip content="Copy" defaultOpen>
141
+ <Button>Copy</Button>
142
+ </Tooltip>,
143
+ );
144
+ const tooltip = screen.getByRole("tooltip");
145
+ expect(tooltip.style.left).toBe("900px");
146
+ rerender(
147
+ <Tooltip content="Copied to clipboard" defaultOpen>
148
+ <Button>Copy</Button>
149
+ </Tooltip>,
150
+ );
151
+ expect(tooltip.style.left).toBe(`${window.innerWidth - 190 - 8}px`);
152
+ } finally {
153
+ HTMLElement.prototype.getBoundingClientRect = original;
154
+ }
155
+ });
156
+
157
+ it("stays open while the pointer moves from the trigger onto the portalled bubble", () => {
158
+ // Hoverable survives the portal because React dispatches enter and leave along the
159
+ // component tree, where the bubble is still inside the anchor. Driven with the native pair
160
+ // React actually listens to (mouseout/mouseover), from the trigger straight onto the bubble.
161
+ // Mutation: portal the bubble from a sibling of the anchor instead of from inside it, and
162
+ // this leave reaches the anchor and closes it.
163
+ vi.useFakeTimers();
164
+ try {
165
+ render(
166
+ <Tooltip content="More information" defaultOpen>
167
+ <Button>Help</Button>
168
+ </Tooltip>,
169
+ );
170
+ const tooltip = screen.getByRole("tooltip");
171
+ const trigger = screen.getByRole("button", { name: "Help" });
172
+ fireEvent.mouseOut(trigger, { relatedTarget: tooltip });
173
+ fireEvent.mouseOver(tooltip, { relatedTarget: trigger });
174
+ act(() => {
175
+ vi.advanceTimersByTime(500);
176
+ });
177
+ expect(tooltip).toBeVisible();
178
+ } finally {
179
+ vi.useRealTimers();
180
+ }
181
+ });
182
+
183
+ it("places an open bubble from what it measured, inside the window", () => {
184
+ // A trigger at the top-right corner -- a page band's primary action -- is the case that put
185
+ // the message off screen: it opened above, at the trigger's left edge, a trigger's width
186
+ // wide. Measured now: above does not fit, so it flips below, and it is pushed in from the
187
+ // right edge by exactly its own width.
188
+ // Mutation: drop the layout effect, and the bubble stays at 0,0 and hidden.
189
+ const rects = new Map<string, Partial<DOMRect>>([
190
+ ["tooltip-anchor", { left: 950, right: 1010, top: 10, bottom: 46, width: 60, height: 36 }],
191
+ ["tooltip", { left: 0, right: 200, top: 0, bottom: 40, width: 200, height: 40 }],
192
+ ]);
193
+ const original = HTMLElement.prototype.getBoundingClientRect;
194
+ HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) {
195
+ const rect = rects.get(this.getAttribute("data-terp") ?? "");
196
+ return rect === undefined ? original.call(this) : (rect as DOMRect);
197
+ };
198
+ try {
199
+ render(
200
+ <Tooltip content="More information" defaultOpen>
201
+ <Button>Help</Button>
202
+ </Tooltip>,
203
+ );
204
+ const tooltip = screen.getByRole("tooltip");
205
+ expect(tooltip.style.visibility).toBe("visible");
206
+ expect(tooltip.style.top).toBe("50px"); // below: bottom 46 + gap 4
207
+ expect(tooltip.style.left).toBe(`${window.innerWidth - 200 - 8}px`);
208
+ } finally {
209
+ HTMLElement.prototype.getBoundingClientRect = original;
210
+ }
211
+ });
212
+ });
213
+
214
+ describe("placeBubble", () => {
215
+ const viewport = { width: 1280, height: 900 };
216
+ const bubble = { width: 200, height: 40 };
217
+
218
+ it("opens above a trigger with room above it, at the trigger's start edge", () => {
219
+ expect(placeBubble({ left: 100, right: 160, top: 300, bottom: 336 }, bubble, viewport)).toEqual(
220
+ { left: 100, top: 256 },
221
+ );
222
+ });
223
+
224
+ it("flips below a trigger too close to the top", () => {
225
+ expect(placeBubble({ left: 100, right: 160, top: 20, bottom: 56 }, bubble, viewport)).toEqual({
226
+ left: 100,
227
+ top: 60,
228
+ });
229
+ });
230
+
231
+ it("is pushed in from the right edge rather than crossing it", () => {
232
+ expect(
233
+ placeBubble({ left: 1200, right: 1260, top: 300, bottom: 336 }, bubble, viewport).left,
234
+ ).toBe(1280 - 200 - 8);
235
+ });
236
+
237
+ it("aligns to the trigger's right edge in a right-to-left document, and stays in from the left", () => {
238
+ expect(
239
+ placeBubble({ left: 600, right: 660, top: 300, bottom: 336 }, bubble, viewport, true).left,
240
+ ).toBe(460);
241
+ expect(
242
+ placeBubble({ left: 10, right: 70, top: 300, bottom: 336 }, bubble, viewport, true).left,
243
+ ).toBe(8);
244
+ });
245
+
246
+ it("stays on screen in a window too short for either side, over the trigger", () => {
247
+ expect(
248
+ placeBubble({ left: 100, right: 160, top: 20, bottom: 56 }, bubble, { width: 1280, height: 90 })
249
+ .top,
250
+ ).toBe(8);
251
+ });
83
252
  });
@@ -1,5 +1,14 @@
1
- import { cloneElement, isValidElement, useEffect, useId, useRef, useState } from "react";
2
- import type { FocusEvent, MouseEvent, ReactElement } from "react";
1
+ import {
2
+ cloneElement,
3
+ isValidElement,
4
+ useEffect,
5
+ useId,
6
+ useLayoutEffect,
7
+ useRef,
8
+ useState,
9
+ } from "react";
10
+ import type { CSSProperties, FocusEvent, MouseEvent, ReactElement } from "react";
11
+ import { createPortal } from "react-dom";
3
12
 
4
13
  import { injectTerpStyles } from "../styles";
5
14
  import { useUiText } from "../uiText";
@@ -22,6 +31,52 @@ export interface TooltipProps {
22
31
  defaultOpen?: boolean;
23
32
  }
24
33
 
34
+ /** The bubble never comes closer than this to the window's edge. Popover's value. */
35
+ const VIEWPORT_GUTTER = 8;
36
+ /** Between the trigger and the bubble: the var(--space-1) the sheet used to offset it by. */
37
+ const BUBBLE_GAP = 4;
38
+
39
+ interface BubblePosition {
40
+ left: number;
41
+ top: number;
42
+ visibility: CSSProperties["visibility"];
43
+ }
44
+
45
+ const UNPLACED: BubblePosition = { left: 0, top: 0, visibility: "hidden" };
46
+
47
+ /**
48
+ * Where the bubble goes: above the trigger if it fits there, below if it does not, and inside
49
+ * the window either way. Start-aligned with the trigger, as the sheet placed it before -- the
50
+ * trigger's left edge, or its right one in a right-to-left document -- and pushed back in from
51
+ * whichever edge it would cross. Exported for its tests, not from the package.
52
+ */
53
+ export function placeBubble(
54
+ trigger: Pick<DOMRect, "left" | "right" | "top" | "bottom">,
55
+ bubble: Pick<DOMRect, "width" | "height">,
56
+ viewport: { width: number; height: number },
57
+ rtl = false,
58
+ ): Pick<BubblePosition, "left" | "top"> {
59
+ const above = trigger.top - BUBBLE_GAP - bubble.height;
60
+ const below = trigger.bottom + BUBBLE_GAP;
61
+ const fitsAbove = above >= VIEWPORT_GUTTER;
62
+ const fitsBelow = below + bubble.height <= viewport.height - VIEWPORT_GUTTER;
63
+ // Above is the preference; below only when above does not fit and below does. With room in
64
+ // neither (a very short window), above is clamped to the top edge and covers the trigger,
65
+ // which is still readable, where off-screen is not.
66
+ const rawTop = fitsAbove || !fitsBelow ? above : below;
67
+ const rawLeft = rtl ? trigger.right - bubble.width : trigger.left;
68
+ return {
69
+ left: Math.max(
70
+ VIEWPORT_GUTTER,
71
+ Math.min(rawLeft, viewport.width - bubble.width - VIEWPORT_GUTTER),
72
+ ),
73
+ top: Math.max(
74
+ VIEWPORT_GUTTER,
75
+ Math.min(rawTop, viewport.height - bubble.height - VIEWPORT_GUTTER),
76
+ ),
77
+ };
78
+ }
79
+
25
80
  interface TriggerHandlers {
26
81
  onFocus?: (event: FocusEvent) => void;
27
82
  onBlur?: (event: FocusEvent) => void;
@@ -42,19 +97,48 @@ interface TriggerHandlers {
42
97
  * - **Hoverable.** The bubble is reachable with the pointer. It used to declare
43
98
  * `pointer-events: none`, which makes hovering it impossible by construction — so a tooltip
44
99
  * long enough to need reading could not be read by anyone tracking with a pointer or using
45
- * magnification. The bubble is a DOM child of the anchor, so moving onto it does not fire the
46
- * anchor's `mouseleave`; the close delay below covers the visual gap between the two, which
47
- * the pointer does cross.
100
+ * magnification. The bubble is portalled, but React dispatches enter and leave along the
101
+ * component tree rather than the DOM, where the bubble is still the anchor's child — so
102
+ * moving onto it does not fire the anchor's `mouseleave`. The close delay below covers the
103
+ * visual gap between the two, which the pointer does cross.
48
104
  * - **Persistent.** It stays until dismissed, focus leaves or the pointer leaves — it has never
49
105
  * had a timeout.
106
+ *
107
+ * And it is readable wherever its trigger is. The bubble is portalled to the body -- or into the
108
+ * dialog its trigger sits in, since nothing outside a modal dialog paints above it -- and placed
109
+ * from measured coordinates (see the sheet's tooltip rule for the three ways the absolutely
110
+ * positioned version was not): no scroll container clips it, its width is the message's
111
+ * rather than the trigger's, and it flips below a trigger too close to the top and stays
112
+ * inside the window at the sides.
50
113
  */
51
114
  export function Tooltip({ content, children, defaultOpen = false }: TooltipProps) {
52
115
  const id = useId();
53
116
  const resolve = useUiText();
54
117
  const [open, setOpen] = useState(defaultOpen);
118
+ // Resolved once, and a dependency of the placement below: text that changes while the
119
+ // bubble is open ("Copy" becoming "Copied to clipboard") changes its size, and a bubble
120
+ // placed for the old size runs past the window's edge or over its trigger.
121
+ const text = resolve(content);
122
+ const anchorRef = useRef<HTMLSpanElement>(null);
123
+ const bubbleRef = useRef<HTMLSpanElement>(null);
124
+ const [position, setPosition] = useState<BubblePosition>(UNPLACED);
125
+ // Where the bubble is portalled to, known only once mounted: a server render has no body,
126
+ // and the first client render has to produce what the server did.
127
+ const [host, setHost] = useState<HTMLElement | null>(null);
55
128
  // Cleared on re-entry, which is what makes the gap between trigger and bubble crossable.
56
129
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
57
130
 
131
+ useEffect(() => {
132
+ // The trigger's own <dialog> when it sits in one, and the body otherwise. A modal dialog
133
+ // is in the top layer, and nothing outside it paints above it or its backdrop whatever
134
+ // its z-index: a bubble portalled to the body opened BEHIND the dialog its trigger was in.
135
+ // Measured in Chromium: a fixed box inside a modal dialog, outside the dialog's own box,
136
+ // is the topmost element at its point (the dialog's overflow: auto does not clip it, since
137
+ // a fixed box is placed against the viewport), and the same box under the body at
138
+ // z-index 70 is covered by the backdrop.
139
+ setHost(anchorRef.current?.closest("dialog") ?? document.body);
140
+ }, []);
141
+
58
142
  function cancelClose() {
59
143
  if (closeTimer.current !== null) {
60
144
  clearTimeout(closeTimer.current);
@@ -85,12 +169,66 @@ export function Tooltip({ content, children, defaultOpen = false }: TooltipProps
85
169
  return () => document.removeEventListener("keydown", onKeyDown);
86
170
  }, [open]);
87
171
 
172
+ // Measured before paint, so an open bubble is never painted where it was last time; the
173
+ // first open is painted nowhere until this has run (UNPLACED is visibility: hidden). Kept up
174
+ // to date while open, because a fixed bubble does not move with a scrolled trigger.
175
+ useLayoutEffect(() => {
176
+ if (!open || host === null) {
177
+ return;
178
+ }
179
+ function update() {
180
+ const anchor = anchorRef.current;
181
+ const bubble = bubbleRef.current;
182
+ if (anchor === null || bubble === null) {
183
+ return;
184
+ }
185
+ // The root's client box rather than the window's inner size: innerWidth includes a
186
+ // classic vertical scrollbar, so a bubble pushed in from the right edge by it could
187
+ // still sit partly under the bar. A document with no layout reports 0 here, and the
188
+ // window's size is the honest answer then.
189
+ const root = document.documentElement;
190
+ const { left, top } = placeBubble(
191
+ anchor.getBoundingClientRect(),
192
+ bubble.getBoundingClientRect(),
193
+ {
194
+ width: root.clientWidth || window.innerWidth,
195
+ height: root.clientHeight || window.innerHeight,
196
+ },
197
+ getComputedStyle(anchor).direction === "rtl",
198
+ );
199
+ setPosition({ left, top, visibility: "visible" });
200
+ }
201
+ update();
202
+ window.addEventListener("resize", update);
203
+ window.addEventListener("scroll", update, true);
204
+ return () => {
205
+ window.removeEventListener("resize", update);
206
+ window.removeEventListener("scroll", update, true);
207
+ };
208
+ }, [open, host, text]);
209
+
88
210
  if (!isValidElement<TriggerHandlers>(children)) {
89
211
  return children;
90
212
  }
91
213
 
214
+ const bubble = (
215
+ <span
216
+ ref={bubbleRef}
217
+ id={id}
218
+ role="tooltip"
219
+ data-terp="tooltip"
220
+ hidden={!open}
221
+ // Only the measured part is inline -- the coordinates and the visibility that hides the
222
+ // bubble for the frame before they exist. Everything it LOOKS like is the sheet's.
223
+ style={position}
224
+ >
225
+ {text}
226
+ </span>
227
+ );
228
+
92
229
  return (
93
230
  <span
231
+ ref={anchorRef}
94
232
  data-terp="tooltip-anchor"
95
233
  onMouseEnter={() => {
96
234
  cancelClose();
@@ -110,9 +248,7 @@ export function Tooltip({ content, children, defaultOpen = false }: TooltipProps
110
248
  setOpen(false);
111
249
  },
112
250
  })}
113
- <span id={id} role="tooltip" data-terp="tooltip" hidden={!open}>
114
- {resolve(content)}
115
- </span>
251
+ {host !== null && createPortal(bubble, host)}
116
252
  </span>
117
253
  );
118
254
  }
@@ -54,14 +54,27 @@ export function useControlMessages(
54
54
  // arrive as a few pixels of drift on screens nobody touched. With the guard, a field
55
55
  // with no messages renders exactly the DOM it rendered before.
56
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.
57
+ // What the box buys is ONE item under the control. Field puts it in its body, beside the
58
+ // control and inside the <label>, so a field is two things wherever fields share lines --
59
+ // its label and its body -- and no line is ever empty: a row where no field has a hint
60
+ // does not carry a zero-height messages line with a gutter on either side of it.
61
+ //
62
+ // A <span> rather than a <div> for that reason: a <label> holds phrasing content, and the
63
+ // envelope now sits inside one. It is display: grid in the sheet, so the element changes
64
+ // nothing it renders; the self-labelling controls (Switch, Checkbox, RadioGroup), which
65
+ // render it outside any label, get the same box.
62
66
  messages:
63
67
  hint === undefined && !hasError ? null : (
64
- <div data-terp="field-messages">
68
+ <span
69
+ data-terp="field-messages"
70
+ // Field puts this box inside its <label>, and a click anywhere in a label that is
71
+ // not itself interactive is forwarded to the label's control: clicking or
72
+ // double-click-selecting an error opened a Select or a DatePicker, and toggled a
73
+ // checkbox. Cancelling the click skips the label's activation and nothing else —
74
+ // the box holds text only, so there is no link or button in it to break, and outside
75
+ // a label (Checkbox, Switch, Radio) a click on a span has no default to cancel.
76
+ onClick={(event) => event.preventDefault()}
77
+ >
65
78
  {hint !== undefined && (
66
79
  <span id={hintId} data-terp="field-hint">
67
80
  {resolve(hint)}
@@ -72,7 +85,7 @@ export function useControlMessages(
72
85
  {error}
73
86
  </span>
74
87
  )}
75
- </div>
88
+ </span>
76
89
  ),
77
90
  };
78
91
  }
@@ -13,6 +13,7 @@ import {
13
13
  UiTextProvider,
14
14
  usePlural,
15
15
  useUiText,
16
+ fillPlaceholders,
16
17
  } from "./uiText";
17
18
  import type { PluralText } from "./uiText";
18
19
 
@@ -246,3 +247,18 @@ describe("FrameworkText", () => {
246
247
  expect(manifest.nav).toHaveLength(1);
247
248
  });
248
249
  });
250
+
251
+ describe("fillPlaceholders", () => {
252
+ it("fills the names it is given and leaves any other as written", () => {
253
+ expect(fillPlaceholders("{current} of {total}", { current: 4, total: 23 })).toBe("4 of 23");
254
+ expect(fillPlaceholders("{current} of {total}", { current: 4 })).toBe("4 of {total}");
255
+ });
256
+
257
+ it("leaves a name every object inherits as written", () => {
258
+ // `key in values` matched inherited members, so a catalog typo of {constructor} printed
259
+ // the source text of Object. Mutation: `key in values` again, and this fails.
260
+ expect(fillPlaceholders("{current} {constructor} {toString}", { current: 4 })).toBe(
261
+ "4 {constructor} {toString}",
262
+ );
263
+ });
264
+ });
package/src/uiText.tsx CHANGED
@@ -113,6 +113,21 @@ export function resolveUiTextNode(
113
113
  }
114
114
 
115
115
  /** The default resolver: plain strings as-is, descriptors via their fallback `message`. */
116
+ /**
117
+ * `{name}` placeholders in *template*, filled from *values*. A name *values* does not own is left
118
+ * as written — including one every object inherits: `key in values` filled `{constructor}` with
119
+ * the source text of `Object`. The one formatter for a framework string that counts or names
120
+ * something (the DataView's ranges, the page sequence's steps), so a fix reaches every caller.
121
+ */
122
+ export function fillPlaceholders(
123
+ template: string,
124
+ values: Readonly<Record<string, string | number>>,
125
+ ): string {
126
+ return template.replace(/\{(\w+)\}/g, (match, key: string) =>
127
+ Object.hasOwn(values, key) ? String(values[key]) : match,
128
+ );
129
+ }
130
+
116
131
  export function resolveUiText(text: UiText): string {
117
132
  return typeof text === "string" ? text : text.message;
118
133
  }
@@ -166,6 +181,53 @@ export interface TerpStrings {
166
181
  moduleNavigationLabel: string;
167
182
  /** Accessible label of the page-actions overflow trigger. */
168
183
  moreActions: string;
184
+ /** Accessible name of a page's link to the previous item of its sequence; `{label}` is that item. */
185
+ pageSequencePrevious: string;
186
+ /** Accessible name of a page's link to the next item of its sequence; `{label}` is that item. */
187
+ pageSequenceNext: string;
188
+ /** A page's place in its sequence; `{current}` and `{total}` are replaced. */
189
+ pageSequencePosition: string;
190
+ /** A figure's change that is good news, read out after it (the pill's colour, as a word). */
191
+ statFavourable: string;
192
+ /** A figure's change that is bad news, read out after it (the pill's colour, as a word). */
193
+ statUnfavourable: string;
194
+ /** A figure's sparkline as text; `{points}` is the listed points, each a label and a value. */
195
+ statTrend: string;
196
+ /**
197
+ * Named the total on the admin hub's users and groups cards until the hub became a dashboard,
198
+ * whose figures name what they count. Not read by the framework since; kept because a
199
+ * catalog that leaves out a framework string, or carries one the framework does not know, is
200
+ * refused, so an app's catalog written for 0.31.0 still loads.
201
+ */
202
+ adminHubTotal: string;
203
+ /** The admin hub's headline figure: the accounts that can sign in. */
204
+ adminHubActiveAccounts: string;
205
+ /** Under that figure; `{count}` is the number of deactivated accounts. */
206
+ adminHubDeactivated: string;
207
+ /** The admin hub's figure for the audit trail's last days; `{count}` is how many. */
208
+ adminHubChangesWeek: string;
209
+ /** What that figure's change is measured against. */
210
+ adminHubVsWeekBefore: string;
211
+ /** The admin hub's chart of the trail per day. */
212
+ adminHubChangesPerDay: string;
213
+ /** That chart's series; `{count}` is how many days it draws. */
214
+ adminHubLastDays: string;
215
+ /** That chart's comparison, drawn dashed; `{count}` is how many days it covers. */
216
+ adminHubDaysBefore: string;
217
+ /** The admin hub's share of each kind of change; `{count}` is how many days it covers. */
218
+ adminHubChangesByKind: string;
219
+ /** A status history read out; `{label}` is what ran and `{runs}` the listed runs, each a label and its ending. */
220
+ statusHistoryRuns: string;
221
+ /** A record's own history, from the audit trail, on its admin screen: the section's title. */
222
+ recordHistory: string;
223
+ /** An audit event: a record was created. */
224
+ auditActionCreated: string;
225
+ /** An audit event: a record was changed. */
226
+ auditActionUpdated: string;
227
+ /** An audit event: a record was deleted. */
228
+ auditActionDeleted: string;
229
+ /** An audit event: guarded data was shown to someone (ADR 0118). */
230
+ auditActionDisclosed: string;
169
231
  /** Default {@link ErrorState} title. */
170
232
  errorTitle: string;
171
233
  /** Title shown by `RequireAuth` when the backend did not answer the boot check. */
@@ -206,13 +268,16 @@ export interface TerpStrings {
206
268
  closeNavigation: string;
207
269
  /** Label of the {@link ThemeToggle} select. */
208
270
  theme: string;
209
- /** {@link ThemeToggle} option: the light theme. */
271
+ /**
272
+ * {@link ThemeToggle} option: `midday`, the light theme. The key keeps the theme's earlier
273
+ * name (`light`), so a catalog written before the rename still loads; the value is the new one.
274
+ */
210
275
  themeLight: string;
211
- /** {@link ThemeToggle} option: the dark theme. */
276
+ /** {@link ThemeToggle} option: `evening`, the slate dark theme (key from its earlier name, `dark`). */
212
277
  themeDark: string;
213
- /** {@link ThemeToggle} option: the near-black dark theme. */
278
+ /** {@link ThemeToggle} option: `night`, the near-black dark theme (key from its earlier name, `midnight`). */
214
279
  themeMidnight: string;
215
- /** {@link ThemeToggle} option: the violet-tinted dark theme. */
280
+ /** {@link ThemeToggle} option: `twilight`, the dimmed violet dark theme. */
216
281
  themeTwilight: string;
217
282
  /** {@link ThemeToggle} option: the high-contrast theme. */
218
283
  themeContrast: string;
@@ -460,6 +525,14 @@ export interface TerpStrings {
460
525
  errorCodeConflict: string;
461
526
  /** Error code `stale_data`. */
462
527
  errorCodeStaleData: string;
528
+ /** Error code `rate_limited`, the rate limiter's refusal. */
529
+ errorCodeRateLimited: string;
530
+ /** Error code `request_too_large`, a body over the size limit. */
531
+ errorCodeRequestTooLarge: string;
532
+ /** Error code `internal_error`, an unhandled failure on the server. */
533
+ errorCodeInternalError: string;
534
+ /** Error code `idempotency_in_flight`: the same request is still being carried out. */
535
+ errorCodeStillProcessing: string;
463
536
  }
464
537
 
465
538
  export const DEFAULT_STRINGS: TerpStrings = {
@@ -493,6 +566,27 @@ export const DEFAULT_STRINGS: TerpStrings = {
493
566
  breadcrumbsLabel: "Breadcrumb",
494
567
  moduleNavigationLabel: "Module navigation",
495
568
  moreActions: "More actions",
569
+ pageSequencePrevious: "Previous: {label}",
570
+ pageSequenceNext: "Next: {label}",
571
+ pageSequencePosition: "{current} of {total}",
572
+ statFavourable: "favourable",
573
+ statUnfavourable: "unfavourable",
574
+ statTrend: "Over time: {points}",
575
+ adminHubTotal: "Total",
576
+ adminHubActiveAccounts: "Active accounts",
577
+ adminHubDeactivated: "{count} deactivated",
578
+ adminHubChangesWeek: "Changes, last {count} days",
579
+ adminHubVsWeekBefore: "vs the week before",
580
+ adminHubChangesPerDay: "Changes per day",
581
+ adminHubLastDays: "Last {count} days",
582
+ adminHubDaysBefore: "The {count} days before",
583
+ adminHubChangesByKind: "Changes by kind, last {count} days",
584
+ statusHistoryRuns: "{label}, oldest first: {runs}",
585
+ recordHistory: "History",
586
+ auditActionCreated: "Created",
587
+ auditActionUpdated: "Changed",
588
+ auditActionDeleted: "Deleted",
589
+ auditActionDisclosed: "Viewed",
496
590
  errorTitle: "Something went wrong.",
497
591
  backendUnreachableTitle: "The application cannot reach its server.",
498
592
  backendUnreachableDescription:
@@ -515,9 +609,9 @@ export const DEFAULT_STRINGS: TerpStrings = {
515
609
  openNavigation: "Open navigation",
516
610
  closeNavigation: "Close navigation",
517
611
  theme: "Theme",
518
- themeLight: "Light",
519
- themeDark: "Dark",
520
- themeMidnight: "Midnight",
612
+ themeLight: "Midday",
613
+ themeDark: "Evening",
614
+ themeMidnight: "Night",
521
615
  themeTwilight: "Twilight",
522
616
  themeContrast: "High contrast",
523
617
  themeSystem: "System",
@@ -647,6 +741,10 @@ export const DEFAULT_STRINGS: TerpStrings = {
647
741
  errorCodeNotFound: "This item could not be found.",
648
742
  errorCodeConflict: "This conflicts with the current state. Refresh and try again.",
649
743
  errorCodeStaleData: "This item was changed by someone else. Refresh and try again.",
744
+ errorCodeRateLimited: "Too many requests at once. Wait a moment and try again.",
745
+ errorCodeRequestTooLarge: "This is too large to send. Make it smaller and try again.",
746
+ errorCodeInternalError: "Something went wrong on the server. Try again in a moment.",
747
+ errorCodeStillProcessing: "This is still being processed. Wait a moment, then check again.",
650
748
  };
651
749
 
652
750
  interface UiTextContextValue {
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The viewer's own time zone, as an IANA name, or `UTC` where the host cannot say.
3
+ *
4
+ * The one question about the host the app has no answer of its own for. Dates are formatted in
5
+ * the app's locale everywhere, but a calendar day is the viewer's: the admin hub counts the
6
+ * audit trail in the days of whoever is looking at it (ADR 0171). Its own module so the
7
+ * locale gate's allowance covers this one read and nothing that might format beside it.
8
+ */
9
+ export function viewerTimeZone(): string {
10
+ try {
11
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
12
+ } catch {
13
+ return "UTC";
14
+ }
15
+ }