@nickrobison/colophon-table 0.0.0-stage → 0.1.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 (59) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +55 -2
  3. package/package.json +72 -3
  4. package/src/components/CphSkeleton.test.tsx +145 -0
  5. package/src/components/CphSkeleton.tsx +42 -0
  6. package/src/components/CphTableEmpty.test.tsx +122 -0
  7. package/src/components/CphTableEmpty.tsx +42 -0
  8. package/src/components/DataTable/CphDataTable.test.tsx +408 -0
  9. package/src/components/DataTable/CphDataTable.tsx +121 -0
  10. package/src/components/DataTable/pinnedOffsets.ts +94 -0
  11. package/src/components/FilterMultiSelect/CphTableFilterMultiSelect.test.tsx +172 -0
  12. package/src/components/FilterMultiSelect/CphTableFilterMultiSelect.tsx +132 -0
  13. package/src/components/FilterRange/CphTableFilterRange.test.tsx +154 -0
  14. package/src/components/FilterRange/CphTableFilterRange.tsx +109 -0
  15. package/src/components/MobileCards/CphMobileCards.test.tsx +174 -0
  16. package/src/components/MobileCards/CphMobileCards.tsx +117 -0
  17. package/src/components/Pagination/CphCursorPagination.test.tsx +51 -0
  18. package/src/components/Pagination/CphCursorPagination.tsx +74 -0
  19. package/src/components/Pagination/CphPagination.test.tsx +98 -0
  20. package/src/components/Pagination/CphPagination.tsx +94 -0
  21. package/src/components/RowDetail/CphRowDetail.test.tsx +182 -0
  22. package/src/components/RowDetail/CphRowDetail.tsx +66 -0
  23. package/src/components/SimpleTable/CphSimpleTable.test.tsx +235 -0
  24. package/src/components/SimpleTable/CphSimpleTable.tsx +369 -0
  25. package/src/components/SortFilterSheet/CphSortFilterSheet.test.tsx +156 -0
  26. package/src/components/SortFilterSheet/CphSortFilterSheet.tsx +131 -0
  27. package/src/components/StatusChip/CphStatusChip.test.tsx +43 -0
  28. package/src/components/StatusChip/CphStatusChip.tsx +33 -0
  29. package/src/components/Summary/CphTableSummary.test.tsx +486 -0
  30. package/src/components/Summary/CphTableSummary.tsx +130 -0
  31. package/src/components/TableHead/CphTableHead.test.tsx +52 -0
  32. package/src/components/TableHead/CphTableHead.tsx +129 -0
  33. package/src/components/TableHead/HeaderCell.test.tsx +880 -0
  34. package/src/components/TableHead/HeaderCell.tsx +221 -0
  35. package/src/components/TableRow/Cell.test.tsx +306 -0
  36. package/src/components/TableRow/Cell.tsx +74 -0
  37. package/src/components/TableRow/CphTableRow.test.tsx +90 -0
  38. package/src/components/TableRow/CphTableRow.tsx +17 -0
  39. package/src/components/Toolbar/CphToolbar.test.tsx +150 -0
  40. package/src/components/Toolbar/CphToolbar.tsx +138 -0
  41. package/src/components.css +593 -0
  42. package/src/index.ts +69 -0
  43. package/src/table/cellRenderers.tsx +88 -0
  44. package/src/table/column.test.tsx +277 -0
  45. package/src/table/column.tsx +36 -0
  46. package/src/table/features.ts +69 -0
  47. package/src/table/pageSize.test.ts +128 -0
  48. package/src/table/pageSize.ts +47 -0
  49. package/src/table/summary.test.tsx +446 -0
  50. package/src/table/summary.ts +94 -0
  51. package/src/table/useCphTable.ts +90 -0
  52. package/src/table/useCphTableState.test.tsx +697 -0
  53. package/src/table/useCphTableState.ts +412 -0
  54. package/src/table-tokens.css +48 -0
  55. package/src/theme/CphTableDensity.test.tsx +53 -0
  56. package/src/theme/CphTableDensity.tsx +24 -0
  57. package/src/theme/cphTableDensityContext.ts +24 -0
  58. package/src/utils/composeClassName.test.ts +26 -0
  59. package/src/utils/composeClassName.ts +28 -0
