@terpjs/react-core 0.30.0 → 0.31.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 (75) 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/Page.test.tsx +192 -0
  8. package/src/Page.tsx +141 -55
  9. package/src/PageActions.test.tsx +64 -3
  10. package/src/PageActions.tsx +40 -15
  11. package/src/PageSequence.tsx +114 -0
  12. package/src/Stat.test.tsx +341 -0
  13. package/src/Stat.tsx +314 -0
  14. package/src/Timeline.test.tsx +74 -0
  15. package/src/Timeline.tsx +71 -0
  16. package/src/admin/AdminHub.tsx +11 -3
  17. package/src/admin/AuditLogAdmin.tsx +3 -1
  18. package/src/admin/GroupCreate.tsx +3 -1
  19. package/src/admin/GroupDetail.tsx +72 -67
  20. package/src/admin/GroupsAdmin.tsx +3 -1
  21. package/src/admin/ModuleAccessPanel.tsx +13 -12
  22. package/src/admin/RecordHistory.tsx +83 -0
  23. package/src/admin/UserCreate.tsx +3 -1
  24. package/src/admin/UserDetail.tsx +8 -1
  25. package/src/admin/UsersAdmin.tsx +3 -0
  26. package/src/admin/admin.test.tsx +208 -5
  27. package/src/bootstrap.test.tsx +31 -7
  28. package/src/bootstrap.tsx +30 -4
  29. package/src/charts/BarChart.tsx +74 -0
  30. package/src/charts/ProportionBar.tsx +118 -0
  31. package/src/charts/StatusHistory.tsx +75 -0
  32. package/src/charts/TrendChart.tsx +232 -0
  33. package/src/charts/charts.test.tsx +409 -0
  34. package/src/charts/scale.ts +103 -0
  35. package/src/dataview/DataView.test.tsx +255 -0
  36. package/src/dataview/DataView.tsx +35 -0
  37. package/src/dataview/DataViewCardList.tsx +21 -13
  38. package/src/dataview/DataViewTable.tsx +5 -6
  39. package/src/dataview/README.md +18 -0
  40. package/src/dataview/index.ts +1 -0
  41. package/src/dataview/internal.tsx +112 -5
  42. package/src/dataview/types.ts +39 -10
  43. package/src/errorMessages.test.tsx +17 -0
  44. package/src/errorMessages.tsx +18 -0
  45. package/src/format.ts +15 -0
  46. package/src/index.ts +24 -1
  47. package/src/layout.manifest.json +2 -9
  48. package/src/layout.manifest.test.ts +4 -2
  49. package/src/layout.test.tsx +74 -6
  50. package/src/layout.tsx +85 -25
  51. package/src/layoutContract.test.tsx +239 -1
  52. package/src/layoutContract.ts +131 -5
  53. package/src/layoutDeclaration.test.ts +31 -10
  54. package/src/layoutDeclaration.ts +9 -4
  55. package/src/locale.tsx +20 -3
  56. package/src/markers.test.ts +70 -2
  57. package/src/router.test.tsx +15 -3
  58. package/src/router.tsx +11 -2
  59. package/src/ssr.test.tsx +18 -0
  60. package/src/styles.test.ts +222 -190
  61. package/src/styles.ts +1268 -328
  62. package/src/theme.test.tsx +44 -18
  63. package/src/theme.themes.test.ts +22 -2
  64. package/src/theme.tsx +22 -14
  65. package/src/themes.ts +39 -4
  66. package/src/tokens.guard.test.ts +13 -15
  67. package/src/typography.tsx +5 -1
  68. package/src/ui/Alert.test.tsx +24 -1
  69. package/src/ui/Alert.tsx +10 -1
  70. package/src/ui/Card.tsx +5 -4
  71. package/src/ui/Tooltip.test.tsx +171 -2
  72. package/src/ui/Tooltip.tsx +144 -8
  73. package/src/ui/controlMessages.tsx +20 -7
  74. package/src/uiText.test.tsx +16 -0
  75. package/src/uiText.tsx +76 -7
@@ -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,32 @@ 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
+ /** The admin hub: names the total on the users and groups cards. */
197
+ adminHubTotal: string;
198
+ /** A status history read out; `{label}` is what ran and `{runs}` the listed runs, each a label and its ending. */
199
+ statusHistoryRuns: string;
200
+ /** A record's own history, from the audit trail, on its admin screen: the section's title. */
201
+ recordHistory: string;
202
+ /** An audit event: a record was created. */
203
+ auditActionCreated: string;
204
+ /** An audit event: a record was changed. */
205
+ auditActionUpdated: string;
206
+ /** An audit event: a record was deleted. */
207
+ auditActionDeleted: string;
208
+ /** An audit event: guarded data was shown to someone (ADR 0118). */
209
+ auditActionDisclosed: string;
169
210
  /** Default {@link ErrorState} title. */
