@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
@@ -174,15 +174,15 @@ describe("renderTerpApp", () => {
174
174
  // on <html> is the actual observable effect an app ships. A throw here would only prove the
175
175
  // file was validated, not that the value reached anything.
176
176
  //
177
- // Mutations, both red, and both by reading NULL rather than "midnight": `"system"` is the
177
+ // Mutations, both red, and both by reading NULL rather than "night": `"system"` is the
178
178
  // provider's default and it REMOVES the attribute, so neither mutation can produce the
179
179
  // string. (An earlier version of this comment said the first one reads "system", which is
180
180
  // not a value `data-theme` ever holds.) Pass `options.defaultTheme` to `ThemeProvider`
181
181
  // instead of `layout.defaultTheme`, or drop `defaultTheme` from the explicit set handed to
182
182
  // the resolver, and the corresponding assertion reads null.
183
183
  for (const [label, options] of [
184
- ["from the file", { layout: { defaultTheme: "midnight" } }],
185
- ["from the option", { defaultTheme: "midnight" as const }],
184
+ ["from the file", { layout: { defaultTheme: "night" } }],
185
+ ["from the option", { defaultTheme: "night" as const }],
186
186
  ] as const) {
187
187
  // A stored choice outranks the default — that is the whole point of a *default* — so the
188
188
  // assertion would be about localStorage rather than about the declaration without this.
@@ -201,7 +201,7 @@ describe("renderTerpApp", () => {
201
201
  expect(
202
202
  document.documentElement.getAttribute("data-theme"),
203
203
  `${label}: the declared palette must reach <html>`,
204
- ).toBe("midnight"),
204
+ ).toBe("night"),
205
205
  );
206
206
  } finally {
207
207
  root.remove();
@@ -221,16 +221,40 @@ describe("renderTerpApp", () => {
221
221
  renderTerpApp({
222
222
  title: "Test",
223
223
  modules: { "./modules/notes/module.tsx": notesModule },
224
- layout: { defaultTheme: "midnight" },
225
- defaultTheme: "midnight",
224
+ layout: { defaultTheme: "night" },
225
+ defaultTheme: "night",
226
226
  rootElement: root,
227
227
  }),
228
- ).toThrow(/both declare "defaultTheme" \(file: "midnight", code: "midnight"\)/);
228
+ ).toThrow(/both declare "defaultTheme" \(file: "night", code: "night"\)/);
229
229
  } finally {
230
230
  root.remove();
231
231
  }
232
232
  });
233
233
 
