@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
@@ -506,6 +506,19 @@ describe("the packaged admin area", () => {
506
506
  expect(probed.some((url) => url.includes("/api/v1/groups/"))).toBe(false);
507
507
  });
508
508
 
509
+ it("drops the access card with the access section, the one a full hub always drew", async () => {
510
+ // The selective hub replaced the full one only when users, groups or audit was dropped, so
511
+ // `{ access: false }` alone removed the route and kept the card that leads to it.
512
+ renderAdminApp("/admin", 30, { access: false });
513
+ await waitFor(() =>
514
+ expect(screen.getByRole("heading", { level: 1, name: "Admin" })).toBeInTheDocument(),
515
+ );
516
+ expect(screen.getByRole("link", { name: /Users/ })).toBeInTheDocument();
517
+ expect(screen.getByRole("link", { name: /Groups/ })).toBeInTheDocument();
518
+ expect(screen.getByRole("link", { name: /Audit log/ })).toBeInTheDocument();
519
+ expect(screen.queryByRole("link", { name: /^Access/ })).not.toBeInTheDocument();
520
+ });
521
+
509
522
  it("uses the users overview action and clickable rows for dedicated pages", async () => {
510
523
  renderAdminApp("/admin/users");
511
524
  await waitFor(() =>
@@ -513,6 +526,13 @@ describe("the packaged admin area", () => {
513
526
  );
514
527
  expect(screen.getByRole("button", { name: "Provision user" })).toBeInTheDocument();
515
528
  await waitFor(() => expect(screen.getByText("jane.doe@example.com")).toBeInTheDocument());
529
+ // The status column is the quiet form (ADR 0169 §5): a dot before its word, toned by the
530
+ // account's state. Mutation: drop `status` from the column, and the dot is gone.
531
+ const active = screen.getAllByText("Active")[0]!.closest('[data-terp="dataview-status"]')!;
532
+ expect(active.querySelector('[data-terp="dataview-status-dot"]')).toHaveAttribute(
533
+ "data-tone",
534
+ "success",
535
+ );
516
536
  expect(screen.getByRole("navigation", { name: "Breadcrumb" })).toHaveTextContent("Admin");
517
537
 
518
538
  fireEvent.click(screen.getByText("jane.doe@example.com"));
@@ -702,6 +722,9 @@ describe("the packaged admin area", () => {
702
722
  renderAdminApp("/admin/groups");
703
723
  await screen.findByRole("heading", { level: 1, name: "Groups" });
704
724
  await screen.findByText("Finance");
725
+ // Group sizes as bars against the largest shown, each still printed (ADR 0169 §5).
726
+ // Mutation: drop `bar` from the column, and no meter is named for it.
727
+ expect(screen.getAllByRole("meter", { name: "Members" }).length).toBeGreaterThan(0);
705
728
 
706
729
  fireEvent.click(screen.getByRole("button", { name: "Create group" }));
707
730
  await screen.findByRole("heading", { level: 1, name: "Create group" });
@@ -819,6 +842,33 @@ describe("the packaged admin area", () => {
819
842
  ).toBeInTheDocument();
820
843
  });
821
844
 
845
+ it("words a refusal by its code in the app's language, not in the backend's English", async () => {
846
+ // The admin screens toasted the backend's detail as written, so a rate-limited create said
847
+ // "Too many requests; please retry later." on a Dutch screen. Mutation: toast error.message
848
+ // again, and the English sentence is what appears.
849
+ const { fetchMock } = renderAdminApp("/admin/groups/new", 30, true, DUTCH);
850
+ await screen.findByRole("heading", { level: 1, name: "Groep aanmaken" });
851
+ const passthrough = fetchMock.getMockImplementation()!;
852
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
853
+ const request = input as Request;
854
+ if (request.method === "POST" && request.url.endsWith("/api/v1/groups/")) {
855
+ return jsonResponse(
856
+ { code: "rate_limited", detail: "Too many requests; please retry later.", request_id: "-" },
857
+ 429,
858
+ );
859
+ }
860
+ return passthrough(input, init);
861
+ });
862
+
863
+ fireEvent.change(screen.getByLabelText("Naam"), { target: { value: "Redactie" } });
864
+ fireEvent.click(screen.getByRole("button", { name: "Groep aanmaken" }));
865
+
866
+ expect(
867
+ await screen.findByText("Te veel verzoeken tegelijk. Wacht even en probeer het opnieuw."),
868
+ ).toBeInTheDocument();
869
+ expect(screen.queryByText("Too many requests; please retry later.")).toBeNull();
870
+ });
871
+
822
872
  it("renders its dates through the framework helper, not the built-in", async () => {
823
873
  // What this gates is the CONVERSION, not the locale channel, and the distinction is worth
824
874
  // naming: `renderAdminApp` mounts no `LocaleProvider`, so `useFormatDateTime` resolves an
@@ -866,18 +916,171 @@ describe("the packaged admin area", () => {
866
916
  renderAdminApp("/admin/groups/g1");
867
917
  const headings = await waitFor(() => {
868
918
  const found = document.querySelectorAll('[data-terp="admin-section-title"]');
869
- // Access per module, members, granted permissions. The count is here so the loop below
870
- // cannot pass by finding nothing, and naming them is what keeps it from being a magic
871
- // number the next section silently invalidates.
872
- expect(found.length).toBe(3);
919
+ // Access per module. The count is here so the loop below cannot pass by finding
920
+ // nothing; the members and the granted permissions were two more, and are collections
921
+ // that name themselves now (below).
922
+ expect(found.length).toBe(1);
873
923
  return found;
874
924
  });
875
925
  for (const heading of headings) {
876
- expect(heading.tagName).toBe("H2");
926
+ // An h3, the level of the group's two collections beside it and of every Card's title:
927
+ // as an h2 it put the members and the permissions under "Access per module" in the
928
+ // page's outline. Mutation: an h2 again, and this fails.
929
+ expect(heading.tagName).toBe("H3");
877
930
  expect(heading.getAttribute("style")).toBeNull();
878
931
  }
879
932
  });
880
933
 
934
+ it("shows an account's facts and a group's as ruled sheets", async () => {
935
+ // The packaged detail screens are the ruled grid's consumers in the framework (ADR 0169
936
+ // §5). Mutation: drop layout="grid" from either list, and its layout is "stacked".
937
+ renderAdminApp("/admin/users/u1");
938
+ await screen.findByRole("heading", { level: 1, name: "jane.doe@example.com" });
939
+ await waitFor(() =>
940
+ expect(document.querySelector('[data-terp="detail-list"]')).toHaveAttribute("data-layout", "grid"),
941
+ );
942
+ cleanup();
943
+ renderAdminApp("/admin/groups/g1");
944
+ await waitFor(() =>
945
+ expect(document.querySelector('[data-terp="detail-list"]')).toHaveAttribute("data-layout", "grid"),
946
+ );
947
+ });
948
+
949
+ it("shows an account's own history from the audit trail, in the app's words", async () => {
950
+ // The trail narrowed to the record the screen is about (ADR 0169 §5): the request names
951
+ // the record, and the events read as a timeline, newest first. Mutation: drop the target
952
+ // from the query, and the request is the whole trail.
953
+ const { fetchMock } = renderAdminApp("/admin/users/u1");
954
+ const base = fetchMock.getMockImplementation()!;
955
+ fetchMock.mockImplementation(async (input) => {
956
+ const url = new URL((input as Request).url);
957
+ if (url.pathname.endsWith("/api/v1/audit/") && url.searchParams.get("target_id") === "u1") {
958
+ return jsonResponse({
959
+ items: [
960
+ {
961
+ id: "e2",
962
+ created_at: "2026-08-21T09:30:00Z",
963
+ action: "updated",
964
+ target_type: "User",
965
+ target_id: "u1",
966
+ actor_id: "9f2c1b7e-0000-4000-8000-000000000002",
967
+ request_id: null,
968
+ payload: null,
969
+ },
970
+ {
971
+ id: "e1",
972
+ created_at: "2026-08-20T08:00:00Z",
973
+ action: "created",
974
+ target_type: "User",
975
+ target_id: "u1",
976
+ actor_id: null,
977
+ request_id: null,
978
+ payload: null,
979
+ },
980
+ ],
981
+ total: 2,
982
+ skip: 0,
983
+ limit: 10,
984
+ });
985
+ }
986
+ return base(input);
987
+ });
988
+ const history = await screen.findByRole("list", { name: "History" });
989
+ const items = within(history).getAllByRole("listitem");
990
+ expect(items.map((item) => item.querySelector('[data-terp="timeline-label"]')!.textContent)).toEqual([
991
+ "Changed",
992
+ "Created",
993
+ ]);
994
+ expect(items[0]!.textContent).toContain("Actor: 9f2c1b7e");
995
+ const asked = fetchMock.mock.calls
996
+ .map((call) => new URL((call[0] as Request).url))
997
+ .find((url) => url.pathname.endsWith("/api/v1/audit/"))!;
998
+ expect(asked.searchParams.get("target_type")).toBe("User");
999
+ expect(asked.searchParams.get("target_id")).toBe("u1");
1000
+ });
1001
+
1002
+ it("shows a group's own history, asked for by the group", async () => {
1003
+ // Mutation: ask GroupDetail's history for the wrong record type, and this group's events are
1004
+ // never asked for.
1005
+ const { fetchMock } = renderAdminApp("/admin/groups/g1");
1006
+ const base = fetchMock.getMockImplementation()!;
1007
+ fetchMock.mockImplementation(async (input) => {
1008
+ const url = new URL((input as Request).url);
1009
+ if (
1010
+ url.pathname.endsWith("/api/v1/audit/") &&
1011
+ url.searchParams.get("target_type") === "Group" &&
1012
+ url.searchParams.get("target_id") === "g1"
1013
+ ) {
1014
+ return jsonResponse({
1015
+ items: [
1016
+ {
1017
+ id: "g-e1",
1018
+ created_at: "2026-08-20T08:00:00Z",
1019
+ action: "created",
1020
+ target_type: "Group",
1021
+ target_id: "g1",
1022
+ actor_id: null,
1023
+ request_id: null,
1024
+ payload: null,
1025
+ },
1026
+ ],
1027
+ total: 1,
1028
+ skip: 0,
1029
+ limit: 10,
1030
+ });
1031
+ }
1032
+ return base(input);
1033
+ });
1034
+ const history = await screen.findByRole("list", { name: "History" });
1035
+ expect(within(history).getAllByRole("listitem").map((item) => item.textContent)).toEqual([
1036
+ expect.stringContaining("Created"),
1037
+ ]);
1038
+ });
1039
+
1040
+ it.each([
1041
+ ["a trail the caller may not read", () => jsonResponse({ code: "permission_denied", detail: "No.", request_id: "-" }, 403)],
1042
+ ["a trail with nothing about the record", () => jsonResponse({ items: [], total: 0, skip: 0, limit: 10 })],
1043
+ ])("renders no history section for %s, and nothing in its place", async (_case, answer) => {
1044
+ // The history is context: the screen is whole without it. Mutation: render an error state
1045
+ // when the trail cannot be read, or the card when it is empty, and a section appears here.
1046
+ const { fetchMock } = renderAdminApp("/admin/users/u1");
1047
+ const base = fetchMock.getMockImplementation()!;
1048
+ fetchMock.mockImplementation(async (input) => {
1049
+ const url = new URL((input as Request).url);
1050
+ return url.pathname.endsWith("/api/v1/audit/") ? answer() : base(input);
1051
+ });
1052
+ await screen.findByRole("heading", { level: 1 });
1053
+ await waitFor(() =>
1054
+ expect(
1055
+ fetchMock.mock.calls.some((call) => new URL((call[0] as Request).url).pathname.endsWith("/api/v1/audit/")),
1056
+ ).toBe(true),
1057
+ );
1058
+ // Let the answer land and the component settle before looking for what it must not draw.
1059
+ await act(async () => {
1060
+ await new Promise((resolve) => setTimeout(resolve, 0));
1061
+ });
1062
+ expect(screen.queryByRole("heading", { name: "History" })).toBeNull();
1063
+ expect(screen.queryByRole("list", { name: "History" })).toBeNull();
1064
+ expect(document.querySelector('[data-terp="error-state"]')).toBeNull();
1065
+ });
1066
+
1067
+ it("names each of a group's collections, and counts the one it has read", async () => {
1068
+ // The members and the grants were an h2 the screen placed over an embedded DataView, with
1069
+ // the count nowhere; the collection now carries its own name and count (ADR 0169 §5), and
1070
+ // the way to add to it sits in its toolbar, under the name. The fixture serves one member
1071
+ // and no grants request at all, so only the members heading may claim a number.
1072
+ // Mutation: drop the count from DataView's heading, and "Members 1" is never found.
1073
+ renderAdminApp("/admin/groups/g1");
1074
+ expect(await screen.findByRole("heading", { level: 3, name: "Members 1" })).toBeInTheDocument();
1075
+ const permissions = screen.getByRole("heading", { level: 3, name: /^Permissions/ });
1076
+ expect(permissions.closest('[data-terp="dataview"]')).not.toBeNull();
1077
+ // The add-member form is inside the members collection, after its heading.
1078
+ const members = screen.getByRole("heading", { level: 3, name: "Members 1" });
1079
+ const form = screen.getByRole("button", { name: "Add member" }).closest("form")!;
1080
+ expect(members.closest('[data-terp="dataview"]')!.contains(form)).toBe(true);
1081
+ expect(members.compareDocumentPosition(form) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
1082
+ });
1083
+
881
1084
  it("speaks the app's language on the audit screen, its table and expanded row included", async () => {
882
1085
  // The framework's own screen, under the framework's own Dutch catalog. Its title was Dutch
883
1086
  // and everything its DataView drew was not — the result count, the row controls — because
@@ -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
+ }