@@ -0,0 +1,33 @@
1
+ import { CphBadge, type CphBadgeTone } from "@nickrobison/colophon";
2
+ import type { ReactElement, ReactNode } from "react";
3
+
4
+ /** Mirrors `CphBadgeTone`; kept as an alias so callers need not import core directly. */
5
+ export type CphStatusTone = CphBadgeTone;
6
+
7
+ export interface CphStatusChipProps {
8
+ children: ReactNode;
9
+ /** Defaults to `"neutral"`. */
10
+ tone?: CphStatusTone;
11
+ className?: string;
12
+ }
13
+
14
+ /**
15
+ * A status value rendered as a small inline chip.
16
+ *
17
+ * The coloured dot is `aria-hidden`, so the status is carried entirely by the label
18
+ * text. That is deliberate: the Tables Spec forbids conveying status by colour alone,
19
+ * and red/green are indistinguishable to many colour-blind users. Any tone change here
20
+ * must keep the text present.
21
+ */
22
+ export function CphStatusChip({
23
+ children,
24
+ tone = "neutral",
25
+ className = "",
26
+ }: Readonly<CphStatusChipProps>): ReactElement {
27
+ return (
28
+ <CphBadge tone={tone} className={`cph-table__chip ${className}`}>
29
+ <span aria-hidden="true" className="cph-table__chip-dot" />
30
+ {children}
31
+ </CphBadge>
32
+ );
33
+ }
@@ -0,0 +1,486 @@
1
+ import type { RowData, Table } from "@tanstack/react-table";
2
+ import { render, screen } from "@testing-library/react";
3
+ import { describe, expect, it, vi } from "vitest";
4
+
5
+ import type { CphColumnMeta } from "../../table/column";
6
+ import type { CphTableFeatures } from "../../table/features";
7
+ import { PinnedOffsetsContext } from "../DataTable/pinnedOffsets";
8
+ import { CphTableSummary } from "./CphTableSummary";
9
+
10
+ const summaryOffsets = {
11
+ offsets: new Map([
12
+ ["value", { left: 50, isLast: true }],
13
+ ["count", { left: 0, isLast: true, right: 30 }],
14
+ ]),
15
+ };
16
+ const sparseSummaryOffsets = {
17
+ offsets: new Map([
18
+ ["value", { left: 50, isLast: true }],
19
+ ["count", { left: 0, isLast: true }],
20
+ ]),
21
+ };
22
+
23
+ /**
24
+ * Creates a minimal mock TanStack Table instance for testing.
25
+ */
26
+ function createMockTable(
27
+ overrides: Partial<{
28
+ leafColumns: Array<{
29
+ id: string;
30
+ getIsVisible: () => boolean;
31
+ getIsPinned: () => "start" | "end" | false;
32
+ columnDef: { meta?: CphColumnMeta };
33
+ getAggregationValue: (options: { rows: unknown[] }) => unknown;
34
+ }>;
35
+ filteredRows: unknown[];
36
+ }>,
37
+ ): Table<CphTableFeatures, RowData> {
38
+ const defaultLeafColumns = [
39
+ {
40
+ id: "name",
41
+ getIsVisible: () => true,
42
+ getIsPinned: () => "start" as const,
43
+ columnDef: { meta: { numeric: false } },
44
+ getAggregationValue: vi.fn(() => null),
45
+ },
46
+ {
47
+ id: "value",
48
+ getIsVisible: () => true,
49
+ getIsPinned: () => false as const,
50
+ columnDef: {
51
+ meta: {
52
+ aggregate: "sum" as const,
53
+ numeric: true,
54
+ format: (v: unknown) => Number(v).toLocaleString("en-US"),
55
+ },
56
+ },
57
+ getAggregationValue: vi.fn(({ rows }) =>
58
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0),
59
+ ),
60
+ },
61
+ {
62
+ id: "count",
63
+ getIsVisible: () => true,
64
+ getIsPinned: () => false as const,
65
+ columnDef: { meta: { aggregate: "count" as const, numeric: true } },
66
+ getAggregationValue: vi.fn(({ rows }) => rows.length),
67
+ },
68
+ ];
69
+
70
+ const leafColumns = overrides.leafColumns ?? defaultLeafColumns;
71
+ const filteredRows = overrides.filteredRows ?? [
72
+ { name: "A", value: 10, count: 1 },
73
+ { name: "B", value: 20, count: 1 },
74
+ { name: "C", value: 30, count: 1 },
75
+ ];
76
+
77
+ return {
78
+ getAllLeafColumns: vi.fn(() => leafColumns),
79
+ getFilteredRowModel: vi.fn(() => ({ rows: filteredRows })),
80
+ } as unknown as Table<CphTableFeatures, RowData>;
81
+ }
82
+
83
+ describe("CphTableSummary", () => {
84
+ it("renders NO tfoot when showSummary is false", () => {
85
+ const table = createMockTable({});
86
+ render(<CphTableSummary table={table} showSummary={false} />);
87
+ expect(screen.queryByRole("rowgroup", { name: /summary/i })).not.toBeInTheDocument();
88
+ expect(screen.queryByTestId("summary")).not.toBeInTheDocument();
89
+ // More direct check: no tfoot element at all
90
+ const tfoot = document.querySelector("tfoot");
91
+ expect(tfoot).toBeNull();
92
+ });
93
+
94
+ it("renders NO tfoot when showSummary is absent", () => {
95
+ const table = createMockTable({});
96
+ render(<CphTableSummary table={table} />);
97
+ const tfoot = document.querySelector("tfoot");
98
+ expect(tfoot).toBeNull();
99
+ });
100
+
101
+ it("renders tfoot with per-column cells when showSummary is true", () => {
102
+ const table = createMockTable({});
103
+ render(<CphTableSummary table={table} showSummary={true} totalCount={10} />);
104
+
105
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
106
+ expect(tfoot).toBeInTheDocument();
107
+ expect(tfoot).toHaveClass("cph-table__summary");
108
+
109
+ // Should have 3 cells (th + 2 tds) for 3 leaf columns
110
+ const cells = tfoot.querySelectorAll("th, td");
111
+ expect(cells).toHaveLength(3);
112
+
113
+ // First cell is th with scope="row"
114
+ const th = tfoot.querySelector("th[scope='row']");
115
+ expect(th).toBeInTheDocument();
116
+ expect(th).toHaveClass("cph-table__pinned"); // first column is pinned
117
+
118
+ // Second cell is td with numeric class
119
+ const tds = tfoot.querySelectorAll("td");
120
+ expect(tds).toHaveLength(2);
121
+ expect(tds[0]).toHaveClass("cph-table__numeric"); // value column is numeric
122
+ expect(tds[1]).toHaveClass("cph-table__numeric"); // count column is numeric
123
+ });
124
+
125
+ it("shows sum of FILTERED rows for sum aggregate", () => {
126
+ const filteredRows = [
127
+ { name: "A", value: 10 },
128
+ { name: "B", value: 20 },
129
+ { name: "C", value: 30 },
130
+ ];
131
+ const table = createMockTable({
132
+ filteredRows,
133
+ leafColumns: [
134
+ {
135
+ id: "name",
136
+ getIsVisible: () => true,
137
+ getIsPinned: () => "start" as const,
138
+ columnDef: { meta: { numeric: false } },
139
+ getAggregationValue: vi.fn(() => null),
140
+ },
141
+ {
142
+ id: "value",
143
+ getIsVisible: () => true,
144
+ getIsPinned: () => false,
145
+ columnDef: {
146
+ meta: {
147
+ aggregate: "sum" as const,
148
+ numeric: true,
149
+ format: (v: unknown) => Number(v).toLocaleString("en-US"),
150
+ },
151
+ },
152
+ getAggregationValue: vi.fn(({ rows }) =>
153
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0),
154
+ ),
155
+ },
156
+ ],
157
+ });
158
+
159
+ render(<CphTableSummary table={table} showSummary={true} totalCount={10} />);
160
+
161
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
162
+ const valueCell = tfoot.querySelector(
163
+ "td[data-cph-table='summary-cell']:not(.cph-table__pinned)",
164
+ );
165
+ expect(valueCell).toHaveTextContent("60"); // 10 + 20 + 30 = 60
166
+ });
167
+
168
+ it("shows count of FILTERED rows for count aggregate", () => {
169
+ const filteredRows = [
170
+ { name: "A", value: 10 },
171
+ { name: "B", value: 20 },
172
+ { name: "C", value: 30 },
173
+ ];
174
+ const table = createMockTable({
175
+ filteredRows,
176
+ leafColumns: [
177
+ {
178
+ id: "name",
179
+ getIsVisible: () => true,
180
+ getIsPinned: () => "start" as const,
181
+ columnDef: { meta: { numeric: false } },
182
+ getAggregationValue: vi.fn(() => null),
183
+ },
184
+ {
185
+ id: "count",
186
+ getIsVisible: () => true,
187
+ getIsPinned: () => false,
188
+ columnDef: { meta: { aggregate: "count" as const, numeric: true } },
189
+ getAggregationValue: vi.fn(({ rows }) => rows.length),
190
+ },
191
+ ],
192
+ });
193
+
194
+ render(<CphTableSummary table={table} showSummary={true} totalCount={10} />);
195
+
196
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
197
+ const countCell = tfoot.querySelector("td[data-cph-table='summary-cell']");
198
+ expect(countCell).toHaveTextContent("3"); // 3 filtered rows
199
+ });
200
+
201
+ it("renders 'of N total' note when filtered count differs from total", () => {
202
+ const filteredRows = [
203
+ { name: "A", value: 10 },
204
+ { name: "B", value: 20 },
205
+ ];
206
+ const table = createMockTable({
207
+ filteredRows,
208
+ leafColumns: [
209
+ {
210
+ id: "name",
211
+ getIsVisible: () => true,
212
+ getIsPinned: () => "start" as const,
213
+ columnDef: { meta: { numeric: false } },
214
+ getAggregationValue: vi.fn(() => null),
215
+ },
216
+ {
217
+ id: "value",
218
+ getIsVisible: () => true,
219
+ getIsPinned: () => false,
220
+ columnDef: { meta: { aggregate: "sum" as const, numeric: true } },
221
+ getAggregationValue: vi.fn(({ rows }) =>
222
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0),
223
+ ),
224
+ },
225
+ ],
226
+ });
227
+
228
+ render(<CphTableSummary table={table} showSummary={true} totalCount={10} />);
229
+
230
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
231
+ const note = tfoot.querySelector("small[data-cph-table='total-note']");
232
+ expect(note).toBeInTheDocument();
233
+ expect(note).toHaveTextContent("of 10 total");
234
+ });
235
+
236
+ it("does NOT render 'of N total' note when filtered count equals total", () => {
237
+ const filteredRows = [
238
+ { name: "A", value: 10 },
239
+ { name: "B", value: 20 },
240
+ { name: "C", value: 30 },
241
+ ];
242
+ const table = createMockTable({
243
+ filteredRows,
244
+ leafColumns: [
245
+ {
246
+ id: "name",
247
+ getIsVisible: () => true,
248
+ getIsPinned: () => "start" as const,
249
+ columnDef: { meta: { numeric: false } },
250
+ getAggregationValue: vi.fn(() => null),
251
+ },
252
+ {
253
+ id: "value",
254
+ getIsVisible: () => true,
255
+ getIsPinned: () => false,
256
+ columnDef: { meta: { aggregate: "sum" as const, numeric: true } },
257
+ getAggregationValue: vi.fn(({ rows }) =>
258
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0),
259
+ ),
260
+ },
261
+ ],
262
+ });
263
+
264
+ render(<CphTableSummary table={table} showSummary={true} totalCount={3} />);
265
+
266
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
267
+ const note = tfoot.querySelector("small[data-cph-table='total-note']");
268
+ expect(note).not.toBeInTheDocument();
269
+ });
270
+
271
+ it("does NOT render 'of N total' note when totalCount is not provided", () => {
272
+ const table = createMockTable({});
273
+ render(<CphTableSummary table={table} showSummary={true} />);
274
+
275
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
276
+ const note = tfoot.querySelector("small[data-cph-table='total-note']");
277
+ expect(note).not.toBeInTheDocument();
278
+ });
279
+
280
+ it("applies cph-table__pinned class to pinned columns", () => {
281
+ const table = createMockTable({
282
+ leafColumns: [
283
+ {
284
+ id: "name",
285
+ getIsVisible: () => true,
286
+ getIsPinned: () => "start" as const,
287
+ columnDef: { meta: { numeric: false } },
288
+ getAggregationValue: vi.fn(() => null),
289
+ },
290
+ {
291
+ id: "value",
292
+ getIsVisible: () => true,
293
+ getIsPinned: () => false,
294
+ columnDef: { meta: { aggregate: "sum" as const, numeric: true } },
295
+ getAggregationValue: vi.fn(({ rows }) =>
296
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0),
297
+ ),
298
+ },
299
+ {
300
+ id: "pinnedEnd",
301
+ getIsVisible: () => true,
302
+ getIsPinned: () => "end" as const,
303
+ columnDef: { meta: { aggregate: "mean" as const, numeric: true } },
304
+ getAggregationValue: vi.fn(
305
+ ({ rows }) =>
306
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0) / rows.length,
307
+ ),
308
+ },
309
+ ],
310
+ });
311
+
312
+ render(<CphTableSummary table={table} showSummary={true} totalCount={10} />);
313
+
314
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
315
+ const cells = tfoot.querySelectorAll("[data-cph-table='summary-cell']");
316
+
317
+ // First cell (th) should be pinned
318
+ expect(cells[0]).toHaveClass("cph-table__pinned");
319
+ // Second cell (td) should not be pinned
320
+ expect(cells[1]).not.toHaveClass("cph-table__pinned");
321
+ // Third cell (td) should be pinned (end)
322
+ expect(cells[2]).toHaveClass("cph-table__pinned");
323
+ });
324
+
325
+ it("renders empty cells for columns without aggregate", () => {
326
+ const table = createMockTable({
327
+ leafColumns: [
328
+ {
329
+ id: "name",
330
+ getIsVisible: () => true,
331
+ getIsPinned: () => "start" as const,
332
+ columnDef: { meta: { numeric: false } },
333
+ getAggregationValue: vi.fn(() => null),
334
+ },
335
+ {
336
+ id: "description",
337
+ getIsVisible: () => true,
338
+ getIsPinned: () => false,
339
+ columnDef: { meta: { numeric: false } }, // no aggregate
340
+ getAggregationValue: vi.fn(() => null),
341
+ },
342
+ {
343
+ id: "value",
344
+ getIsVisible: () => true,
345
+ getIsPinned: () => false,
346
+ columnDef: { meta: { aggregate: "sum" as const, numeric: true } },
347
+ getAggregationValue: vi.fn(({ rows }) =>
348
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0),
349
+ ),
350
+ },
351
+ ],
352
+ });
353
+
354
+ render(<CphTableSummary table={table} showSummary={true} totalCount={10} />);
355
+
356
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
357
+ const cells = tfoot.querySelectorAll("td[data-cph-table='summary-cell']");
358
+
359
+ // description column (index 1 in tds, index 2 overall) should be empty
360
+ expect(cells[0]).toHaveTextContent(""); // description column
361
+ expect(cells[1]).toHaveTextContent("60"); // value column
362
+ });
363
+
364
+ it("uses column formatter when provided", () => {
365
+ const table = createMockTable({
366
+ leafColumns: [
367
+ {
368
+ id: "name",
369
+ getIsVisible: () => true,
370
+ getIsPinned: () => "start" as const,
371
+ columnDef: { meta: { numeric: false } },
372
+ getAggregationValue: vi.fn(() => null),
373
+ },
374
+ {
375
+ id: "value",
376
+ getIsVisible: () => true,
377
+ getIsPinned: () => false,
378
+ columnDef: {
379
+ meta: {
380
+ aggregate: "sum" as const,
381
+ numeric: true,
382
+ format: (v: unknown) => `$${Number(v).toLocaleString("en-US")}`,
383
+ },
384
+ },
385
+ getAggregationValue: vi.fn(({ rows }) =>
386
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0),
387
+ ),
388
+ },
389
+ ],
390
+ });
391
+
392
+ render(<CphTableSummary table={table} showSummary={true} totalCount={10} />);
393
+
394
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
395
+ const valueCell = tfoot.querySelector("td:not(.cph-table__pinned)");
396
+ expect(valueCell).toHaveTextContent("$60");
397
+ });
398
+
399
+ it("applies accumulated offsets to pinned summary cells from context", () => {
400
+ const table = createMockTable({
401
+ leafColumns: [
402
+ {
403
+ id: "name",
404
+ getIsVisible: () => true,
405
+ getIsPinned: () => false as const,
406
+ columnDef: { meta: { numeric: false } },
407
+ getAggregationValue: vi.fn(() => null),
408
+ },
409
+ {
410
+ id: "value",
411
+ getIsVisible: () => true,
412
+ getIsPinned: () => "start" as const,
413
+ columnDef: { meta: { aggregate: "sum" as const, numeric: true } },
414
+ getAggregationValue: vi.fn(({ rows }) =>
415
+ rows.reduce((sum: number, r: { value: number }) => sum + r.value, 0),
416
+ ),
417
+ },
418
+ {
419
+ id: "count",
420
+ getIsVisible: () => true,
421
+ getIsPinned: () => "end" as const,
422
+ columnDef: { meta: { aggregate: "count" as const, numeric: true } },
423
+ getAggregationValue: vi.fn(({ rows }) => rows.length),
424
+ },
425
+ ],
426
+ });
427
+
428
+ render(
429
+ <PinnedOffsetsContext.Provider value={summaryOffsets}>
430
+ <table>
431
+ <CphTableSummary table={table} showSummary={true} />
432
+ </table>
433
+ </PinnedOffsetsContext.Provider>,
434
+ );
435
+
436
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
437
+ const cells = tfoot.querySelectorAll("td.cph-table__pinned");
438
+ expect(cells).toHaveLength(2);
439
+ expect(cells[0]).toHaveStyle({ left: "50px" });
440
+ expect(cells[1]).toHaveStyle({ left: "auto", right: "30px" });
441
+ });
442
+
443
+ it("falls back to zero offset and empty text for sparse entries", () => {
444
+ const table = createMockTable({
445
+ leafColumns: [
446
+ {
447
+ id: "name",
448
+ getIsVisible: () => true,
449
+ getIsPinned: () => false as const,
450
+ columnDef: { meta: { numeric: false } },
451
+ getAggregationValue: vi.fn(() => null),
452
+ },
453
+ {
454
+ id: "value",
455
+ getIsVisible: () => true,
456
+ getIsPinned: () => "start" as const,
457
+ columnDef: { meta: { aggregate: "sum" as const, numeric: true } },
458
+ getAggregationValue: vi.fn(() => null),
459
+ },
460
+ {
461
+ id: "count",
462
+ getIsVisible: () => true,
463
+ getIsPinned: () => "end" as const,
464
+ columnDef: { meta: { aggregate: "count" as const, numeric: true } },
465
+ getAggregationValue: vi.fn(() => null),
466
+ },
467
+ ],
468
+ filteredRows: [],
469
+ });
470
+
471
+ render(
472
+ <PinnedOffsetsContext.Provider value={sparseSummaryOffsets}>
473
+ <table>
474
+ <CphTableSummary table={table} showSummary={true} />
475
+ </table>
476
+ </PinnedOffsetsContext.Provider>,
477
+ );
478
+
479
+ const tfoot = screen.getByRole("rowgroup", { name: /summary/i });
480
+ const cells = tfoot.querySelectorAll("td.cph-table__pinned");
481
+ expect(cells).toHaveLength(2);
482
+ expect(cells[0]).toHaveStyle({ left: "50px" });
483
+ expect(cells[1]).toHaveStyle({ left: "auto", right: "0px" });
484
+ expect(cells[0]).toHaveTextContent("");
485
+ });
486
+ });
@@ -0,0 +1,130 @@
1
+ /** @packageDocumentation Table summary/aggregate footer row. */
2
+
3
+ import type { Column, Row, RowData, Table } from "@tanstack/react-table";
4
+
5
+ import type { CphTableFeatures } from "../../table/features";
6
+ import { usePinnedOffset } from "../DataTable/pinnedOffsets";
7
+
8
+ export interface CphTableSummaryProps<TData extends RowData> {
9
+ /** The TanStack Table instance. */
10
+ table: Table<CphTableFeatures, TData>;
11
+ /** Opt-in: show the summary footer. When false, no tfoot is rendered. */
12
+ showSummary?: boolean;
13
+ /** Total row count (unfiltered) for "of N total" note. */
14
+ totalCount?: number;
15
+ }
16
+
17
+ /**
18
+ * Sticky footer showing aggregated values for filtered rows.
19
+ *
20
+ * Renders as `<tfoot class="cph-table__summary">` when `showSummary` is true.
21
+ * When false or absent, no `<tfoot>` element exists in the DOM.
22
+ *
23
+ * Each visible leaf column with `meta.aggregate` ("sum" | "mean" | "count")
24
+ * displays its filter-aware aggregate. Columns without an aggregate render empty.
25
+ * An "of N total" note shows the filtered row count against the total.
26
+ */
27
+ export function CphTableSummary<TData extends RowData>({
28
+ table,
29
+ showSummary = false,
30
+ totalCount,
31
+ }: Readonly<CphTableSummaryProps<TData>>) {
32
+ if (!showSummary) {
33
+ return null;
34
+ }
35
+
36
+ const filteredRows = table.getFilteredRowModel().rows;
37
+ const filteredCount = filteredRows.length;
38
+ const leafColumns = table.getAllLeafColumns().filter((col) => col.getIsVisible());
39
+
40
+ return (
41
+ <tfoot className="cph-table__summary" data-cph-table="summary" aria-label="Summary">
42
+ <tr>
43
+ {leafColumns.map((column, index) => (
44
+ <SummaryCell
45
+ key={column.id}
46
+ column={column}
47
+ isFirstColumn={index === 0}
48
+ filteredRows={filteredRows}
49
+ filteredCount={filteredCount}
50
+ {...(totalCount === undefined ? {} : { totalCount })}
51
+ />
52
+ ))}
53
+ </tr>
54
+ </tfoot>
55
+ );
56
+ }
57
+
58
+ function SummaryCell<TData extends RowData>({
59
+ column,
60
+ isFirstColumn,
61
+ filteredRows,
62
+ filteredCount,
63
+ totalCount,
64
+ }: {
65
+ column: Column<CphTableFeatures, TData, unknown>;
66
+ isFirstColumn: boolean;
67
+ filteredRows: Row<CphTableFeatures, TData>[];
68
+ filteredCount: number;
69
+ totalCount?: number;
70
+ }) {
71
+ const offset = usePinnedOffset(column.id);
72
+ const meta = column.columnDef.meta;
73
+ const aggregate = meta?.aggregate;
74
+ const pinned = column.getIsPinned();
75
+ const isPinned = pinned === "start" || pinned === "end";
76
+ const isNumeric = meta?.numeric === true;
77
+ const pinnedStyle =
78
+ !isPinned || offset === undefined
79
+ ? undefined
80
+ : pinned === "start"
81
+ ? { left: `${offset.left}px` }
82
+ : { left: "auto", right: `${offset.right ?? 0}px` };
83
+
84
+ let cellContent: React.ReactNode = null;
85
+
86
+ if (aggregate) {
87
+ // Use the column's getAggregationValue with filtered rows for filter-aware aggregation
88
+ const aggregatedValue = column.getAggregationValue({
89
+ rows: filteredRows,
90
+ });
91
+
92
+ // Format the value if a formatter is provided
93
+ const formattedValue = meta?.format
94
+ ? meta.format(aggregatedValue)
95
+ : String(aggregatedValue ?? "");
96
+
97
+ cellContent = formattedValue;
98
+ }
99
+
100
+ // First column renders as <th scope="row"> for the label/note
101
+ if (isFirstColumn) {
102
+ return (
103
+ <th
104
+ scope="row"
105
+ className={`cph-table__summary-cell ${isPinned ? "cph-table__pinned" : ""}`}
106
+ style={pinnedStyle}
107
+ data-cph-table="summary-cell"
108
+ data-pinned={isPinned ? "true" : undefined}
109
+ >
110
+ <span data-cph-table="summary-label">Summary</span>
111
+ {totalCount !== undefined && filteredCount !== totalCount && (
112
+ <small data-cph-table="total-note">of {totalCount} total</small>
113
+ )}
114
+ </th>
115
+ );
116
+ }
117
+
118
+ // Data columns render as <td>
119
+ return (
120
+ <td
121
+ className={`cph-table__summary-cell ${isNumeric ? "cph-table__numeric" : ""} ${isPinned ? "cph-table__pinned" : ""}`}
122
+ style={pinnedStyle}
123
+ data-cph-table="summary-cell"
124
+ data-pinned={isPinned ? "true" : undefined}
125
+ data-numeric={isNumeric ? "true" : undefined}
126
+ >
127
+ {cellContent}
128
+ </td>
129
+ );
130
+ }
@@ -0,0 +1,52 @@
1
+ /** @packageDocumentation Tests for CphTableHead. */
2
+
3
+ import { useTable } from "@tanstack/react-table";
4
+ import { render, screen } from "@testing-library/react";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+
7
+ import { cphColumnHelper } from "../../table/column";
8
+ import { cphTableFeatures } from "../../table/features";
9
+ import { CphTableHead } from "./CphTableHead";
10
+
11
+ type TestRow = {
12
+ id: string;
13
+ name: string;
14
+ };
15
+
16
+ const helper = cphColumnHelper<TestRow>();
17
+ const columns = helper.columns([
18
+ helper.accessor("name", {
19
+ header: () => <span>Function header</span>,
20
+ }),
21
+ ]);
22
+
23
+ function TableHeadSurface() {
24
+ const table = useTable({
25
+ features: cphTableFeatures,
26
+ columns,
27
+ data: [{ id: "row-1", name: "Name" }],
28
+ getRowId: (row) => row.id,
29
+ enableMultiSort: false,
30
+ });
31
+
32
+ return (
33
+ <table>
34
+ <CphTableHead table={table} />
35
+ </table>
36
+ );
37
+ }
38
+
39
+ afterEach(() => {
40
+ vi.restoreAllMocks();
41
+ });
42
+
43
+ describe("CphTableHead", () => {
44
+ it("renders function headers without React warnings", () => {
45
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
46
+
47
+ render(<TableHeadSurface />);
48
+
49
+ expect(screen.getByRole("columnheader")).toHaveTextContent("Function header");
50
+ expect(consoleError).not.toHaveBeenCalled();
51
+ });
52
+ });