234
+ it("refuses a palette passed as an option that names no theme", () => {
235
+ // Resolved to undefined, an unknown name was dropped twice over: the app opened on another
236
+ // palette, and a palette also declared in the file was no longer reported as declared in
237
+ // both places. Refused now in the resolver's own words, as the file's is.
238
+ // Mutation: resolve it with `?? undefined` again, and both calls return quietly.
239
+ for (const layout of [undefined, { defaultTheme: "night" }] as const) {
240
+ const root = document.createElement("div");
241
+ document.body.appendChild(root);
242
+ try {
243
+ expect(() =>
244
+ renderTerpApp({
245
+ title: "Test",
246
+ modules: { "./modules/notes/module.tsx": notesModule },
247
+ layout,
248
+ defaultTheme: "midnite" as never,
249
+ rootElement: root,
250
+ }),
251
+ ).toThrow(/renderTerpApp: "defaultTheme" is "midnite"; expected one of "midday"/);
252
+ } finally {
253
+ root.remove();
254
+ }
255
+ }
256
+ });
257
+
234
258
  it("names every doubly-declared key at once, groups included", async () => {
235
259
  // The property the resolver's `conflicts.join("; ")` exists for, asserted through the entry
236
260
  // point apps use — and it was broken here. `renderTerpApp` resolves the declaration itself
package/src/bootstrap.tsx CHANGED
@@ -20,7 +20,8 @@ import type { LocaleCatalog } from "./locale";
20
20
  import { buildAppRouter } from "./router";
21
21
  import type { SsoProvider } from "./sso";
22
22
  import { ThemeProvider } from "./theme";
23
- import type { Theme } from "./theme";
23
+ import type { LegacyTheme, Theme } from "./theme";
24
+ import { THEME_ALIASES, THEMES, resolveTheme } from "./themes";
24
25
  import { ToastProvider } from "./toast";
25
26
 
26
27
  /** A frontend module: its stack-agnostic manifest and the view components it names. */
@@ -225,8 +226,11 @@ export interface RenderTerpAppOptions {
225
226
  * `frontend/layout-contract.json` says the same thing in the one document a tool can read and
226
227
  * rewrite, which is the whole reason the declaration exists. Declaring it in both places is
227
228
  * refused rather than silently resolved.
229
+ *
230
+ * Today's name, or a name the theme had before the rename ({@link LegacyTheme}), which
231
+ * resolves to it.
228
232
  */
229
- defaultTheme?: Theme;
233
+ defaultTheme?: Theme | LegacyTheme;
230
234
  /**
231
235
  * Opt into a slot-typed layout contract (ADR 0079), e.g. `"standard"`: every routed
232
236
  * archetype's body slot then accepts only the components the contract allows there,
@@ -302,7 +306,7 @@ export function withAdminArea(
302
306
  return { manifests, views };
303
307
  }
304
308
  const merged = { ...views };
305
- const allSections = sections.users && sections.groups && sections.audit;
309
+ const allSections = sections.users && sections.groups && sections.audit && sections.access;
306
310
  for (const route of routes) {
307
311
  if (route.view === "TerpAdminHub" && !allSections) {
308
312
  // The hub mirrors the selection: one card per kept section (and no stat
@@ -334,6 +338,28 @@ export function withAdminArea(
334
338
  * the provider + auth gate + shell. A consumer's `main.tsx` is just this plus the token
335
339
  * stylesheet import. Drop to `TerpProvider` + `buildAppRouter` for full control.
336
340
  */
341
+ /**
342
+ * The palette `renderTerpApp` was handed, resolved the way `layout-contract.json`'s is: an
343
+ * earlier name is the theme it now names, and a name nothing answers to is refused, in the
344
+ * resolver's own words. Dropping an unknown one instead hid it twice over: the app quietly
345
+ * opened on another palette, and a palette ALSO declared in the file stopped being reported as
346
+ * declared in both places, because the resolver sees a code side only when it is defined.
347
+ */
348
+ function resolveCodeTheme(name: string | undefined): Theme | undefined {
349
+ if (name === undefined) {
350
+ return undefined;
351
+ }
352
+ const theme = resolveTheme(name);
353
+ if (theme === null) {
354
+ throw new Error(
355
+ `renderTerpApp: "defaultTheme" is "${name}"; expected one of ` +
356
+ `${THEMES.map((known) => `"${known}"`).join(", ")} (or an earlier name: ` +
357
+ `${Object.keys(THEME_ALIASES).map((known) => `"${known}"`).join(", ")}).`,
358
+ );
359
+ }
360
+ return theme;
361
+ }
362
+
337
363
  export function renderTerpApp(options: RenderTerpAppOptions): void {
338
364
  // Resolved here as well as inside `buildAppRouter`, because the one key mounted OUTSIDE the
339
365
  // router is the palette: `ThemeProvider` wraps everything, the router included.
@@ -354,7 +380,7 @@ export function renderTerpApp(options: RenderTerpAppOptions): void {
354
380
  navPlacement: options.navPlacement,
355
381
  contentWidth: options.contentWidth,
356
382
  navGroups: options.navGroups,
357
- defaultTheme: options.defaultTheme,
383
+ defaultTheme: resolveCodeTheme(options.defaultTheme),
358
384
  });
359
385
  const collected = collectModules(options.modules);
360
386
  const { manifests, views } = withAdminArea(
@@ -0,0 +1,74 @@
1
+ import { useId } from "react";
2
+
3
+ import { useFormatNumber } from "../format";
4
+ import { injectTerpStyles } from "../styles";
5
+ import { useUiText } from "../uiText";
6
+ import type { UiText } from "../uiText";
7
+ import type { ChartPoint } from "./TrendChart";
8
+ import { round } from "./scale";
9
+
10
+ injectTerpStyles();
11
+
12
+ export interface BarChartProps {
13
+ /** What the bars compare: printed as the chart's caption, and its accessible name. */
14
+ label: UiText;
15
+ /**
16
+ * The categories, in the order to show them. Rank them before passing them: the order is the
17
+ * reading, and a chart that sorted on its own would answer a question the caller did not ask.
18
+ */
19
+ bars: readonly ChartPoint[];
20
+ /** How values print, as `Intl.NumberFormatOptions` (default: a plain number). */
21
+ format?: Intl.NumberFormatOptions;
22
+ /** The top of every bar's range (default: the largest value). */
23
+ max?: number;
24
+ }
25
+
26
+ /**
27
+ * Categories compared by length (ADR 0158, ADR 0169 §6): one row per category, its name, its
28
+ * bar and its value, the bars scaled to the largest.
29
+ *
30
+ * The chart IS its table. ADR 0158 asks every chart for its data as a table, and a bar chart's
31
+ * data is one row per bar — so the rows are a `<table>`, named by the caption, with each
32
+ * category as a row header and each value printed, and the bar is a cell of its own drawn for
33
+ * the eye and hidden from assistive technology with its cell, so a row reads as its name and
34
+ * its value and never as a blank between them. A name longer than a third of the tile ends in
35
+ * an ellipsis rather than squeezing the bars; its whole text is still what is read.
36
+ *
37
+ * The bars are SVG geometry with the chart's first colour from the sheet, so nothing is styled
38
+ * inline, and a value that is not a number draws no bar and prints the dash.
39
+ */
40
+ export function BarChart({ label, bars, format, max }: BarChartProps) {
41
+ const resolve = useUiText();
42
+ const formatNumber = useFormatNumber();
43
+ const captionId = useId();
44
+ const finite = bars.map((bar) => bar.value).filter((value) => Number.isFinite(value));
45
+ const top = max ?? Math.max(0, ...finite);
46
+ return (
47
+ <figure data-terp="bar-chart" aria-labelledby={captionId}>
48
+ <figcaption id={captionId} data-terp="chart-caption">
49
+ {resolve(label)}
50
+ </figcaption>
51
+ <table data-terp="bar-chart-table" aria-labelledby={captionId}>
52
+ <tbody>
53
+ {bars.map((bar, index) => {
54
+ const share =
55
+ top > 0 && Number.isFinite(bar.value) ? Math.min(Math.max(bar.value / top, 0), 1) : 0;
56
+ return (
57
+ <tr key={index}>
58
+ <th scope="row" data-terp="bar-chart-label">
59
+ <span data-terp="bar-chart-name">{resolve(bar.label)}</span>
60
+ </th>
61
+ <td data-terp="bar-chart-bar" aria-hidden="true">
62
+ <svg viewBox="0 0 100 1" preserveAspectRatio="none" focusable="false">
63
+ <rect data-terp="bar-chart-mark" x={0} y={0} width={round(share * 100)} height={1} />
64
+ </svg>
65
+ </td>
66
+ <td data-terp="bar-chart-value">{formatNumber(bar.value, format)}</td>
67
+ </tr>
68
+ );
69
+ })}
70
+ </tbody>
71
+ </table>
72
+ </figure>
73
+ );
74
+ }
@@ -0,0 +1,118 @@
1
+ import { useId } from "react";
2
+
3
+ import { useFormatNumber } from "../format";
4
+ import { injectTerpStyles } from "../styles";
5
+ import type { BadgeTone } from "../ui/Badge";
6
+ import { useUiText } from "../uiText";
7
+ import type { UiText } from "../uiText";
8
+ import { round } from "./scale";
9
+
10
+ injectTerpStyles();
11
+
12
+ /** One part of a whole. */
13
+ export interface ProportionPart {
14
+ /** What the part is ("Created"): its legend entry. */
15
+ label: UiText;
16
+ /** How many. Parts that are not positive numbers take no share. */
17
+ value: number;
18
+ /**
19
+ * The part's tone where it is a state — created, updated, failed — so failed reads as the
20
+ * danger it is; parts without one take the chart colours in order.
21
+ */
22
+ tone?: BadgeTone;
23
+ }
24
+
25
+ export interface ProportionBarProps {
26
+ /** What the whole is: printed as the caption, and the accessible name. */
27
+ label: UiText;
28
+ /** The parts, in the order they lie along the bar. */
29
+ parts: readonly ProportionPart[];
30
+ /** How each part's count prints, as `Intl.NumberFormatOptions` (default: a plain number). */
31
+ format?: Intl.NumberFormatOptions;
32
+ }
33
+
34
+ // One decimal, so a small part reads as the half a percent it is rather than as nothing.
35
+ const PERCENT: Intl.NumberFormatOptions = { style: "percent", maximumFractionDigits: 1 };
36
+
37
+ /**
38
+ * A whole split into its parts (ADR 0169 §6): one bar, each part's length its share, and a
39
+ * legend that says every part in words — its name, its count and its share. The legend is the
40
+ * chart's data and the bar is hidden from assistive technology, so a tone is always also a word.
41
+ *
42
+ * Parts that are states take their tone; the rest take the chart colours in order. Adjacent
43
+ * parts are parted by a hairline of the surface, so two parts of near colours still read as two.
44
+ */
45
+ export function ProportionBar({ label, parts, format }: ProportionBarProps) {
46
+ const resolve = useUiText();
47
+ const formatNumber = useFormatNumber();
48
+ const captionId = useId();
49
+ const counted = parts.map((part) => (Number.isFinite(part.value) && part.value > 0 ? part.value : 0));
50
+ const total = counted.reduce((sum, value) => sum + value, 0);
51
+ let start = 0;
52
+ const segments = counted.map((value) => {
53
+ const width = total > 0 ? (value / total) * 100 : 0;
54
+ const segment = { x: round(start), width: round(width) };
55
+ start += width;
56
+ return segment;
57
+ });
58
+ // A part with no tone of its own takes the next chart colour.
59
+ const series = (index: number) => String((index % 5) + 1);
60
+ return (
61
+ <figure data-terp="proportion-bar" aria-labelledby={captionId}>
62
+ <figcaption id={captionId} data-terp="chart-caption">
63
+ {resolve(label)}
64
+ </figcaption>
65
+ <svg
66
+ data-terp="proportion-bar-track"
67
+ viewBox="0 0 100 1"
68
+ preserveAspectRatio="none"
69
+ aria-hidden="true"
70
+ focusable="false"
71
+ >
72
+ {segments.map((segment, index) =>
73
+ segment.width > 0 ? (
74
+ <rect
75
+ key={index}
76
+ data-terp="proportion-bar-part"
77
+ data-tone={parts[index]!.tone}
78
+ data-series={parts[index]!.tone === undefined ? series(index) : undefined}
79
+ x={segment.x}
80
+ y={0}
81
+ width={segment.width}
82
+ height={1}
83
+ />
84
+ ) : null,
85
+ )}
86
+ {segments.slice(1).map((segment, index) =>
87
+ segment.width > 0 && segment.x > 0 ? (
88
+ <line
89
+ key={index}
90
+ data-terp="proportion-bar-gap"
91
+ x1={segment.x}
92
+ x2={segment.x}
93
+ y1={0}
94
+ y2={1}
95
+ />
96
+ ) : null,
97
+ )}
98
+ </svg>
99
+ <ul data-terp="chart-legend">
100
+ {parts.map((part, index) => (
101
+ <li key={index} data-terp="chart-legend-item">
102
+ <span
103
+ data-terp="chart-swatch"
104
+ data-tone={part.tone}
105
+ data-series={part.tone === undefined ? series(index) : undefined}
106
+ aria-hidden="true"
107
+ />
108
+ <span>{resolve(part.label)}</span>{" "}
109
+ <span data-terp="chart-legend-value">
110
+ {formatNumber(part.value, format)}
111
+ {total > 0 && ` · ${formatNumber(counted[index]! / total, PERCENT)}`}
112
+ </span>
113
+ </li>
114
+ ))}
115
+ </ul>
116
+ </figure>
117
+ );
118
+ }
@@ -0,0 +1,75 @@
1
+ import { formatList } from "../format";
2
+ import { useLocale } from "../locale";
3
+ import { injectTerpStyles } from "../styles";
4
+ import type { BadgeTone } from "../ui/Badge";
5
+ import { fillPlaceholders, useStrings, useUiText } from "../uiText";
6
+ import type { UiText } from "../uiText";
7
+
8
+ injectTerpStyles();
9
+
10
+ /**
11
+ * One way a run can end: its word and its tone. Declared once per ending and reused by every
12
+ * run that ends that way -- and an object rather than a string beside a tone, so its word is a
13
+ * `label`, which the i18n lint reads as copy wherever it is written.
14
+ */
15
+ export interface StatusOutcome {
16
+ /** The ending in words ("Succeeded", "Timed out"). */
17
+ label: UiText;
18
+ /** Its tone: the cell's colour. */
19
+ tone: BadgeTone;
20
+ }
21
+
22
+ /** One run and how it ended. */
23
+ export interface StatusRun {
24
+ /** Which run — its time or its number. */
25
+ label: UiText;
26
+ /** How it ended. */
27
+ outcome: StatusOutcome;
28
+ }
29
+
30
+ export interface StatusHistoryProps {
31
+ /** What ran ("Runs"): the start of the text alternative. */
32
+ label: UiText;
33
+ /** The runs, oldest first. */
34
+ runs: readonly StatusRun[];
35
+ }
36
+
37
+ /**
38
+ * How the recent runs of something ended, one cell per run, oldest first (ADR 0169 §6): a sync's
39
+ * runs, a webhook's deliveries, a check's results.
40
+ *
41
+ * A tone is always also a word: the latest run's ending is printed beside the cells, and every
42
+ * run is read out, its label and its ending, in the order drawn — the cells themselves are
43
+ * hidden from assistive technology. Phrasing content throughout, so it sits in a page's summary
44
+ * band, a collection's cell or a hub card's link alike. With no runs there is nothing to say,
45
+ * and it renders nothing rather than a sentence that stops at its colon.
46
+ */
47
+ export function StatusHistory({ label, runs }: StatusHistoryProps) {
48
+ const resolve = useUiText();
49
+ const strings = useStrings();
50
+ const locale = useLocale()?.locale;
51
+ const latest = runs.at(-1);
52
+ if (latest === undefined) {
53
+ return null;
54
+ }
55
+ const text = fillPlaceholders(strings.statusHistoryRuns, {
56
+ label: resolve(label),
57
+ runs: formatList(
58
+ runs.map((run) => `${resolve(run.label)}: ${resolve(run.outcome.label)}`),
59
+ locale,
60
+ ),
61
+ });
62
+ return (
63
+ <span data-terp="status-history">
64
+ <span data-terp="status-history-cells" aria-hidden="true">
65
+ {runs.map((run, index) => (
66
+ <span key={index} data-terp="status-history-cell" data-tone={run.outcome.tone} />
67
+ ))}
68
+ </span>
69
+ <span data-terp="status-history-latest" aria-hidden="true">
70
+ {resolve(latest.outcome.label)}
71
+ </span>
72
+ <span data-terp="status-history-data">{text}</span>
73
+ </span>
74
+ );
75
+ }
@@ -0,0 +1,232 @@
1
+ import { useId } from "react";
2
+
3
+ import { useFormatNumber } from "../format";
4
+ import { injectTerpStyles } from "../styles";
5
+ import { useUiText } from "../uiText";
6
+ import type { UiText } from "../uiText";
7
+ import { PLOT_HEIGHT, PLOT_WIDTH, bandCentre, columnOf, valueAxis, xOf, yOf } from "./scale";
8
+ import type { ValueAxis } from "./scale";
9
+
10
+ injectTerpStyles();
11
+
12
+ /** One point of a series, or one bar: what it is, and how much. */
13
+ export interface ChartPoint {
14
+ /** What the point is — a period's name or a date in a trend, a category in a bar chart. */
15
+ label: UiText;
16
+ /** How much, in the chart's format. A value that is not a number is printed as the dash and drawn as a gap. */
17
+ value: number;
18
+ }
19
+
20
+ /** A named run of points, oldest first. */
21
+ export interface ChartSeries {
22
+ /** What the series is ("This month"): its legend entry and its column in the table. */
23
+ label: UiText;
24
+ points: readonly ChartPoint[];
25
+ }
26
+
27
+ /** How the series is drawn: a line, a line with the area under it filled, or a column per point. */
28
+ export type TrendMark = "line" | "area" | "columns";
29
+
30
+ export interface TrendChartProps {
31
+ /** What the chart shows: printed as its caption, and its accessible name. */
32
+ label: UiText;
33
+ /** The values over time. */
34
+ series: ChartSeries;
35
+ /**
36
+ * The same measure for an earlier period, drawn as a dashed line — behind a line or an area,
37
+ * over columns, where behind them it would be hidden — and listed beside the series in the
38
+ * table: the comparison a figure's delta summarises. Point `i` of
39
+ * either series stands at the same place, so a period still running stops short of the one it
40
+ * is compared with, as "this month so far" against last month should. Where the two differ in
41
+ * length, label points by their place in the period ("Day 3"): the axis and the table read a
42
+ * point's label from whichever series has that point.
43
+ */
44
+ comparison?: ChartSeries;
45
+ /**
46
+ * `"line"` (the default) for a level that moves, `"area"` for an amount that accumulates,
47
+ * `"columns"` for a count per period — runs per day, deliveries per hour. An area and columns
48
+ * keep zero on the axis, because their length is the value; a line does not, because an axis
49
+ * from zero flattens the change a line is drawn to show.
50
+ */
51
+ mark?: TrendMark;
52
+ /** How values print, as `Intl.NumberFormatOptions` (default: a plain number). */
53
+ format?: Intl.NumberFormatOptions;
54
+ }
55
+
56
+ /**
57
+ * Points as runs of coordinates, broken where a value is not a number. `x` places point `i`;
58
+ * a run of one point is kept, and drawn as a dot, since a line needs two.
59
+ */
60
+ function runsOf(points: readonly ChartPoint[], axis: ValueAxis, x: (index: number) => number): string[][] {
61
+ const runs: string[][] = [];
62
+ let current: string[] = [];
63
+ points.forEach((point, index) => {
64
+ if (!Number.isFinite(point.value)) {
65
+ if (current.length > 0) runs.push(current);
66
+ current = [];
67
+ return;
68
+ }
69
+ current.push(`${x(index)},${yOf(point.value, axis)}`);
70
+ });
71
+ if (current.length > 0) runs.push(current);
72
+ return runs;
73
+ }
74
+
75
+ /**
76
+ * Values over time (ADR 0158, ADR 0169 §6): a line, an area or columns, with an optional
77
+ * comparison period, on a value axis of round numbers.
78
+ *
79
+ * Under ADR 0158's contract: SVG geometry in attributes and colour from the sheet, so nothing
80
+ * is styled inline; numbers through the `format` helpers in the app's locale; no dependency;
81
+ * and the data as a table — visually hidden here, read by assistive technology in place of the
82
+ * picture, which is hidden from it. The axis takes three ticks in two equal steps, so its labels
83
+ * stand at the top, the middle and the foot of the plot without a position of their own; an
84
+ * axis of counts steps in whole numbers.
85
+ *
86
+ * A tile on the surface, the rung where data is read (ADR 0169 §3), like a figure.
87
+ */
88
+ export function TrendChart({ label, series, comparison, mark = "line", format }: TrendChartProps) {
89
+ const resolve = useUiText();
90
+ const formatNumber = useFormatNumber();
91
+ const captionId = useId();
92
+ const points = series.points;
93
+ const earlier = comparison?.points ?? [];
94
+ // One index scale for both series, as long as the longer of them.
95
+ const count = Math.max(points.length, earlier.length);
96
+ const values = [...points, ...earlier].map((point) => point.value);
97
+ const counts = values.filter((value) => Number.isFinite(value)).every((value) => Number.isInteger(value));
98
+ const axis = valueAxis(values, mark !== "line", counts);
99
+ const base = yOf(Math.min(Math.max(0, axis.low), axis.high), axis);
100
+ // A line's point stands at its index across the plot; a column's in the middle of its band,
101
+ // where a comparison drawn over columns puts its vertices too.
102
+ const x = mark === "columns" ? (index: number) => bandCentre(index, count) : (index: number) => xOf(index, count);
103
+ const lines = runsOf(points, axis, x);
104
+ const before = runsOf(earlier, axis, x);
105
+ const caption = resolve(label);
106
+ const labelAt = (index: number) => resolve(points[index]?.label ?? earlier[index]?.label ?? "");
107
+ // Which labels the x axis prints: the ends, and the middle where there are enough points for
108
+ // one. A column chart prints under its columns, so its middle band always has one; a line's
109
+ // middle label sits at the plot's centre, where only an odd number of points puts a point.
110
+ const middle = (count - 1) / 2;
111
+ const shown = (index: number) =>
112
+ index === 0 ||
113
+ index === count - 1 ||
114
+ (count >= 5 && (mark === "columns" ? index === Math.floor(middle) : index === middle));
115
+ const indices = Array.from({ length: count }, (_, index) => index);
116
+ const comparisonMarks = before.map((run, index) =>
117
+ run.length === 1 ? (
118
+ // A zero-length stroke with a round cap: a dot the plot's stretch cannot flatten.
119
+ <polyline key={`c${index}`} data-terp="trend-chart-dot" data-series="comparison" points={`${run[0]} ${run[0]}`} />
120
+ ) : (
121
+ <polyline key={`c${index}`} data-terp="trend-chart-comparison" points={run.join(" ")} />
122
+ ),
123
+ );
124
+ return (
125
+ // Named by its caption explicitly: the figure-from-figcaption name is the HTML mapping
126
+ // browsers implement and not every accessibility tree computes.
127
+ <figure data-terp="trend-chart" data-mark={mark} aria-labelledby={captionId}>
128
+ <figcaption id={captionId} data-terp="chart-caption">
129
+ {caption}
130
+ </figcaption>
131
+ {comparison !== undefined && (
132
+ <ul data-terp="chart-legend">
133
+ <li data-terp="chart-legend-item">
134
+ <span data-terp="chart-swatch" data-series="main" aria-hidden="true" />
135
+ {resolve(series.label)}
136
+ </li>
137
+ <li data-terp="chart-legend-item">
138
+ <span data-terp="chart-swatch" data-series="comparison" aria-hidden="true" />
139
+ {resolve(comparison.label)}
140
+ </li>
141
+ </ul>
142
+ )}
143
+ <div data-terp="chart-body" aria-hidden="true">
144
+ <span data-terp="chart-axis">
145
+ {axis.ticks.map((tick, index) => (
146
+ <span key={index}>{formatNumber(tick, format)}</span>
147
+ ))}
148
+ </span>
149
+ <svg
150
+ data-terp="chart-plot"
151
+ viewBox={`0 0 ${PLOT_WIDTH} ${PLOT_HEIGHT}`}
152
+ preserveAspectRatio="none"
153
+ focusable="false"
154
+ >
155
+ {[0, PLOT_HEIGHT / 2, PLOT_HEIGHT].map((y) => (
156
+ <line key={y} data-terp="chart-gridline" x1={0} x2={PLOT_WIDTH} y1={y} y2={y} />
157
+ ))}
158
+ {mark !== "columns" && comparisonMarks}
159
+ {mark === "area" &&
160
+ lines
161
+ .filter((run) => run.length > 1)
162
+ .map((run, index) => {
163
+ const first = run[0]!.split(",")[0];
164
+ const last = run.at(-1)!.split(",")[0];
165
+ return (
166
+ <polygon
167
+ key={index}
168
+ data-terp="trend-chart-area"
169
+ points={`${first},${base} ${run.join(" ")} ${last},${base}`}
170
+ />
171
+ );
172
+ })}
173
+ {mark !== "columns" &&
174
+ lines.map((run, index) =>
175
+ run.length === 1 ? (
176
+ <polyline key={index} data-terp="trend-chart-dot" points={`${run[0]} ${run[0]}`} />
177
+ ) : (
178
+ <polyline key={index} data-terp="trend-chart-line" points={run.join(" ")} />
179
+ ),
180
+ )}
181
+ {mark === "columns" &&
182
+ points.map((point, index) => {
183
+ if (!Number.isFinite(point.value)) {
184
+ return null;
185
+ }
186
+ const column = columnOf(index, count);
187
+ const y = yOf(point.value, axis);
188
+ return (
189
+ <rect
190
+ key={index}
191
+ data-terp="trend-chart-column"
192
+ x={column.x}
193
+ y={Math.min(y, base)}
194
+ width={column.width}
195
+ height={Math.abs(base - y)}
196
+ />
197
+ );
198
+ })}
199
+ {mark === "columns" && comparisonMarks}
200
+ </svg>
201
+ <span data-terp="chart-labels" data-mark={mark}>
202
+ {indices.map((index) =>
203
+ mark === "columns" || shown(index) ? (
204
+ <span key={index} data-quiet={mark === "columns" && !shown(index) ? "true" : undefined}>
205
+ {labelAt(index)}
206
+ </span>
207
+ ) : null,
208
+ )}
209
+ </span>
210
+ </div>
211
+ {/* Named by the same caption rather than a <caption> of its own, so it is not read twice. */}
212
+ <table data-terp="chart-table" aria-labelledby={captionId}>
213
+ <thead>
214
+ <tr>
215
+ <td />
216
+ <th scope="col">{resolve(series.label)}</th>
217
+ {comparison !== undefined && <th scope="col">{resolve(comparison.label)}</th>}
218
+ </tr>
219
+ </thead>
220
+ <tbody>
221
+ {indices.map((index) => (
222
+ <tr key={index}>
223
+ <th scope="row">{labelAt(index)}</th>
224
+ <td>{formatNumber(points[index]?.value, format)}</td>
225
+ {comparison !== undefined && <td>{formatNumber(earlier[index]?.value, format)}</td>}
226
+ </tr>
227
+ ))}
228
+ </tbody>
229
+ </table>
230
+ </figure>
231
+ );
232
+ }