@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
@@ -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(() => {
@@ -599,10 +600,16 @@ describe("DataView localisation", () => {
599
600
  });
600
601
 
601
602
  it("speaks the app's locale without a strings prop, and follows a switch", async () => {
603
+ // A smallest page of two, so four rows have pages and the page-size control is offered.
602
604
  render(
603
605
  <LocaleProvider locales={{ en: LOCALE_EN, nl: LOCALE_NL }}>
604
606
  <LanguageSwitcher />
605
- <DataView repository={inMemoryRepo()} columns={COLUMNS} />
607
+ <DataView
608
+ repository={inMemoryRepo()}
609
+ columns={COLUMNS}
610
+ pageSizeOptions={[2, 10]}
611
+ initialPageSize={10}
612
+ />
606
613
  </LocaleProvider>,
607
614
  );
608
615
  expect(await screen.findByText("1–4 of 4 results")).toBeInTheDocument();
@@ -683,3 +690,298 @@ describe("DataView localisation", () => {
683
690
  expect(screen.getByRole("button", { name: "Volgende pagina" })).toBeInTheDocument();
684
691
  });
685
692
  });
693
+
694
+ describe("DataView as a panel (ADR 0169 §5)", () => {
695
+ it("names itself in a heading and counts its results once it has read them", async () => {
696
+ // Mutation: drop the count from the heading, and the name stays "Tickets".
697
+ render(<DataView title="Tickets" repository={inMemoryRepo()} columns={COLUMNS} />);
698
+ // No number while the first page loads: the count is a claim, and nothing was read yet.
699
+ expect(screen.getByRole("heading", { level: 3, name: "Tickets" })).toBeInTheDocument();
700
+ expect(await screen.findByRole("heading", { level: 3, name: "Tickets 4" })).toBeInTheDocument();
701
+ });
702
+
703
+ it("prints the count in the app's locale", async () => {
704
+ const many = Array.from({ length: 1234 }, (_, index) => ({
705
+ id: String(index),
706
+ title: `Ticket ${index}`,
707
+ status: "open",
708
+ }));
709
+ render(
710
+ <LocaleProvider locales={{ nl: LOCALE_NL, en: LOCALE_EN }} defaultLocale="nl">
711
+ <DataView title="Tickets" repository={inMemoryRepo(many)} columns={COLUMNS} />
712
+ </LocaleProvider>,
713
+ );
714
+ expect(await screen.findByRole("heading", { level: 3, name: "Tickets 1.234" })).toBeInTheDocument();
715
+ });
716
+
717
+ it("claims no count over an error, even with an earlier count in hand", async () => {
718
+ // A failed query sets the error and leaves the last total where it was, so after one good
719
+ // page and one failed search the view still holds "4" -- a number about rows it is no
720
+ // longer showing. Mutation: drop the error from the condition, and the heading keeps "4".
721
+ let calls = 0;
722
+ const base = inMemoryRepo();
723
+ const flaky: DataViewRepository<Ticket> = {
724
+ capabilities: base.capabilities,
725
+ getRowId: (t) => t.id,
726
+ query: (query) =>
727
+ calls++ === 0 ? base.query(query) : Promise.reject(new Error("upstream is down")),
728
+ };
729
+ render(<DataView title="Tickets" repository={flaky} columns={COLUMNS} searchDebounceMs={0} />);
730
+ await screen.findByRole("heading", { level: 3, name: "Tickets 4" });
731
+ fireEvent.change(screen.getByRole("searchbox"), { target: { value: "printer" } });
732
+ await waitFor(() =>
733
+ expect(document.querySelector('[data-terp="dataview-error"]')).not.toBeNull(),
734
+ );
735
+ expect(screen.getByRole("heading", { level: 3, name: "Tickets" })).toBeInTheDocument();
736
+ expect(document.querySelector('[data-terp="dataview-count"]')).toBeNull();
737
+ });
738
+
739
+ it("titles an embedded view too, above its toolbar", async () => {
740
+ render(
741
+ <DataView
742
+ title="Tickets"
743
+ variant="embedded"
744
+ repository={inMemoryRepo()}
745
+ columns={COLUMNS}
746
+ toolbarContent={<button type="button">Add ticket</button>}
747
+ />,
748
+ );
749
+ const heading = await screen.findByRole("heading", { level: 3, name: "Tickets 4" });
750
+ const add = screen.getByRole("button", { name: "Add ticket" });
751
+ expect(heading.compareDocumentPosition(add) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
752
+ });
753
+ });
754
+
755
+ describe("DataView's cell presentations (ADR 0169 §5)", () => {
756
+ interface Group {
757
+ id: string;
758
+ name: string;
759
+ members: number;
760
+ active: boolean;
761
+ }
762
+ const GROUPS: Group[] = [
763
+ { id: "a", name: "Operations", members: 12, active: true },
764
+ { id: "b", name: "Finance", members: 3, active: false },
765
+ { id: "c", name: "Support", members: 6, active: true },
766
+ ];
767
+ const repo = () =>
768
+ new InMemoryDataViewRepository(GROUPS, {
769
+ getRowId: (g) => g.id,
770
+ getValue: (g, col) => g[col as keyof Group],
771
+ searchFields: ["name"],
772
+ });
773
+
774
+ it("puts a status dot before the cell's text, in the row's tone", async () => {
775
+ const columns: DataViewColumn<Group>[] = [
776
+ { id: "name", header: "Name", accessor: (g) => g.name },
777
+ {
778
+ id: "active",
779
+ header: "Status",
780
+ accessor: (g) => (g.active ? "Active" : "Paused"),
781
+ status: (g) => (g.active ? "success" : "neutral"),
782
+ },
783
+ ];
784
+ render(<DataView repository={repo()} columns={columns} />);
785
+ const paused = await screen.findByText("Paused");
786
+ const status = paused.closest('[data-terp="dataview-status"]')!;
787
+ const dot = status.querySelector('[data-terp="dataview-status-dot"]')!;
788
+ expect(dot).toHaveAttribute("data-tone", "neutral");
789
+ expect(dot).toHaveAttribute("aria-hidden", "true");
790
+ // The text is the word the dot stands for, and it is the cell's whole accessible text.
791
+ expect(status.textContent).toBe("Paused");
792
+ });
793
+
794
+ it("draws no dot beside a cell with no text, since the dot stands for a word", async () => {
795
+ // Mutation: drop the empty-content guard, and the empty cell gets a bare dot.
796
+ const columns: DataViewColumn<Group>[] = [
797
+ { id: "name", header: "Name", accessor: (g) => g.name },
798
+ { id: "note", header: "Note", accessor: () => null, status: () => "danger" },
799
+ ];
800
+ render(<DataView repository={repo()} columns={columns} />);
801
+ await screen.findByText("Operations");
802
+ expect(document.querySelector('[data-terp="dataview-status-dot"]')).toBeNull();
803
+ });
804
+
805
+ it("draws a numeric column as bars scaled to the largest value shown", async () => {
806
+ // Mutation: scale to the row's own value, and every bar is full.
807
+ const columns: DataViewColumn<Group>[] = [
808
+ { id: "name", header: "Name", accessor: (g) => g.name },
809
+ { id: "members", header: "Members", accessor: (g) => g.members, bar: true },
810
+ ];
811
+ render(<DataView repository={repo()} columns={columns} />);
812
+ await screen.findByText("Operations");
813
+ const meters = screen.getAllByRole("meter", { name: "Members" });
814
+ expect(meters.map((meter) => meter.getAttribute("max"))).toEqual(["12", "12", "12"]);
815
+ expect(meters.map((meter) => meter.getAttribute("aria-valuetext"))).toEqual(["12", "3", "6"]);
816
+ });
817
+
818
+ it("scales bars to a declared max, and formats the printed value", async () => {
819
+ const columns: DataViewColumn<Group>[] = [
820
+ { id: "name", header: "Name", accessor: (g) => g.name },
821
+ {
822
+ id: "members",
823
+ header: "Members",
824
+ accessor: (g) => g.members * 1000,
825
+ bar: { max: 20_000 },
826
+ },
827
+ ];
828
+ render(<DataView repository={repo()} columns={columns} />);
829
+ await screen.findByText("Operations");
830
+ const meters = screen.getAllByRole("meter", { name: "Members" });
831
+ expect(meters[0]).toHaveAttribute("max", "20000");
832
+ // A plain number in the app's locale -- grouped, where the default cell printed "12000".
833
+ expect(meters[0]).toHaveAttribute("aria-valuetext", "12,000");
834
+ });
835
+
836
+ it("prints a percent column's own rates, drawn against 100%", async () => {
837
+ // A Meter prints a percentage as the value's share of its range, so rates scaled to the
838
+ // largest shown printed 40% / 100% / 83% for 0.12 / 0.30 / 0.25. Mutation: scale a percent
839
+ // bar to the largest value again, and the printed rates are shares.
840
+ const columns: DataViewColumn<Group>[] = [
841
+ { id: "name", header: "Name", accessor: (g) => g.name },
842
+ {
843
+ id: "rate",
844
+ header: "Rate",
845
+ accessor: (g) => g.members / 40,
846
+ bar: { format: { style: "percent" } },
847
+ },
848
+ ];
849
+ render(<DataView repository={repo()} columns={columns} />);
850
+ await screen.findByText("Operations");
851
+ const meters = screen.getAllByRole("meter", { name: "Rate" });
852
+ expect(meters.map((meter) => meter.getAttribute("aria-valuetext"))).toEqual(["30%", "8%", "15%"]);
853
+ expect(meters.map((meter) => meter.getAttribute("max"))).toEqual(["1", "1", "1"]);
854
+ });
855
+
856
+ it("refuses a max beside a percent bar, which would print shares", () => {
857
+ const columns: DataViewColumn<Group>[] = [
858
+ { id: "rate", header: "Rate", accessor: (g) => g.members / 40, bar: { max: 0.5, format: { style: "percent" } } },
859
+ ];
860
+ expect(() => barMaxima(columns, GROUPS)).toThrow(/a percent bar is drawn against 100%/);
861
+ });
862
+
863
+ it("renders the same presentation in the card layout", async () => {
864
+ const original = window.matchMedia;
865
+ window.matchMedia = ((query: string) => ({
866
+ matches: true,
867
+ media: query,
868
+ onchange: null,
869
+ addEventListener: () => {},
870
+ removeEventListener: () => {},
871
+ addListener: () => {},
872
+ removeListener: () => {},
873
+ dispatchEvent: () => false,
874
+ })) as typeof window.matchMedia;
875
+ const columns: DataViewColumn<Group>[] = [
876
+ { id: "name", header: "Name", accessor: (g) => g.name, meta: { mobileSlot: "title" } },
877
+ {
878
+ id: "active",
879
+ header: "Status",
880
+ accessor: (g) => (g.active ? "Active" : "Paused"),
881
+ status: (g) => (g.active ? "success" : "neutral"),
882
+ meta: { mobileSlot: "status" },
883
+ },
884
+ ];
885
+ try {
886
+ render(<DataView repository={repo()} columns={columns} />);
887
+ await screen.findByText("Operations");
888
+ expect(document.querySelector('[data-terp="dataview-card-list"]')).not.toBeNull();
889
+ const card = screen.getByText("Paused").closest('[data-terp="dataview-card-status"]')!;
890
+ expect(card.querySelector('[data-terp="dataview-status-dot"]')).toHaveAttribute(
891
+ "data-tone",
892
+ "neutral",
893
+ );
894
+ } finally {
895
+ window.matchMedia = original;
896
+ }
897
+ });
898
+ });
899
+
900
+ describe("DataView's status dots are declared pairings", () => {
901
+ it("colours each toned dot in a pairing the contrast gate holds against the surface", async () => {
902
+ // A dot is the graphical object SC 1.4.11 asks 3:1 of, and the gate measures only what
903
+ // token-pairs.json declares. Mutation: colour the success dot with the accent, and no
904
+ // pairing holds it.
905
+ const { TERP_STYLES_CSS } = await import("../styles");
906
+ const pairs = (await import("../../../contract/token-pairs.json")).default as {
907
+ nonTextPairs: { fg?: string; bg?: string }[];
908
+ };
909
+ for (const tone of ["info", "success", "warning", "danger"]) {
910
+ const selector = `[data-terp="dataview-status-dot"][data-tone="${tone}"]`;
911
+ const at = TERP_STYLES_CSS.indexOf(`${selector} {`);
912
+ expect(at, `no rule for ${selector}`).toBeGreaterThan(-1);
913
+ const body = TERP_STYLES_CSS.slice(at, TERP_STYLES_CSS.indexOf("}", at));
914
+ const fg = /background: var\((--[a-z0-9-]+)\)/.exec(body)![1]!;
915
+ expect(
916
+ pairs.nonTextPairs.some((pair) => pair.fg === fg && pair.bg === "--color-bg-surface"),
917
+ `${tone}: ${fg} on the surface`,
918
+ ).toBe(true);
919
+ }
920
+ });
921
+ });
922
+
923
+ describe("DataView's status history cell (ADR 0169 §6)", () => {
924
+ it("draws a column as each row's recent runs, its latest ending in words", async () => {
925
+ // Mutation: drop the history branch from the shared renderer, and the column is empty.
926
+ const SUCCEEDED = { label: "Succeeded", tone: "success" as const };
927
+ const FAILED = { label: "Failed", tone: "danger" as const };
928
+ const columns: DataViewColumn<Ticket>[] = [
929
+ { id: "title", header: "Title", accessor: (t) => t.title },
930
+ {
931
+ id: "runs",
932
+ header: "Recent runs",
933
+ history: (t) =>
934
+ t.status === "open"
935
+ ? [{ label: "Mon", outcome: SUCCEEDED }, { label: "Tue", outcome: FAILED }]
936
+ : [],
937
+ },
938
+ ];
939
+ render(<DataView repository={inMemoryRepo()} columns={columns} />);
940
+ await screen.findByText("Broken printer");
941
+ const histories = document.querySelectorAll('[data-terp="status-history"]');
942
+ // Three open tickets have runs; the closed one renders no history rather than an empty one.
943
+ expect(histories).toHaveLength(3);
944
+ expect(histories[0]!.querySelector('[data-terp="status-history-latest"]')!.textContent).toBe("Failed");
945
+ });
946
+ });
947
+
948
+ describe("DataView page size", () => {
949
+ it("offers no page size for a collection that fits on its smallest page", async () => {
950
+ render(<DataView repository={inMemoryRepo()} columns={COLUMNS} />);
951
+ await screen.findByText("Broken printer");
952
+ // Four rows against a smallest page of ten: the control changed nothing. Mutation:
953
+ // offering it at any size.
954
+ expect(screen.queryByRole("button", { name: "Rows per page" })).not.toBeInTheDocument();
955
+ // The controls that work at any size stay.
956
+ expect(screen.getByRole("button", { name: "View options" })).toBeInTheDocument();
957
+ });
958
+
959
+ it("offers it where the rows are more than the smallest page holds", async () => {
960
+ render(<DataView repository={inMemoryRepo()} columns={COLUMNS} pageSizeOptions={[3, 10]} />);
961
+ await screen.findByText("Broken printer");
962
+ // Mutation: comparing with the largest option. (The page in force is 3 here too, so the
963
+ // test below is the one that tells it apart from the smallest option.)
964
+ expect(screen.getByRole("button", { name: "Rows per page" })).toBeInTheDocument();
965
+ });
966
+
967
+ it("offers it while the page in force is smaller than every option, and the view pages", async () => {
968
+ // Four rows on pages of three: two pages, and the default options all start at ten.
969
+ // Mutation: comparing with the smallest option alone, which hid the control and left the
970
+ // view paging with no way to show the rows at once.
971
+ render(<DataView repository={inMemoryRepo()} columns={COLUMNS} initialPageSize={3} />);
972
+ await screen.findByText("Broken printer");
973
+ expect(screen.getByRole("button", { name: "Rows per page" })).toBeInTheDocument();
974
+ });
975
+
976
+ it("keeps it while the total is not known yet", () => {
977
+ const repository: DataViewRepository<Ticket> = {
978
+ query: () => new Promise(() => {}),
979
+ getRowId: (ticket) => ticket.id,
980
+ capabilities: { serverSide: true, search: false, searchScope: false },
981
+ };
982
+ render(<DataView repository={repository} columns={COLUMNS} />);
983
+ // Mutation: reading an unknown total as none, which takes the control away during every
984
+ // first load and puts it back when a large collection arrives.
985
+ expect(screen.getByRole("button", { name: "Rows per page" })).toBeInTheDocument();
986
+ });
987
+ });
@@ -4,13 +4,14 @@ 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";
10
11
  import { DataViewPagination } from "./DataViewPagination";
11
12
  import type { DataViewRowActionsLayout } from "./DataViewRowActions";
12
13
  import { DataViewTable } from "./DataViewTable";
13
- import { DataViewToolbar } from "./DataViewToolbar";
14
+ import { DATA_VIEW_PAGE_SIZES, DataViewToolbar } from "./DataViewToolbar";
14
15
  import { useDataViewQuery } from "./hooks/useDataViewQuery";
15
16
  import { useDataViewState } from "./hooks/useDataViewState";
16
17
  import type { DataViewControlledQuery } from "./hooks/useDataViewState";
@@ -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}
@@ -451,8 +485,22 @@ function DataViewInner<T>(props: DataViewProps<T>) {
451
485
  );
452
486
  }
453
487
 
488
+ // A collection that fits on its smallest page has nothing to page through, so it is offered no
489
+ // page size: above a one-row table the control changed nothing and still led the toolbar.
490
+ // Only once the total is known, so the control does not blink out while the first page loads;
491
+ // the view and column controls stay at every size, since they work on any collection and a
492
+ // toolbar that rearranged itself as a filter narrowed the rows would move under the pointer.
493
+ // The page in force counts too: `initialPageSize`, a restored view or a server query can set
494
+ // one smaller than every option, and a view that pages must keep the control that ends it.
495
+ const smallestPage = Math.min(
496
+ ...(props.pageSizeOptions ?? DATA_VIEW_PAGE_SIZES),
497
+ state.pagination.pageSize,
498
+ );
499
+ const fitsSmallestPage = totalCount !== undefined && totalCount <= smallestPage;
500
+
454
501
  return (
455
502
  <div data-terp="dataview" data-variant={variantAttribute} data-density={densityAttribute}>
503
+ {heading}
456
504
  <DataViewToolbar<T>
457
505
  searchEnabled={props.repository.capabilities.search}
458
506
  search={state.search}
@@ -472,8 +520,10 @@ function DataViewInner<T>(props: DataViewProps<T>) {
472
520
  onLayoutChange={setManualLayout}
473
521
  pageSize={state.pagination.pageSize}
474
522
  pageSizeOptions={props.pageSizeOptions}
475
- onPageSizeChange={(pageSize) =>
476
- state.setPagination({ pageIndex: 0, pageSize })
523
+ onPageSizeChange={
524
+ fitsSmallestPage
525
+ ? undefined
526
+ : (pageSize) => state.setPagination({ pageIndex: 0, pageSize })
477
527
  }
478
528
  selectedCount={selectedIds.size}
479
529
  totalCount={totalCount ?? 0}
@@ -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 && (
@@ -44,6 +44,9 @@ export interface DataViewToolbarProps<T> {
44
44
  trailing?: ReactNode;
45
45
  }
46
46
 
47
+ /** The page sizes a view offers when its caller names none. */
48
+ export const DATA_VIEW_PAGE_SIZES: readonly number[] = [10, 25, 50, 100];
49
+
47
50
  /**
48
51
  * The DataView toolbar. In its normal mode it hosts search, caller filter controls,
49
52
  * the page-size selector, the table/cards toggle and the column-settings menu; when
@@ -201,7 +204,7 @@ export function DataViewToolbar<T>(props: DataViewToolbarProps<T>) {
201
204
  }
202
205
  >
203
206
  {(close) =>
204
- (props.pageSizeOptions ?? [10, 25, 50, 100]).map((option) => (
207
+ (props.pageSizeOptions ?? DATA_VIEW_PAGE_SIZES).map((option) => (
205
208
  <DataViewMenuItem
206
209
  key={option}
207
210
  label={String(option)}
@@ -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,