@terpjs/react-core 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +35 -14
  2. package/package.json +5 -5
  3. package/src/DashboardPage.tsx +34 -0
  4. package/src/Field.test.tsx +26 -1
  5. package/src/Field.tsx +15 -5
  6. package/src/HubPage.tsx +7 -2
  7. package/src/Page.test.tsx +192 -0
  8. package/src/Page.tsx +141 -55
  9. package/src/PageActions.test.tsx +64 -3
  10. package/src/PageActions.tsx +40 -15
  11. package/src/PageSequence.tsx +114 -0
  12. package/src/Stat.test.tsx +341 -0
  13. package/src/Stat.tsx +314 -0
  14. package/src/Timeline.test.tsx +74 -0
  15. package/src/Timeline.tsx +71 -0
  16. package/src/admin/AdminHub.tsx +11 -3
  17. package/src/admin/AuditLogAdmin.tsx +3 -1
  18. package/src/admin/GroupCreate.tsx +3 -1
  19. package/src/admin/GroupDetail.tsx +72 -67
  20. package/src/admin/GroupsAdmin.tsx +3 -1
  21. package/src/admin/ModuleAccessPanel.tsx +13 -12
  22. package/src/admin/RecordHistory.tsx +83 -0
  23. package/src/admin/UserCreate.tsx +3 -1
  24. package/src/admin/UserDetail.tsx +8 -1
  25. package/src/admin/UsersAdmin.tsx +3 -0
  26. package/src/admin/admin.test.tsx +208 -5
  27. package/src/bootstrap.test.tsx +31 -7
  28. package/src/bootstrap.tsx +30 -4
  29. package/src/charts/BarChart.tsx +74 -0
  30. package/src/charts/ProportionBar.tsx +118 -0
  31. package/src/charts/StatusHistory.tsx +75 -0
  32. package/src/charts/TrendChart.tsx +232 -0
  33. package/src/charts/charts.test.tsx +409 -0
  34. package/src/charts/scale.ts +103 -0
  35. package/src/dataview/DataView.test.tsx +255 -0
  36. package/src/dataview/DataView.tsx +35 -0
  37. package/src/dataview/DataViewCardList.tsx +21 -13
  38. package/src/dataview/DataViewTable.tsx +5 -6
  39. package/src/dataview/README.md +18 -0
  40. package/src/dataview/index.ts +1 -0
  41. package/src/dataview/internal.tsx +112 -5
  42. package/src/dataview/types.ts +39 -10
  43. package/src/errorMessages.test.tsx +17 -0
  44. package/src/errorMessages.tsx +18 -0
  45. package/src/format.ts +15 -0
  46. package/src/index.ts +24 -1
  47. package/src/layout.manifest.json +2 -9
  48. package/src/layout.manifest.test.ts +4 -2
  49. package/src/layout.test.tsx +74 -6
  50. package/src/layout.tsx +85 -25
  51. package/src/layoutContract.test.tsx +239 -1
  52. package/src/layoutContract.ts +131 -5
  53. package/src/layoutDeclaration.test.ts +31 -10
  54. package/src/layoutDeclaration.ts +9 -4
  55. package/src/locale.tsx +20 -3
  56. package/src/markers.test.ts +70 -2
  57. package/src/router.test.tsx +15 -3
  58. package/src/router.tsx +11 -2
  59. package/src/ssr.test.tsx +18 -0
  60. package/src/styles.test.ts +222 -190
  61. package/src/styles.ts +1268 -328
  62. package/src/theme.test.tsx +44 -18
  63. package/src/theme.themes.test.ts +22 -2
  64. package/src/theme.tsx +22 -14
  65. package/src/themes.ts +39 -4
  66. package/src/tokens.guard.test.ts +13 -15
  67. package/src/typography.tsx +5 -1
  68. package/src/ui/Alert.test.tsx +24 -1
  69. package/src/ui/Alert.tsx +10 -1
  70. package/src/ui/Card.tsx +5 -4
  71. package/src/ui/Tooltip.test.tsx +171 -2
  72. package/src/ui/Tooltip.tsx +144 -8
  73. package/src/ui/controlMessages.tsx +20 -7
  74. package/src/uiText.test.tsx +16 -0
  75. package/src/uiText.tsx +76 -7
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The arithmetic every chart kind shares: a value axis with round bounds, and positions on a
3
+ * plot whose coordinates are proportions rather than pixels.
4
+ *
5
+ * Kept free of React and of the DOM, so the geometry is tested as numbers — the screenshot lane
6
+ * shows a picture, and a picture cannot say that a column is a pixel too short.
7
+ */
8
+
9
+ /** The plot's coordinate space. The SVG stretches to its box, so these are proportions. */
10
+ export const PLOT_WIDTH = 100;
11
+ export const PLOT_HEIGHT = 40;
12
+
13
+ /** A value axis: its bottom, its top and the tick between them. */
14
+ export interface ValueAxis {
15
+ low: number;
16
+ high: number;
17
+ /** The three ticks, top first, the order the labels are read down the axis. */
18
+ ticks: readonly [number, number, number];
19
+ }
20
+
21
+ /**
22
+ * The smallest of 1, 2, 2.5 and 5 times a power of ten that is at least `raw`. An axis of
23
+ * `counts` steps in whole numbers instead -- 1, 2, 3 and 5 times a power of ten, and never
24
+ * below 1 -- since half a run is a label nobody can read, and a format that rounds it prints a
25
+ * tick the gridline is not at.
26
+ */
27
+ export function niceStep(raw: number, counts = false): number {
28
+ if (!(raw > 0) || !Number.isFinite(raw)) {
29
+ return 1;
30
+ }
31
+ if (counts && raw <= 1) {
32
+ return 1;
33
+ }
34
+ const power = 10 ** Math.floor(Math.log10(raw));
35
+ for (const factor of counts ? [1, 2, 3, 5, 10] : [1, 2, 2.5, 5, 10]) {
36
+ if (factor * power >= raw - power * 1e-9) {
37
+ return factor * power;
38
+ }
39
+ }
40
+ return 10 * power;
41
+ }
42
+
43
+ /**
44
+ * A value axis over `values` in two equal steps of a round size, so its three tick labels can
45
+ * sit at the top, the middle and the bottom of the plot with no position of their own.
46
+ *
47
+ * `fromZero` keeps zero on the axis — required where a mark's length is its value (an area, a
48
+ * column), and left off for a line, where an axis from zero flattens the change the line is
49
+ * there to show. An empty or a flat series still gets an axis with height. `counts` steps it in
50
+ * whole numbers, for values that are counts.
51
+ */
52
+ export function valueAxis(values: readonly number[], fromZero: boolean, counts = false): ValueAxis {
53
+ const finite = values.filter((value) => Number.isFinite(value));
54
+ let min = finite.length === 0 ? 0 : Math.min(...finite);
55
+ let max = finite.length === 0 ? 0 : Math.max(...finite);
56
+ if (fromZero) {
57
+ min = Math.min(min, 0);
58
+ max = Math.max(max, 0);
59
+ }
60
+ if (min === max) {
61
+ // A flat series: give it a step either side of itself, or one step above zero.
62
+ const pad = niceStep(Math.abs(max) || 1, counts);
63
+ min = fromZero && min >= 0 ? 0 : min - pad;
64
+ max = max + pad;
65
+ }
66
+ let step = niceStep((max - min) / 2, counts);
67
+ for (;;) {
68
+ const low = Math.floor(min / step) * step;
69
+ const high = low + 2 * step;
70
+ if (high >= max - step * 1e-9) {
71
+ return { low: clean(low), high: clean(high), ticks: [clean(high), clean(low + step), clean(low)] };
72
+ }
73
+ step = niceStep(step * 1.01, counts);
74
+ }
75
+ }
76
+
77
+ /** Float residue off a computed tick (0.30000000000000004 is 0.3). */
78
+ const clean = (value: number) => Number.parseFloat(value.toPrecision(12));
79
+
80
+ /** The y coordinate of `value` on an axis, top of the plot highest. */
81
+ export function yOf(value: number, axis: ValueAxis): number {
82
+ const share = (value - axis.low) / (axis.high - axis.low);
83
+ return round(PLOT_HEIGHT - share * PLOT_HEIGHT);
84
+ }
85
+
86
+ /** The x coordinate of point `index` of `count`, the first at the left edge and the last at the right. */
87
+ export function xOf(index: number, count: number): number {
88
+ return count <= 1 ? PLOT_WIDTH / 2 : round((index / (count - 1)) * PLOT_WIDTH);
89
+ }
90
+
91
+ /** The middle of band `index` of `count`: where a column stands, and a line drawn over columns bends. */
92
+ export function bandCentre(index: number, count: number): number {
93
+ return round(((index + 0.5) * PLOT_WIDTH) / count);
94
+ }
95
+
96
+ /** A column's left edge and width, in a band of its own: each of `count` bands holds one column. */
97
+ export function columnOf(index: number, count: number): { x: number; width: number } {
98
+ const band = PLOT_WIDTH / count;
99
+ const width = band * 0.6;
100
+ return { x: round(index * band + (band - width) / 2), width: round(width) };
101
+ }
102
+
103
+ export const round = (value: number) => Math.round(value * 100) / 100;
@@ -7,6 +7,7 @@ import { DataView } from "./DataView";
7
7
  import { DataViewPagination } from "./DataViewPagination";