170
211
  errorTitle: string;
171
212
  /** Title shown by `RequireAuth` when the backend did not answer the boot check. */
@@ -206,13 +247,16 @@ export interface TerpStrings {
206
247
  closeNavigation: string;
207
248
  /** Label of the {@link ThemeToggle} select. */
208
249
  theme: string;
209
- /** {@link ThemeToggle} option: the light theme. */
250
+ /**
251
+ * {@link ThemeToggle} option: `midday`, the light theme. The key keeps the theme's earlier
252
+ * name (`light`), so a catalog written before the rename still loads; the value is the new one.
253
+ */
210
254
  themeLight: string;
211
- /** {@link ThemeToggle} option: the dark theme. */
255
+ /** {@link ThemeToggle} option: `evening`, the slate dark theme (key from its earlier name, `dark`). */
212
256
  themeDark: string;
213
- /** {@link ThemeToggle} option: the near-black dark theme. */
257
+ /** {@link ThemeToggle} option: `night`, the near-black dark theme (key from its earlier name, `midnight`). */
214
258
  themeMidnight: string;
215
- /** {@link ThemeToggle} option: the violet-tinted dark theme. */
259
+ /** {@link ThemeToggle} option: `twilight`, the dimmed violet dark theme. */
216
260
  themeTwilight: string;
217
261
  /** {@link ThemeToggle} option: the high-contrast theme. */
218
262
  themeContrast: string;
@@ -460,6 +504,14 @@ export interface TerpStrings {
460
504
  errorCodeConflict: string;
461
505
  /** Error code `stale_data`. */
462
506
  errorCodeStaleData: string;
507
+ /** Error code `rate_limited`, the rate limiter's refusal. */
508
+ errorCodeRateLimited: string;
509
+ /** Error code `request_too_large`, a body over the size limit. */
510
+ errorCodeRequestTooLarge: string;
511
+ /** Error code `internal_error`, an unhandled failure on the server. */
512
+ errorCodeInternalError: string;
513
+ /** Error code `idempotency_in_flight`: the same request is still being carried out. */
514
+ errorCodeStillProcessing: string;
463
515
  }
464
516
 
465
517
  export const DEFAULT_STRINGS: TerpStrings = {
@@ -493,6 +545,19 @@ export const DEFAULT_STRINGS: TerpStrings = {
493
545
  breadcrumbsLabel: "Breadcrumb",
494
546
  moduleNavigationLabel: "Module navigation",
495
547
  moreActions: "More actions",
548
+ pageSequencePrevious: "Previous: {label}",
549
+ pageSequenceNext: "Next: {label}",
550
+ pageSequencePosition: "{current} of {total}",
551
+ statFavourable: "favourable",
552
+ statUnfavourable: "unfavourable",
553
+ statTrend: "Over time: {points}",
554
+ adminHubTotal: "Total",
555
+ statusHistoryRuns: "{label}, oldest first: {runs}",
556
+ recordHistory: "History",
557
+ auditActionCreated: "Created",
558
+ auditActionUpdated: "Changed",
559
+ auditActionDeleted: "Deleted",
560
+ auditActionDisclosed: "Viewed",
496
561
  errorTitle: "Something went wrong.",
497
562
  backendUnreachableTitle: "The application cannot reach its server.",
498
563
  backendUnreachableDescription:
@@ -515,9 +580,9 @@ export const DEFAULT_STRINGS: TerpStrings = {
515
580
  openNavigation: "Open navigation",
516
581
  closeNavigation: "Close navigation",
517
582
  theme: "Theme",
518
- themeLight: "Light",
519
- themeDark: "Dark",
520
- themeMidnight: "Midnight",
583
+ themeLight: "Midday",
584
+ themeDark: "Evening",
585
+ themeMidnight: "Night",
521
586
  themeTwilight: "Twilight",
522
587
  themeContrast: "High contrast",
523
588
  themeSystem: "System",
@@ -647,6 +712,10 @@ export const DEFAULT_STRINGS: TerpStrings = {
647
712
  errorCodeNotFound: "This item could not be found.",
648
713
  errorCodeConflict: "This conflicts with the current state. Refresh and try again.",
649
714
  errorCodeStaleData: "This item was changed by someone else. Refresh and try again.",
715
+ errorCodeRateLimited: "Too many requests at once. Wait a moment and try again.",
716
+ errorCodeRequestTooLarge: "This is too large to send. Make it smaller and try again.",
717
+ errorCodeInternalError: "Something went wrong on the server. Try again in a moment.",
718
+ errorCodeStillProcessing: "This is still being processed. Wait a moment, then check again.",
650
719
  };
651
720
 
652
721
  interface UiTextContextValue {