@terpjs/react-core 0.29.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 +215 -1
  8. package/src/Page.tsx +145 -54
  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 +252 -176
  61. package/src/styles.ts +1290 -318
  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 +16 -18
  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
@@ -0,0 +1,341 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, render, screen } from "@testing-library/react";
3
+ import type { ReactNode } from "react";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+
6
+ // The pairings the contrast gate measures, read from the contract package that owns them.
7
+ import tokenPairs from "../../contract/token-pairs.json";
8
+ import { HubCard, HubPage } from "./HubPage";
9
+ import { LOCALE_EN, LOCALE_NL, LocaleProvider } from "./locale";
10
+ import { Stat, StatGroup } from "./Stat";
11
+ import { TERP_STYLES_CSS } from "./styles";
12
+
13
+ afterEach(() => {
14
+ cleanup();
15
+ window.localStorage.clear();
16
+ });
17
+
18
+ /** Render under a fixed app locale, so a formatting assertion never depends on the runner's. */
19
+ function renderIn(locale: "nl" | "en", node: ReactNode) {
20
+ return render(
21
+ <LocaleProvider locales={{ nl: LOCALE_NL, en: LOCALE_EN }} defaultLocale={locale}>
22
+ {node}
23
+ </LocaleProvider>,
24
+ );
25
+ }
26
+
27
+ const part = (marker: string) => document.querySelector(`[data-terp="${marker}"]`);
28
+
29
+ describe("Stat's figure", () => {
30
+ it("prints its label and a numeric value in the app's locale", () => {
31
+ renderIn("nl", <Stat label="Open orders" value={1284.5} />);
32
+ expect(part("stat-label")!.textContent).toBe("Open orders");
33
+ expect(part("stat-value")!.textContent).toBe("1.284,5");
34
+ cleanup();
35
+ renderIn("en", <Stat label="Open orders" value={1284.5} />);
36
+ expect(part("stat-value")!.textContent).toBe("1,284.5");
37
+ });
38
+
39
+ it("formats with the options it is given", () => {
40
+ renderIn("en", <Stat label="Spend" value={842} format={{ style: "currency", currency: "EUR" }} />);
41
+ expect(part("stat-value")!.textContent).toBe("€842.00");
42
+ });
43
+
44
+ it("prints a string as written, and the dash for a figure not known yet", () => {
45
+ renderIn("en", <Stat label="Uptime" value="3 d 4 h" />);
46
+ expect(part("stat-value")!.textContent).toBe("3 d 4 h");
47
+ cleanup();
48
+ for (const value of [null, undefined, ""] as const) {
49
+ renderIn("en", <Stat label="Uptime" value={value} />);
50
+ expect(part("stat-value")!.textContent).toBe("—");
51
+ cleanup();
52
+ }
53
+ });
54
+
55
+ it("stamps the headline only when asked", () => {
56
+ // The page frame counts [data-terp="stat"][data-headline]; a stamp on every figure would
57
+ // make every page with two figures fail closed.
58
+ renderIn("en", <Stat label="Revenue" value={1} />);
59
+ expect(part("stat")).not.toHaveAttribute("data-headline");
60
+ cleanup();
61
+ renderIn("en", <Stat label="Revenue" value={1} headline />);
62
+ expect(part("stat")).toHaveAttribute("data-headline", "true");
63
+ });
64
+
65
+ it("prints a caption, and renders no empty line for an absent one", () => {
66
+ renderIn("en", <Stat label="Spend" value={842} caption="of 1,200 budgeted" />);
67
+ expect(part("stat-caption")!.textContent).toBe("of 1,200 budgeted");
68
+ cleanup();
69
+ for (const caption of [undefined, null, false, ""] as const) {
70
+ renderIn("en", <Stat label="Spend" value={842} caption={caption} />);
71
+ expect(part("stat-caption")).toBeNull();
72
+ cleanup();
73
+ }
74
+ });
75
+ });
76
+
77
+ describe("Stat's delta", () => {
78
+ it("prints the change with its sign, in the change's own format", () => {
79
+ renderIn("en", (
80
+ <Stat
81
+ label="Orders"
82
+ value={1284}
83
+ delta={{ value: 0.12, sentiment: "positive", format: { style: "percent" } }}
84
+ />
85
+ ));
86
+ // The sign is printed even when the caller's format says nothing about it.
87
+ expect(part("stat-change")!.textContent).toBe("+12% favourable");
88
+ cleanup();
89
+ renderIn("en", <Stat label="Orders" value={1284} delta={{ value: -3, sentiment: "negative" }} />);
90
+ expect(part("stat-change")!.textContent).toBe("-3 unfavourable");
91
+ });
92
+
93
+ it("colours by the declared sentiment, never by the sign", () => {
94
+ // More rejections is up and bad: the caller says so, and the pill follows the caller.
95
+ renderIn("en", (
96
+ <Stat label="Rejections" value={40} delta={{ value: 6, sentiment: "negative" }} />
97
+ ));
98
+ expect(part("stat-change")).toHaveAttribute("data-sentiment", "negative");
99
+ expect(part("stat-arrow")!.querySelector("path")!.getAttribute("d")).toBe("M6 2 L11 10 L1 10 Z");
100
+ });
101
+
102
+ it("points the arrow by the sign, and draws a bar for no change", () => {
103
+ const arrows: Record<string, string> = {};
104
+ for (const [name, value] of [["up", 2], ["down", -2], ["flat", 0]] as const) {
105
+ renderIn("en", <Stat label="Runs" value={9} delta={{ value, sentiment: "neutral" }} />);
106
+ arrows[name] = part("stat-arrow")!.querySelector("path")!.getAttribute("d")!;
107
+ cleanup();
108
+ }
109
+ expect(new Set(Object.values(arrows)).size).toBe(3);
110
+ expect(arrows.flat).toBe("M1 5 H11 V7 H1 Z");
111
+ });
112
+
113
+ it("says the sentiment as a word, and says nothing for a neutral change", () => {
114
+ // A tone is always also a word (ADR 0169 §7): the pill's colour is read out after the
115
+ // change. Mutation: drop the word, and a screen reader hears "+12%" with no judgement.
116
+ renderIn("nl", (
117
+ <Stat label="Orders" value={1284} delta={{ value: 12, sentiment: "positive" }} />
118
+ ));
119
+ expect(part("stat-sentiment")!.textContent).toBe(" gunstig");
120
+ cleanup();
121
+ renderIn("nl", <Stat label="Orders" value={1284} delta={{ value: 12, sentiment: "negative" }} />);
122
+ expect(part("stat-sentiment")!.textContent).toBe(" ongunstig");
123
+ cleanup();
124
+ renderIn("nl", <Stat label="Orders" value={1284} delta={{ value: 12, sentiment: "neutral" }} />);
125
+ expect(part("stat-sentiment")).toBeNull();
126
+ });
127
+
128
+ it("follows the change as it prints: a change that rounds to zero is no change", () => {
129
+ // 0.004 as a whole percentage prints "0%"; an up arrow, a green pill and "favourable" beside
130
+ // "0%" contradicted the number they decorate. Mutation: take the direction from the raw
131
+ // value again, and the arrow points up.
132
+ renderIn("en", (
133
+ <Stat
134
+ label="Orders"
135
+ value={1}
136
+ delta={{ value: 0.004, sentiment: "positive", format: { style: "percent" } }}
137
+ />
138
+ ));
139
+ expect(part("stat-change")!.textContent).toBe("0%");
140
+ expect(part("stat-change")).toHaveAttribute("data-sentiment", "neutral");
141
+ expect(part("stat-arrow")!.querySelector("path")!.getAttribute("d")).toBe("M1 5 H11 V7 H1 Z");
142
+ });
143
+
144
+ it("keeps the sign over a format that asks to hide it", () => {
145
+ // Mutation: spread the caller's format last, and "never" wins.
146
+ renderIn("en", (
147
+ <Stat label="Orders" value={1} delta={{ value: 5, sentiment: "positive", format: { signDisplay: "never" } }} />
148
+ ));
149
+ expect(part("stat-change")!.textContent).toBe("+5 favourable");
150
+ });
151
+
152
+ it("hides the arrow from assistive technology, which hears the sign instead", () => {
153
+ renderIn("en", <Stat label="Orders" value={1} delta={{ value: 1, sentiment: "positive" }} />);
154
+ expect(part("stat-arrow")).toHaveAttribute("aria-hidden", "true");
155
+ });
156
+
157
+ it("prints what the change is measured against", () => {
158
+ renderIn("en", (
159
+ <Stat
160
+ label="Orders"
161
+ value={1284}
162
+ delta={{ value: 12, sentiment: "positive", label: "vs last week" }}
163
+ />
164
+ ));
165
+ expect(part("stat-delta-label")!.textContent).toBe("vs last week");
166
+ });
167
+ });
168
+
169
+ describe("Stat's trend", () => {
170
+ const WEEK = [
171
+ { label: "Mon", value: 10 },
172
+ { label: "Tue", value: 30 },
173
+ { label: "Wed", value: 20 },
174
+ ];
175
+
176
+ it("draws the series as SVG geometry, highest at the top", () => {
177
+ renderIn("en", <Stat label="Runs" value={20} trend={WEEK} />);
178
+ const line = part("stat-trend-line")!;
179
+ // x spreads the points across 100, y maps 10..30 onto 22..2 (the canvas less its inset).
180
+ expect(line.getAttribute("points")).toBe("0,22 50,2 100,12");
181
+ expect(part("stat-trend-area")!.getAttribute("points")).toBe("0,24 0,22 50,2 100,12 100,24");
182
+ expect(part("stat-trend-chart")).toHaveAttribute("aria-hidden", "true");
183
+ // Geometry, not style: nothing here is an inline style (ADR 0169 §7).
184
+ expect(part("stat")!.querySelector("[style]")).toBeNull();
185
+ });
186
+
187
+ it("draws a flat series through the middle rather than along the floor", () => {
188
+ renderIn("en", <Stat label="Runs" value={5} trend={[{ label: "a", value: 5 }, { label: "b", value: 5 }]} />);
189
+ expect(part("stat-trend-line")!.getAttribute("points")).toBe("0,12 100,12");
190
+ });
191
+
192
+ it("reads every point out, label and value, in the app's locale", () => {
193
+ // ADR 0158's data alternative, as text because a figure is phrasing content throughout.
194
+ // Mutation: drop the text, and the sparkline is a picture with nothing behind it.
195
+ renderIn("nl", (
196
+ <Stat
197
+ label="Omzet"
198
+ value={1500}
199
+ trend={[{ label: "jan", value: 1200.5 }, { label: "feb", value: 1500 }]}
200
+ />
201
+ ));
202
+ expect(part("stat-trend-data")!.textContent).toBe("Verloop: jan: 1.200,5 en feb: 1.500");
203
+ });
204
+
205
+ it("reads a series out as a sentence in English too, each point's label set off from its value", () => {
206
+ // Intl's narrow unit list joins English with bare spaces, so "Mon 10 Tue 30 Wed 20" read as
207
+ // one run of words and numbers. Mutation: go back to the narrow unit list, and this fails.
208
+ renderIn("en", <Stat label="Runs" value={20} trend={WEEK} />);
209
+ expect(part("stat-trend-data")!.textContent).toBe("Over time: Mon: 10, Tue: 30, and Wed: 20");
210
+ });
211
+
212
+ it("reads out a single point without drawing a line, or a block, for it", () => {
213
+ // As the only child of the trend's own block, the hidden text left that block's margin
214
+ // behind as an empty line. Mutation: keep the block for one point, and it is found.
215
+ renderIn("en", <Stat label="Runs" value={5} trend={[{ label: "Mon", value: 5 }]} />);
216
+ expect(part("stat-trend-chart")).toBeNull();
217
+ expect(part("stat-trend")).toBeNull();
218
+ expect(part("stat-trend-data")!.textContent).toBe("Over time: Mon: 5");
219
+ });
220
+
221
+ it("draws only the points that are numbers, and prints the dash for one that is not", () => {
222
+ // A NaN in the points attribute is a console error and no line at all.
223
+ // Mutation: draw every value, and the points carry a NaN.
224
+ renderIn("en", (
225
+ <Stat
226
+ label="Runs"
227
+ value={3}
228
+ trend={[
229
+ { label: "a", value: 1 },
230
+ { label: "b", value: Number.NaN },
231
+ { label: "c", value: 3 },
232
+ ]}
233
+ />
234
+ ));
235
+ expect(part("stat-trend-line")!.getAttribute("points")).toBe("0,22 100,2");
236
+ expect(part("stat-trend-data")!.textContent).toBe("Over time: a: 1, b: —, and c: 3");
237
+ });
238
+
239
+ it("renders no trend at all for an empty series", () => {
240
+ renderIn("en", <Stat label="Runs" value={5} trend={[]} />);
241
+ expect(part("stat-trend")).toBeNull();
242
+ });
243
+ });
244
+
245
+ describe("Stat's target", () => {
246
+ it("draws the figure against its range as a Meter named by the figure's label", () => {
247
+ renderIn("en", <Stat label="Spend" value={600} target={{ max: 1200, high: 1000, optimum: 0 }} />);
248
+ expect(screen.getByRole("meter", { name: "Spend" })).toHaveAttribute("aria-valuetext", "50%");
249
+ });
250
+
251
+ it("draws no meter for a figure that is not a number", () => {
252
+ renderIn("en", <Stat label="Spend" value={null} target={{ max: 1200 }} />);
253
+ expect(screen.queryByRole("meter")).toBeNull();
254
+ });
255
+ });
256
+
257
+ describe("Stat as phrasing content", () => {
258
+ it("renders only phrasing elements, so it is valid inside a HubCard's link", () => {
259
+ // A HubCard is one link whose body is spans; a block element inside it is invalid HTML.
260
+ // Mutation: render the root as a div, and this fails.
261
+ renderIn("en", (
262
+ <Stat
263
+ label="Spend"
264
+ value={600}
265
+ delta={{ value: 1, sentiment: "positive", label: "vs last week" }}
266
+ trend={[{ label: "a", value: 1 }, { label: "b", value: 2 }]}
267
+ target={{ max: 1200 }}
268
+ caption="of 1,200"
269
+ />
270
+ ));
271
+ const PHRASING = new Set(["span", "svg", "path", "polyline", "polygon", "meter"]);
272
+ const tags = [part("stat")!, ...part("stat")!.querySelectorAll("*")].map((element) =>
273
+ element.tagName.toLowerCase(),
274
+ );
275
+ expect(tags.filter((tag) => !PHRASING.has(tag))).toEqual([]);
276
+ });
277
+
278
+ it("sits in a HubCard's stat row and names the card's link with the figure", () => {
279
+ renderIn("en", (
280
+ <HubPage title="Admin">
281
+ <HubCard to="/users" title="Users" stat={<Stat label="Total" value={1420} />} />
282
+ </HubPage>
283
+ ));
284
+ expect(screen.getByRole("link").textContent).toContain("Total1,420");
285
+ });
286
+ });
287
+
288
+ describe("StatGroup", () => {
289
+ it("renders its figures in one group", () => {
290
+ renderIn("en", (
291
+ <StatGroup>
292
+ <Stat label="A" value={1} />
293
+ <Stat label="B" value={2} />
294
+ </StatGroup>
295
+ ));
296
+ expect(part("stat-group")!.querySelectorAll(':scope > [data-terp="stat"]')).toHaveLength(2);
297
+ });
298
+ });
299
+
300
+ describe("Stat's colours are declared pairings", () => {
301
+ /** The declarations of the one rule whose selector is exactly *selector*. */
302
+ function rule(selector: string): string {
303
+ const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
304
+ const match = new RegExp(`(?:^|\\n)${escaped} \\{([^}]*)\\}`).exec(TERP_STYLES_CSS);
305
+ expect(match, `no rule for ${selector}`).not.toBeNull();
306
+ return match![1]!;
307
+ }
308
+ const declared = (fg: string, bg: string) =>
309
+ [...tokenPairs.textPairs, ...tokenPairs.nonTextPairs].some(
310
+ (pair) => "fg" in pair && pair.fg === fg && pair.bg === bg,
311
+ );
312
+
313
+ it("draws each delta pill in a pairing the contrast gate holds", () => {
314
+ // The pill carries its own fill so its contrast travels with it onto a band, a card or the
315
+ // headline. Mutation: colour the positive pill's ink with the accent, and no pairing
316
+ // holds it.
317
+ for (const sentiment of ["positive", "negative", "neutral"]) {
318
+ const body = rule(`[data-terp="stat-change"][data-sentiment="${sentiment}"]`);
319
+ const fg = /(?<![-\w])color: var\((--[a-z0-9-]+)\)/.exec(body)![1]!;
320
+ const bg = /(?<![-\w])background: var\((--[a-z0-9-]+)\)/.exec(body)![1]!;
321
+ expect(declared(fg, bg), `${sentiment}: ${fg} on ${bg}`).toBe(true);
322
+ }
323
+ });
324
+
325
+ it("fills the headline with the brand and its contrast ink, the primary button's pairing", () => {
326
+ const body = rule('[data-terp="stat"][data-headline]');
327
+ const fg = /(?<![-\w])color: var\((--[a-z0-9-]+)\)/.exec(body)![1]!;
328
+ const bg = /(?<![-\w])background: var\((--[a-z0-9-]+)\)/.exec(body)![1]!;
329
+ expect(declared(fg, bg)).toBe(true);
330
+ });
331
+
332
+ it("writes the summary band's text in inks declared against its fill", () => {
333
+ const body = rule('[data-terp="page-summary"]');
334
+ const bg = /(?<![-\w])background: var\((--[a-z0-9-]+)\)/.exec(body)![1]!;
335
+ expect(bg).toBe("--color-bg-summary");
336
+ // The band's own ink, and the two a figure writes on it.
337
+ for (const fg of ["--color-fg-default", "--color-fg-muted", "--color-fg-accent"]) {
338
+ expect(declared(fg, bg), `${fg} on ${bg}`).toBe(true);
339
+ }
340
+ });
341
+ });
package/src/Stat.tsx ADDED
@@ -0,0 +1,314 @@
1
+ import { useContext, useEffect } from "react";
2
+ import type { ReactNode } from "react";
3
+
4
+ import { formatList, useFormatNumber } from "./format";
5
+ import { HeadlineContext } from "./layoutContract";
6
+ import { useLocale } from "./locale";
7
+ import { Meter } from "./Meter";
8
+ import type { MeterProps } from "./Meter";
9
+ import { injectTerpStyles } from "./styles";
10
+ import { fillPlaceholders, resolveUiTextNode, useStrings, useUiText } from "./uiText";
11
+ import type { UiText, UiTextNode } from "./uiText";
12
+
13
+ injectTerpStyles();
14
+
15
+ /**
16
+ * Whether a change is good news, bad news, or neither.
17
+ *
18
+ * The caller's fact, never inferred (ADR 0169 §5): more rows synced is good and more deliveries
19
+ * failed is bad, and only the module that owns the number knows which — the reason ADR 0097 §5
20
+ * gave for refusing a navigation badge a tone of its own.
21
+ */
22
+ export type StatSentiment = "positive" | "negative" | "neutral";
23
+
24
+ /** A figure's change against an earlier value of itself. */
25
+ export interface StatDelta {
26
+ /** The change. Its sign is the arrow's direction, and zero reads as unchanged. */
27
+ value: number;
28
+ /** Whether the change is good news, bad news or neither — see {@link StatSentiment}. */
29
+ sentiment: StatSentiment;
30
+ /**
31
+ * How the change prints, as the `Intl.NumberFormatOptions` the `format` helpers take
32
+ * (default: a plain number). It always carries its sign, so `{ style: "percent" }` with
33
+ * `0.12` prints `+12%`; a `signDisplay` of the caller's own is overridden to keep it.
34
+ *
35
+ * The printed change is what the arrow and the tone follow: a change that rounds to zero in
36
+ * this format prints `0`, draws the bar for no change and reads as neutral, whatever its
37
+ * declared sentiment, because there is no change left to judge.
38
+ */
39
+ format?: Intl.NumberFormatOptions;
40
+ /**
41
+ * What the change is measured against — "vs last week", "since the previous run". `label`
42
+ * rather than a name of its own, so the i18n lint reads it as copy wherever it is written.
43
+ */
44
+ label?: UiText;
45
+ }
46
+
47
+ /** One point of a figure's recent history: when, and how much. */
48
+ export interface StatPoint {
49
+ /** When — a period's name or a formatted date. Read out in the trend's text alternative. */
50
+ label: UiText;
51
+ /** How much, in the figure's own format. */
52
+ value: number;
53
+ }
54
+
55
+ /** The range a figure is read against: `Meter`'s range and bands, with the top required. */
56
+ export type StatTarget = Omit<MeterProps, "value" | "label" | "max"> & {
57
+ /** The top of the range — the budget, the quota, the goal. */
58
+ max: number;
59
+ };
60
+
61
+ export interface StatProps {
62
+ /** What the figure is ("Open orders"). Printed above the value, and the target meter's name. */
63
+ label: UiText;
64
+ /**
65
+ * The figure. A number prints through the `format` helpers in the app's locale; a string
66
+ * prints as written, for a figure that is not a quantity ("3 d 4 h", "A+"); `null` or
67
+ * `undefined` prints the framework's dash, for a figure not known yet.
68
+ */
69
+ value: number | string | null | undefined;
70
+ /** How a numeric value prints, as `Intl.NumberFormatOptions` (default: a plain number). */
71
+ format?: Intl.NumberFormatOptions;
72
+ /** The change against an earlier value, as a pill whose tone is the declared sentiment. */
73
+ delta?: StatDelta;
74
+ /**
75
+ * The figure's recent history, oldest first, drawn as a sparkline under the value — ADR
76
+ * 0158's sparkline, the first chart kind. Two points or more draw a line; every point is
77
+ * also read out as text, which is the sparkline's data alternative.
78
+ */
79
+ trend?: readonly StatPoint[];
80
+ /**
81
+ * The range the figure is read against, drawn as a `Meter` under the value: a spend against
82
+ * its budget, a count against the minimum it must reach. Declare `low`, `high` and
83
+ * `optimum` for the bands, as on `Meter`. Ignored unless the value is a number.
84
+ */
85
+ target?: StatTarget;
86
+ /** One short line under the figure — "of 1,200 budgeted", "last run 4 minutes ago". */
87
+ caption?: UiTextNode;
88
+ /**
89
+ * The page's headline figure: filled with the brand colour, the loudest thing on the page.
90
+ *
91
+ * At most one figure on a page is the headline — scarcity is what lets the accent mean
92
+ * something (ADR 0169 §4) — and under a layout contract both halves refuse a second one.
93
+ */
94
+ headline?: boolean;
95
+ }
96
+
97
+ const DASH = "—";
98
+
99
+ /** The delta's sign rule, applied last over the caller's format so the sign always shows. */
100
+ const SIGNED: Intl.NumberFormatOptions = { signDisplay: "exceptZero" };
101
+
102
+ // The arrow, as geometry: a triangle up, one down, and a bar for no change. Paths rather than
103
+ // glyphs, so the mark is the same in every font and its colour is the pill's.
104
+ const ARROWS = {
105
+ up: "M6 2 L11 10 L1 10 Z",
106
+ down: "M6 10 L1 2 L11 2 Z",
107
+ flat: "M1 5 H11 V7 H1 Z",
108
+ } as const;
109
+
110
+ // The sparkline's canvas. The SVG is stretched to its box (preserveAspectRatio="none"), so these
111
+ // are proportions rather than pixels; the stroke keeps its width through the stretch because
112
+ // the sheet gives it vector-effect: non-scaling-stroke.
113
+ const TREND_WIDTH = 100;
114
+ const TREND_HEIGHT = 24;
115
+ const TREND_INSET = 2;
116
+
117
+ /**
118
+ * Which way a change points, read from the change as it prints rather than as it was passed:
119
+ * `0.004` as a percentage prints `0%`, and an up arrow beside `0%` would contradict itself.
120
+ * The sign is a part of its own in `formatToParts`, so this holds in every locale's spelling.
121
+ */
122
+ function directionOf(
123
+ value: number,
124
+ format: Intl.NumberFormatOptions,
125
+ locale: string | undefined,
126
+ ): "up" | "down" | "flat" {
127
+ const parts = new Intl.NumberFormat(locale, format).formatToParts(value);
128
+ return parts.some((part) => part.type === "plusSign")
129
+ ? "up"
130
+ : parts.some((part) => part.type === "minusSign")
131
+ ? "down"
132
+ : "flat";
133
+ }
134
+
135
+ /** The sparkline's points, scaled to its canvas: x by position, y by value, top is highest. */
136
+ function trendPoints(values: readonly number[]): string {
137
+ const low = Math.min(...values);
138
+ const high = Math.max(...values);
139
+ const span = high - low;
140
+ const step = TREND_WIDTH / (values.length - 1);
141
+ return values
142
+ .map((value, index) => {
143
+ // A flat series is a line through the middle, not a line along the floor.
144
+ const share = span === 0 ? 0.5 : (value - low) / span;
145
+ const y = TREND_HEIGHT - TREND_INSET - share * (TREND_HEIGHT - 2 * TREND_INSET);
146
+ return `${round(index * step)},${round(y)}`;
147
+ })
148
+ .join(" ");
149
+ }
150
+
151
+ const round = (value: number) => Math.round(value * 100) / 100;
152
+
153
+ /**
154
+ * One figure, with what it needs to be read: its label, its value in the app's locale, how it
155
+ * changed, its recent history, and the range it sits in.
156
+ *
157
+ * The shape of data ADR 0169 calls "one figure, with context". A `Card` with a title and a line
158
+ * of text was the way to show one, and it put the label above the number in a larger type than
159
+ * the number — the figure was the quietest thing in its own box. Here the value is the largest
160
+ * type on the tile, and the label names it.
161
+ *
162
+ * **Where it sits.** On its own, a figure is a tile on `--color-bg-surface`, the rung where data
163
+ * is read (ADR 0169 §3). Several figures about one subject are a {@link StatGroup}, which draws
164
+ * them as one ruled row without a tile each. In a `HubCard`'s `stat` row the card is the frame,
165
+ * so the figure has none of its own. The `headline` figure is filled with the brand colour.
166
+ *
167
+ * **A tone is also a word.** The delta's pill is coloured by the declared sentiment and carries
168
+ * its sign, so every reader sees the direction; the sentiment itself is a word in the
169
+ * accessibility tree ("favourable", "unfavourable"), because a colour alone says it to nobody
170
+ * who cannot see the colour. The sparkline is drawn for the eye and read out as text — each
171
+ * point's label and value — which is ADR 0158's data alternative in the one form valid inside a
172
+ * `HubCard`'s link: a figure is phrasing content throughout, so a table cannot be.
173
+ *
174
+ * It renders no inline styles: the sparkline is SVG geometry in attributes, and every colour
175
+ * comes from the sheet, keyed on the markers and on `data-sentiment` (ADR 0094, ADR 0169 §7).
176
+ *
177
+ * ```tsx
178
+ * <Stat
179
+ * label={{ id: "orders.open", message: "Open orders" }}
180
+ * value={1284}
181
+ * delta={{ value: 0.12, format: { style: "percent" }, sentiment: "positive", label: { id: "orders.vsLastWeek", message: "vs last week" } }}
182
+ * trend={weeks.map((week) => ({ label: week.name, value: week.open }))}
183
+ * />
184
+ * ```
185
+ */
186
+ export function Stat({
187
+ label,
188
+ value,
189
+ format,
190
+ delta,
191
+ trend,
192
+ target,
193
+ caption,
194
+ headline = false,
195
+ }: StatProps) {
196
+ const resolve = useUiText();
197
+ const strings = useStrings();
198
+ const formatNumber = useFormatNumber();
199
+ const locale = useLocale()?.locale;
200
+ // A headline registers with its page, which counts them (ADR 0169 §4): a figure that
201
+ // renders late -- after its own data arrives -- is counted when it arrives, where a DOM count
202
+ // taken when the page rendered would have missed it.
203
+ const headlines = useContext(HeadlineContext);
204
+ useEffect(
205
+ () => (headline && headlines !== null ? headlines.register() : undefined),
206
+ [headline, headlines],
207
+ );
208
+ const printed =
209
+ typeof value === "number"
210
+ ? formatNumber(value, format)
211
+ : typeof value === "string" && value !== ""
212
+ ? value
213
+ : DASH;
214
+ const deltaFormat =
215
+ delta === undefined ? SIGNED : { ...(delta.format ?? {}), ...SIGNED };
216
+ const direction =
217
+ delta === undefined || !Number.isFinite(delta.value)
218
+ ? undefined
219
+ : directionOf(delta.value, deltaFormat, locale);
220
+ // No change left to judge is neutral, whatever was declared for the change.
221
+ const sentiment = direction === "flat" ? "neutral" : delta?.sentiment;
222
+ const sentimentWord =
223
+ sentiment === "positive"
224
+ ? strings.statFavourable
225
+ : sentiment === "negative"
226
+ ? strings.statUnfavourable
227
+ : undefined;
228
+ const points = trend ?? [];
229
+ // The text alternative names every point, label and value, in the order drawn and joined the
230
+ // way the app's locale joins a list ("a, b and c"), so it reads as a sentence in every
231
+ // language. A value that is not a number prints the dash here and draws nothing below.
232
+ const trendText =
233
+ points.length === 0
234
+ ? undefined
235
+ : fillPlaceholders(strings.statTrend, {
236
+ points: formatList(
237
+ points.map((point) => `${resolve(point.label)}: ${formatNumber(point.value, format)}`),
238
+ locale,
239
+ ),
240
+ });
241
+ const drawable = points.map((point) => point.value).filter((value) => Number.isFinite(value));
242
+ const line = drawable.length >= 2 ? trendPoints(drawable) : undefined;
243
+ const showsTarget = target !== undefined && typeof value === "number" && Number.isFinite(value);
244
+ return (
245
+ <span data-terp="stat" data-headline={headline ? "true" : undefined}>
246
+ <span data-terp="stat-label">{resolve(label)}</span>
247
+ <span data-terp="stat-value">{printed}</span>
248
+ {delta !== undefined && direction !== undefined && (
249
+ <span data-terp="stat-delta">
250
+ <span data-terp="stat-change" data-sentiment={sentiment}>
251
+ <svg data-terp="stat-arrow" viewBox="0 0 12 12" aria-hidden="true" focusable="false">
252
+ <path d={ARROWS[direction]} />
253
+ </svg>
254
+ {formatNumber(delta.value, deltaFormat)}
255
+ {sentimentWord !== undefined && (
256
+ <span data-terp="stat-sentiment">{` ${sentimentWord}`}</span>
257
+ )}
258
+ </span>
259
+ {delta.label !== undefined && (
260
+ <span data-terp="stat-delta-label">{resolve(delta.label)}</span>
261
+ )}
262
+ </span>
263
+ )}
264
+ {/* The series' text, alone when there is no line to draw: as the only child of a block
265
+ of its own it left an empty block the height of the block's margin. */}
266
+ {trendText !== undefined && line === undefined && (
267
+ <span data-terp="stat-trend-data">{trendText}</span>
268
+ )}
269
+ {trendText !== undefined && line !== undefined && (
270
+ <span data-terp="stat-trend">
271
+ <svg
272
+ data-terp="stat-trend-chart"
273
+ viewBox={`0 0 ${TREND_WIDTH} ${TREND_HEIGHT}`}
274
+ preserveAspectRatio="none"
275
+ aria-hidden="true"
276
+ focusable="false"
277
+ >
278
+ <polygon
279
+ data-terp="stat-trend-area"
280
+ points={`0,${TREND_HEIGHT} ${line} ${TREND_WIDTH},${TREND_HEIGHT}`}
281
+ />
282
+ <polyline data-terp="stat-trend-line" points={line} />
283
+ </svg>
284
+ <span data-terp="stat-trend-data">{trendText}</span>
285
+ </span>
286
+ )}
287
+ {showsTarget && <Meter label={label} value={value} {...target} />}
288
+ {caption !== undefined && caption !== null && caption !== false && caption !== "" && (
289
+ <span data-terp="stat-caption">{resolveUiTextNode(caption, resolve)}</span>
290
+ )}
291
+ </span>
292
+ );
293
+ }
294
+
295
+ export interface StatGroupProps {
296
+ /** The figures: `Stat`s, one of which may be the page's headline. */
297
+ children: ReactNode;
298
+ }
299
+
300
+ /**
301
+ * Several figures about one subject, as one ruled row: the shape ADR 0169 calls "a group of
302
+ * figures", and the usual content of a page's `summary` band.
303
+ *
304
+ * Unframed, always — the figures sit on whatever the group sits on, divided by hairline rules
305
+ * rather than boxed one by one, so a row of four figures reads as one statement about the
306
+ * subject rather than four tiles. It is the same row in the summary band and in a body; nothing
307
+ * about it changes with where it is placed.
308
+ *
309
+ * The row wraps by itself, as many figures to a line as fit at 8rem (two on a phone), and a
310
+ * figure that starts a line carries no rule before it.
311
+ */
312
+ export function StatGroup({ children }: StatGroupProps) {
313
+ return <span data-terp="stat-group">{children}</span>;
314
+ }