8
8
  import { InMemoryDataViewRepository } from "./repositories/InMemoryDataViewRepository";
9
9
  import { InMemoryViewStateRepository } from "./repositories/viewState";
10
+ import { barMaxima } from "./internal";
10
11
  import type { DataViewColumn, DataViewQuery, DataViewRepository } from "./types";
11
12
 
12
13
  afterEach(() => {
@@ -683,3 +684,257 @@ describe("DataView localisation", () => {
683
684
  expect(screen.getByRole("button", { name: "Volgende pagina" })).toBeInTheDocument();
684
685
  });
685
686
  });
687
+
688
+ describe("DataView as a panel (ADR 0169 §5)", () => {
689
+ it("names itself in a heading and counts its results once it has read them", async () => {
690
+ // Mutation: drop the count from the heading, and the name stays "Tickets".
691
+ render(<DataView title="Tickets" repository={inMemoryRepo()} columns={COLUMNS} />);
692
+ // No number while the first page loads: the count is a claim, and nothing was read yet.
693
+ expect(screen.getByRole("heading", { level: 3, name: "Tickets" })).toBeInTheDocument();
694
+ expect(await screen.findByRole("heading", { level: 3, name: "Tickets 4" })).toBeInTheDocument();
695
+ });
696
+
697
+ it("prints the count in the app's locale", async () => {
698
+ const many = Array.from({ length: 1234 }, (_, index) => ({
699
+ id: String(index),
700
+ title: `Ticket ${index}`,
701
+ status: "open",
702
+ }));
703
+ render(
704
+ <LocaleProvider locales={{ nl: LOCALE_NL, en: LOCALE_EN }} defaultLocale="nl">
705
+ <DataView title="Tickets" repository={inMemoryRepo(many)} columns={COLUMNS} />
706
+ </LocaleProvider>,
707
+ );
708
+ expect(await screen.findByRole("heading", { level: 3, name: "Tickets 1.234" })).toBeInTheDocument();
709
+ });
710
+
711
+ it("claims no count over an error, even with an earlier count in hand", async () => {
712
+ // A failed query sets the error and leaves the last total where it was, so after one good
713
+ // page and one failed search the view still holds "4" -- a number about rows it is no
714
+ // longer showing. Mutation: drop the error from the condition, and the heading keeps "4".
715
+ let calls = 0;
716
+ const base = inMemoryRepo();
717
+ const flaky: DataViewRepository<Ticket> = {
718
+ capabilities: base.capabilities,
719
+ getRowId: (t) => t.id,
720
+ query: (query) =>
721
+ calls++ === 0 ? base.query(query) : Promise.reject(new Error("upstream is down")),
722
+ };
723
+ render(<DataView title="Tickets" repository={flaky} columns={COLUMNS} searchDebounceMs={0} />);
724
+ await screen.findByRole("heading", { level: 3, name: "Tickets 4" });
725
+ fireEvent.change(screen.getByRole("searchbox"), { target: { value: "printer" } });
726
+ await waitFor(() =>
727
+ expect(document.querySelector('[data-terp="dataview-error"]')).not.toBeNull(),
728
+ );
729
+ expect(screen.getByRole("heading", { level: 3, name: "Tickets" })).toBeInTheDocument();
730
+ expect(document.querySelector('[data-terp="dataview-count"]')).toBeNull();
731
+ });
732
+
733
+ it("titles an embedded view too, above its toolbar", async () => {
734
+ render(
735
+ <DataView
736
+ title="Tickets"
737
+ variant="embedded"
738
+ repository={inMemoryRepo()}
739
+ columns={COLUMNS}
740
+ toolbarContent={<button type="button">Add ticket</button>}
741
+ />,
742
+ );
743
+ const heading = await screen.findByRole("heading", { level: 3, name: "Tickets 4" });
744
+ const add = screen.getByRole("button", { name: "Add ticket" });
745
+ expect(heading.compareDocumentPosition(add) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
746
+ });
747
+ });
748
+
749
+ describe("DataView's cell presentations (ADR 0169 §5)", () => {
750
+ interface Group {
751
+ id: string;
752
+ name: string;
753
+ members: number;
754
+ active: boolean;
755
+ }
756
+ const GROUPS: Group[] = [
757
+ { id: "a", name: "Operations", members: 12, active: true },
758
+ { id: "b", name: "Finance", members: 3, active: false },
759
+ { id: "c", name: "Support", members: 6, active: true },
760
+ ];
761
+ const repo = () =>
762
+ new InMemoryDataViewRepository(GROUPS, {
763
+ getRowId: (g) => g.id,
764
+ getValue: (g, col) => g[col as keyof Group],
765
+ searchFields: ["name"],
766
+ });
767
+
768
+ it("puts a status dot before the cell's text, in the row's tone", async () => {
769
+ const columns: DataViewColumn<Group>[] = [
770
+ { id: "name", header: "Name", accessor: (g) => g.name },
771
+ {
772
+ id: "active",
773
+ header: "Status",
774
+ accessor: (g) => (g.active ? "Active" : "Paused"),
775
+ status: (g) => (g.active ? "success" : "neutral"),
776
+ },
777
+ ];
778
+ render(<DataView repository={repo()} columns={columns} />);
779
+ const paused = await screen.findByText("Paused");
780
+ const status = paused.closest('[data-terp="dataview-status"]')!;
781
+ const dot = status.querySelector('[data-terp="dataview-status-dot"]')!;
782
+ expect(dot).toHaveAttribute("data-tone", "neutral");
783
+ expect(dot).toHaveAttribute("aria-hidden", "true");
784
+ // The text is the word the dot stands for, and it is the cell's whole accessible text.
785
+ expect(status.textContent).toBe("Paused");
786
+ });
787
+
788
+ it("draws no dot beside a cell with no text, since the dot stands for a word", async () => {
789
+ // Mutation: drop the empty-content guard, and the empty cell gets a bare dot.
790
+ const columns: DataViewColumn<Group>[] = [
791
+ { id: "name", header: "Name", accessor: (g) => g.name },
792
+ { id: "note", header: "Note", accessor: () => null, status: () => "danger" },
793
+ ];
794
+ render(<DataView repository={repo()} columns={columns} />);
795
+ await screen.findByText("Operations");
796
+ expect(document.querySelector('[data-terp="dataview-status-dot"]')).toBeNull();
797
+ });
798
+
799
+ it("draws a numeric column as bars scaled to the largest value shown", async () => {
800
+ // Mutation: scale to the row's own value, and every bar is full.
801
+ const columns: DataViewColumn<Group>[] = [
802
+ { id: "name", header: "Name", accessor: (g) => g.name },
803
+ { id: "members", header: "Members", accessor: (g) => g.members, bar: true },
804
+ ];
805
+ render(<DataView repository={repo()} columns={columns} />);
806
+ await screen.findByText("Operations");
807
+ const meters = screen.getAllByRole("meter", { name: "Members" });
808
+ expect(meters.map((meter) => meter.getAttribute("max"))).toEqual(["12", "12", "12"]);
809
+ expect(meters.map((meter) => meter.getAttribute("aria-valuetext"))).toEqual(["12", "3", "6"]);
810
+ });
811
+
812
+ it("scales bars to a declared max, and formats the printed value", async () => {
813
+ const columns: DataViewColumn<Group>[] = [
814
+ { id: "name", header: "Name", accessor: (g) => g.name },
815
+ {
816
+ id: "members",
817
+ header: "Members",
818
+ accessor: (g) => g.members * 1000,
819
+ bar: { max: 20_000 },
820
+ },
821
+ ];
822
+ render(<DataView repository={repo()} columns={columns} />);
823
+ await screen.findByText("Operations");
824
+ const meters = screen.getAllByRole("meter", { name: "Members" });
825
+ expect(meters[0]).toHaveAttribute("max", "20000");
826
+ // A plain number in the app's locale -- grouped, where the default cell printed "12000".
827
+ expect(meters[0]).toHaveAttribute("aria-valuetext", "12,000");
828
+ });
829
+
830
+ it("prints a percent column's own rates, drawn against 100%", async () => {
831
+ // A Meter prints a percentage as the value's share of its range, so rates scaled to the
832
+ // largest shown printed 40% / 100% / 83% for 0.12 / 0.30 / 0.25. Mutation: scale a percent
833
+ // bar to the largest value again, and the printed rates are shares.
834
+ const columns: DataViewColumn<Group>[] = [
835
+ { id: "name", header: "Name", accessor: (g) => g.name },
836
+ {
837
+ id: "rate",
838
+ header: "Rate",
839
+ accessor: (g) => g.members / 40,
840
+ bar: { format: { style: "percent" } },
841
+ },
842
+ ];
843
+ render(<DataView repository={repo()} columns={columns} />);
844
+ await screen.findByText("Operations");
845
+ const meters = screen.getAllByRole("meter", { name: "Rate" });
846
+ expect(meters.map((meter) => meter.getAttribute("aria-valuetext"))).toEqual(["30%", "8%", "15%"]);
847
+ expect(meters.map((meter) => meter.getAttribute("max"))).toEqual(["1", "1", "1"]);
848
+ });
849
+
850
+ it("refuses a max beside a percent bar, which would print shares", () => {
851
+ const columns: DataViewColumn<Group>[] = [
852
+ { id: "rate", header: "Rate", accessor: (g) => g.members / 40, bar: { max: 0.5, format: { style: "percent" } } },
853
+ ];
854
+ expect(() => barMaxima(columns, GROUPS)).toThrow(/a percent bar is drawn against 100%/);
855
+ });
856
+
857
+ it("renders the same presentation in the card layout", async () => {
858
+ const original = window.matchMedia;
859
+ window.matchMedia = ((query: string) => ({
860
+ matches: true,
861
+ media: query,
862
+ onchange: null,
863
+ addEventListener: () => {},
864
+ removeEventListener: () => {},
865
+ addListener: () => {},
866
+ removeListener: () => {},
867
+ dispatchEvent: () => false,
868
+ })) as typeof window.matchMedia;
869
+ const columns: DataViewColumn<Group>[] = [
870
+ { id: "name", header: "Name", accessor: (g) => g.name, meta: { mobileSlot: "title" } },
871
+ {
872
+ id: "active",
873
+ header: "Status",
874
+ accessor: (g) => (g.active ? "Active" : "Paused"),
875
+ status: (g) => (g.active ? "success" : "neutral"),
876
+ meta: { mobileSlot: "status" },
877
+ },
878
+ ];
879
+ try {
880
+ render(<DataView repository={repo()} columns={columns} />);
881
+ await screen.findByText("Operations");
882
+ expect(document.querySelector('[data-terp="dataview-card-list"]')).not.toBeNull();
883
+ const card = screen.getByText("Paused").closest('[data-terp="dataview-card-status"]')!;
884
+ expect(card.querySelector('[data-terp="dataview-status-dot"]')).toHaveAttribute(
885
+ "data-tone",
886
+ "neutral",
887
+ );
888
+ } finally {
889
+ window.matchMedia = original;
890
+ }
891
+ });
892
+ });
893
+
894
+ describe("DataView's status dots are declared pairings", () => {
895
+ it("colours each toned dot in a pairing the contrast gate holds against the surface", async () => {
896
+ // A dot is the graphical object SC 1.4.11 asks 3:1 of, and the gate measures only what
897
+ // token-pairs.json declares. Mutation: colour the success dot with the accent, and no
898
+ // pairing holds it.
899
+ const { TERP_STYLES_CSS } = await import("../styles");
900
+ const pairs = (await import("../../../contract/token-pairs.json")).default as {
901
+ nonTextPairs: { fg?: string; bg?: string }[];
902
+ };
903
+ for (const tone of ["info", "success", "warning", "danger"]) {
904
+ const selector = `[data-terp="dataview-status-dot"][data-tone="${tone}"]`;
905
+ const at = TERP_STYLES_CSS.indexOf(`${selector} {`);
906
+ expect(at, `no rule for ${selector}`).toBeGreaterThan(-1);
907
+ const body = TERP_STYLES_CSS.slice(at, TERP_STYLES_CSS.indexOf("}", at));
908
+ const fg = /background: var\((--[a-z0-9-]+)\)/.exec(body)![1]!;
909
+ expect(
910
+ pairs.nonTextPairs.some((pair) => pair.fg === fg && pair.bg === "--color-bg-surface"),
911
+ `${tone}: ${fg} on the surface`,
912
+ ).toBe(true);
913
+ }
914
+ });
915
+ });
916
+
917
+ describe("DataView's status history cell (ADR 0169 §6)", () => {
918
+ it("draws a column as each row's recent runs, its latest ending in words", async () => {
919
+ // Mutation: drop the history branch from the shared renderer, and the column is empty.
920
+ const SUCCEEDED = { label: "Succeeded", tone: "success" as const };
921
+ const FAILED = { label: "Failed", tone: "danger" as const };
922
+ const columns: DataViewColumn<Ticket>[] = [
923
+ { id: "title", header: "Title", accessor: (t) => t.title },
924
+ {
925
+ id: "runs",
926
+ header: "Recent runs",
927
+ history: (t) =>
928
+ t.status === "open"
929
+ ? [{ label: "Mon", outcome: SUCCEEDED }, { label: "Tue", outcome: FAILED }]
930
+ : [],
931
+ },
932
+ ];
933
+ render(<DataView repository={inMemoryRepo()} columns={columns} />);
934
+ await screen.findByText("Broken printer");
935
+ const histories = document.querySelectorAll('[data-terp="status-history"]');
936
+ // Three open tickets have runs; the closed one renders no history rather than an empty one.
937
+ expect(histories).toHaveLength(3);
938
+ expect(histories[0]!.querySelector('[data-terp="status-history-latest"]')!.textContent).toBe("Failed");
939
+ });
940
+ });
@@ -4,6 +4,7 @@ import type { ReactNode } from "react";
4
4
  import { NARROW_VIEWPORT } from "../breakpoints";
5
5
  import { EmptyState } from "../EmptyState";
6
6
  import { ErrorState } from "../ErrorState";
7
+ import { useFormatNumber } from "../format";
7
8
  import type { BadgeTone } from "../ui/Badge";
8
9
  import type { UiText } from "../uiText";
9
10
  import { DataViewCardList } from "./DataViewCardList";
@@ -31,6 +32,17 @@ import type {
31
32
  const EMBEDDED_PAGE_SIZE = 10_000;
32
33
 
33
34
  interface DataViewBaseProps<T> {
35
+ /**
36
+ * The collection's name, as the panel's heading — with its count beside it once the
37
+ * repository has said how many there are (ADR 0169 §5).
38
+ *
39
+ * For a collection that is one section of a page — a record's members, a run's deliveries —
40
+ * where a heading over it was a second element the caller placed and the count was nowhere
41
+ * at all. An `<h3>`, the level `Card` gives a section, and the count is part of its name, so
42
+ * a screen reader hears "Members 12". An overview whose page title already names the
43
+ * collection leaves it off.
44
+ */
45
+ title?: UiText;
34
46
  /** Stable key for persisted view preferences; omit to keep them in memory only. */
35
47
  viewId?: string;
36
48
  /** The data access seam — DataView never fetches on its own. */
@@ -166,6 +178,7 @@ function useIsMobile(): boolean {
166
178
 
167
179
  function DataViewInner<T>(props: DataViewProps<T>) {
168
180
  const { strings, resolve } = useDataViewText();
181
+ const formatNumber = useFormatNumber();
169
182
  const embedded = props.variant === "embedded";
170
183
  // Only the compact value is expressible as an attribute; see the prop's doc comment.
171
184
  const densityAttribute = props.density;
@@ -405,6 +418,26 @@ function DataViewInner<T>(props: DataViewProps<T>) {
405
418
  );
406
419
  })();
407
420
 
421
+ // The count is part of the heading once there is one to tell. The query hook holds none
422
+ // before the first page and drops it on a failed query, so neither a load nor an error can
423
+ // put a number about unread records into the name.
424
+ const knowsCount = totalCount !== undefined;
425
+ const heading =
426
+ props.title === undefined ? null : (
427
+ <h3 data-terp="dataview-title">
428
+ {resolve(props.title)}
429
+ {/* A space, so the name reads "Members 12" rather than "Members12": the count is an
430
+ inline span and the accessible name joins inline text as written. The flex gap does
431
+ the visual spacing, and a whitespace text node in a flex box renders nothing. */}
432
+ {knowsCount && (
433
+ <>
434
+ {" "}
435
+ <span data-terp="dataview-count">{formatNumber(totalCount)}</span>
436
+ </>
437
+ )}
438
+ </h3>
439
+ );
440
+
408
441
  if (embedded) {
409
442
  // Stable inputs only: keying this on transient fetch state would pop the
410
443
  // whole band in and out on mount and on every background refetch.
@@ -418,6 +451,7 @@ function DataViewInner<T>(props: DataViewProps<T>) {
418
451
  props.toolbarTrailing !== undefined;
419
452
  return (
420
453
  <div data-terp="dataview" data-variant={variantAttribute} data-density={densityAttribute}>
454
+ {heading}
421
455
  {showsEmbeddedToolbar && (
422
456
  <DataViewToolbar<T>
423
457
  searchEnabled={props.repository.capabilities.search}
@@ -453,6 +487,7 @@ function DataViewInner<T>(props: DataViewProps<T>) {
453
487
 
454
488
  return (
455
489
  <div data-terp="dataview" data-variant={variantAttribute} data-density={densityAttribute}>
490
+ {heading}
456
491
  <DataViewToolbar<T>
457
492
  searchEnabled={props.repository.capabilities.search}
458
493
  search={state.search}
@@ -1,3 +1,4 @@
1
+ import { useMemo } from "react";
1
2
  import type { ReactNode } from "react";
2
3
 
3
4
  import type { BadgeTone } from "../ui/Badge";
@@ -5,7 +6,7 @@ import type { UiText } from "../uiText";
5
6
 
6
7
  import { DataViewExpandToggle } from "./DataViewExpandableRow";
7
8
  import { DataViewRowActions } from "./DataViewRowActions";
8
- import { useCellFormatter, useDataViewText } from "./internal";
9
+ import { barMaxima, useCellRenderer, useDataViewText } from "./internal";
9
10
  import type { DataViewColumn, DataViewRowAction } from "./types";
10
11
 
11
12
  export interface DataViewCardListProps<T> {
@@ -34,16 +35,14 @@ function slotValue<T>(
34
35
  columns: DataViewColumn<T>[],
35
36
  row: T,
36
37
  slot: "title" | "subtitle" | "status" | "date",
37
- formatCell: (value: unknown) => ReactNode,
38
+ renderCell: ReturnType<typeof useCellRenderer>,
39
+ maxima: ReadonlyMap<string, number>,
38
40
  ): ReactNode {
39
41
  const column = columns.find((candidate) => candidate.meta?.mobileSlot === slot);
40
42
  if (column === undefined) {
41
43
  return null;
42
44
  }
43
- if (column.cell !== undefined) {
44
- return column.cell(row);
45
- }
46
- return formatCell(column.accessor?.(row));
45
+ return renderCell(column, row, maxima);
47
46
  }
48
47
 
49
48
  /**
@@ -54,6 +53,7 @@ function slotValue<T>(
54
53
  */
55
54
  export function DataViewCardList<T>(props: DataViewCardListProps<T>) {
56
55
  const { strings, resolve, format } = useDataViewText();
56
+ const maxima = useMemo(() => barMaxima(props.columns, props.rows), [props.columns, props.rows]);
57
57
 
58
58
  return (
59
59
  <ul data-terp="dataview-card-list">
@@ -105,7 +105,7 @@ export function DataViewCardList<T>(props: DataViewCardListProps<T>) {
105
105
  {props.renderCard !== undefined ? (
106
106
  props.renderCard(row)
107
107
  ) : (
108
- <DefaultCardBody row={row} columns={props.columns} />
108
+ <DefaultCardBody row={row} columns={props.columns} maxima={maxima} />
109
109
  )}
110
110
  </div>
111
111
  {props.rowActions !== undefined && (
@@ -130,12 +130,20 @@ export function DataViewCardList<T>(props: DataViewCardListProps<T>) {
130
130
  );
131
131
  }
132
132
 
133
- function DefaultCardBody<T>({ row, columns }: { row: T; columns: DataViewColumn<T>[] }) {
134
- const formatCell = useCellFormatter();
135
- const title = slotValue(columns, row, "title", formatCell);
136
- const subtitle = slotValue(columns, row, "subtitle", formatCell);
137
- const status = slotValue(columns, row, "status", formatCell);
138
- const date = slotValue(columns, row, "date", formatCell);
133
+ function DefaultCardBody<T>({
134
+ row,
135
+ columns,
136
+ maxima,
137
+ }: {
138
+ row: T;
139
+ columns: DataViewColumn<T>[];
140
+ maxima: ReadonlyMap<string, number>;
141
+ }) {
142
+ const renderCell = useCellRenderer();
143
+ const title = slotValue(columns, row, "title", renderCell, maxima);
144
+ const subtitle = slotValue(columns, row, "subtitle", renderCell, maxima);
145
+ const status = slotValue(columns, row, "status", renderCell, maxima);
146
+ const date = slotValue(columns, row, "date", renderCell, maxima);
139
147
  return (
140
148
  <div data-terp="dataview-card-fields">
141
149
  <div data-terp="dataview-card-heading">
@@ -1,4 +1,4 @@
1
- import { useCallback, useEffect, useRef, useState } from "react";
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
2
  import type { ReactNode } from "react";
3
3
 
4
4
  import { injectTerpStyles } from "../styles";
@@ -8,7 +8,7 @@ import { DataViewExpandToggle, DataViewExpandableRow } from "./DataViewExpandabl
8
8
  import { DataViewRowActions } from "./DataViewRowActions";
9
9
  import type { DataViewRowActionsLayout } from "./DataViewRowActions";
10
10
  import { SortAscGlyph, SortDescGlyph, SortNoneGlyph } from "./glyphs";
11
- import { useCellFormatter, useDataViewText } from "./internal";
11
+ import { barMaxima, useCellRenderer, useDataViewText } from "./internal";
12
12
 
13
13
  injectTerpStyles();
14
14
  import type {
@@ -59,7 +59,8 @@ export interface DataViewTableProps<T> {
59
59
  */
60
60
  export function DataViewTable<T>(props: DataViewTableProps<T>) {
61
61
  const { strings, resolve, format } = useDataViewText();
62
- const formatCell = useCellFormatter();
62
+ const renderCell = useCellRenderer();
63
+ const maxima = useMemo(() => barMaxima(props.columns, props.rows), [props.columns, props.rows]);
63
64
  const tableRef = useRef<HTMLTableElement>(null);
64
65
 
65
66
  // Live widths during a resize drag only — persisted once, on pointer-up.
@@ -275,9 +276,7 @@ export function DataViewTable<T>(props: DataViewTableProps<T>) {
275
276
  }}
276
277
  />
277
278
  )}
278
- {column.cell !== undefined
279
- ? column.cell(row)
280
- : formatCell(column.accessor?.(row))}
279
+ {renderCell(column, row, maxima)}
281
280
  </td>
282
281
  ))}
283
282
  {hasActions && (
@@ -130,6 +130,24 @@ versioned envelope; corrupt data falls back to defaults) and
130
130
  only a preference the algorithm shrinks to fit, so the px hint this replaced did nothing
131
131
  at all. A user resize replaces the step outright rather than competing with it: a resized
132
132
  column stops carrying the attribute, so the floor can never spring a drag back.
133
+ - **A titled collection** (ADR 0169 §5): `title` renders the collection's heading — an
134
+ `<h3>`, the level a `Card` gives a section — with its count beside it once the repository has
135
+ said how many there are: not while the first page loads, and not over an error. The count is
136
+ part of the heading's name ("Members 12") and prints in the app's locale. Use it for a
137
+ collection that is one section of a page; an overview whose page title already names the
138
+ collection leaves it off.
139
+ - **Cell presentations** (ADR 0169 §5), on a column and the same in the table and the cards:
140
+ `status: (row) => tone | null` puts a dot of that tone before the cell's text — the quiet
141
+ form of a status column, where most rows are fine and a pill on every one is noise; the text
142
+ is the word the dot stands for, so an empty cell gets none. `bar: true` (or
143
+ `{ max, format }`) draws the column's number as a `Meter` scaled to the largest value among
144
+ the rows shown — or to `max` — with the value printed beside it in the app's locale; a row
145
+ whose value is not a number renders as text, and a `cell` renderer is not used for a bar. A
146
+ percent column is drawn against 100%, its rates' own range, because a `Meter` prints a
147
+ percentage as the share of its range; a `max` beside a percent format is refused.
148
+ `history: (row) => runs` draws each row's recent runs as a `StatusHistory` — one cell per run,
149
+ the latest ending in words — for a collection of things that run; a row with no runs renders
150
+ none.
133
151
  - **Row tone**: `getRowTone={(row) => tone | null}` marks the *row* as being in a
134
152
  state (a refused link, a failed run) — the right altitude when the verdict belongs
135
153
  to the record, not to one of its cells. The row/card is tinted with the tone's soft
@@ -23,6 +23,7 @@ export type {
23
23
  DataViewState,
24
24
  ViewStateRepository,
25
25
  ColumnWidth,
26
+ DataViewBar,
26
27
  DataViewColumn,
27
28
  DataViewColumnMeta,
28
29
  DataViewDensity,