@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,408 @@
1
+ /** @packageDocumentation Tests for CphDataTable. */
2
+
3
+ import type { Table, RowData, ColumnPinningPosition } from "@tanstack/react-table";
4
+ import { render, screen } from "@testing-library/react";
5
+ import { describe, expect, it, vi } from "vitest";
6
+
7
+ import type { CphTableFeatures } from "../../table/features";
8
+ import { CphTableDensityProvider } from "../../theme/CphTableDensity";
9
+ import { CphDataTable } from "./CphDataTable";
10
+ import { computePinnedOffsets, usePinnedOffset } from "./pinnedOffsets";
11
+
12
+ // Test data type
13
+ type TestRow = RowData & {
14
+ id: string;
15
+ name: string;
16
+ value: number;
17
+ };
18
+
19
+ function OffsetTestConsumer({
20
+ headerId,
21
+ mode = "json",
22
+ }: {
23
+ headerId: string;
24
+ mode?: "json" | "presence";
25
+ }) {
26
+ const offset = usePinnedOffset(headerId);
27
+ return (
28
+ <span data-testid={`offset-${headerId}`}>
29
+ {mode === "presence" ? (offset ? "found" : "undefined") : JSON.stringify(offset)}
30
+ </span>
31
+ );
32
+ }
33
+
34
+ // Minimal mock header for testing
35
+ function createMockHeader(
36
+ id: string,
37
+ size: number,
38
+ isPinned: "start" | "end" | false,
39
+ isLast: boolean,
40
+ ) {
41
+ return {
42
+ id,
43
+ getSize: vi.fn(() => size),
44
+ column: {
45
+ getIsPinned: vi.fn(() => isPinned),
46
+ getIsLastColumn: vi.fn((pos?: ColumnPinningPosition | "center") =>
47
+ pos === "start" || pos === "end" ? isLast : false,
48
+ ),
49
+ },
50
+ };
51
+ }
52
+
53
+ // Minimal mock column for testing
54
+ function createMockColumn(id: string, widthClass?: string) {
55
+ return {
56
+ id,
57
+ columnDef: {
58
+ meta: widthClass ? { widthClass } : {},
59
+ },
60
+ };
61
+ }
62
+
63
+ // Minimal mock table for testing
64
+ function createMockTable(
65
+ overrides: Partial<{
66
+ startLeafHeaders: ReturnType<typeof createMockHeader>[];
67
+ endLeafHeaders: ReturnType<typeof createMockHeader>[];
68
+ startVisibleLeafColumns: ReturnType<typeof createMockColumn>[];
69
+ centerVisibleLeafColumns: ReturnType<typeof createMockColumn>[];
70
+ endVisibleLeafColumns: ReturnType<typeof createMockColumn>[];
71
+ }> = {},
72
+ ) {
73
+ const startLeafHeaders = overrides.startLeafHeaders ?? [
74
+ createMockHeader("col-1", 100, "start", false),
75
+ createMockHeader("col-2", 120, "start", true),
76
+ ];
77
+ const startVisibleLeafColumns = overrides.startVisibleLeafColumns ?? [
78
+ createMockColumn("col-1", "source"),
79
+ createMockColumn("col-2", "type"),
80
+ ];
81
+ const centerVisibleLeafColumns = overrides.centerVisibleLeafColumns ?? [
82
+ createMockColumn("col-3", "collection"),
83
+ createMockColumn("col-4", "status"),
84
+ ];
85
+ const endVisibleLeafColumns = overrides.endVisibleLeafColumns ?? [
86
+ createMockColumn("col-5", "number"),
87
+ ];
88
+
89
+ return {
90
+ getStartLeafHeaders: vi.fn(() => startLeafHeaders),
91
+ getEndLeafHeaders: vi.fn(() => overrides.endLeafHeaders ?? []),
92
+ getStartVisibleLeafColumns: vi.fn(() => startVisibleLeafColumns),
93
+ getCenterVisibleLeafColumns: vi.fn(() => centerVisibleLeafColumns),
94
+ getEndVisibleLeafColumns: vi.fn(() => endVisibleLeafColumns),
95
+ } as unknown as Table<CphTableFeatures, TestRow>;
96
+ }
97
+
98
+ describe("CphDataTable", () => {
99
+ it("renders root, scroll, and table elements with correct classes", () => {
100
+ const table = createMockTable();
101
+ render(
102
+ <CphDataTable table={table}>
103
+ <thead data-testid="thead" />
104
+ <tbody data-testid="tbody" />
105
+ </CphDataTable>,
106
+ );
107
+
108
+ expect(screen.getByTestId("thead").closest(".cph-table-root")).toBeInTheDocument();
109
+ expect(screen.getByTestId("thead").closest(".cph-table-scroll")).toBeInTheDocument();
110
+ expect(screen.getByTestId("thead").closest(".cph-table")).toBeInTheDocument();
111
+ });
112
+
113
+ it("renders a colgroup with one col per visible leaf column in visual order", () => {
114
+ const table = createMockTable();
115
+ const { container } = render(
116
+ <CphDataTable table={table}>
117
+ <thead />
118
+ <tbody />
119
+ </CphDataTable>,
120
+ );
121
+
122
+ const cols = container.querySelectorAll("col");
123
+ expect(cols).toHaveLength(5);
124
+ // key is a React internal prop, not rendered to DOM
125
+ expect(cols[0]).toBeInTheDocument();
126
+ expect(cols[1]).toBeInTheDocument();
127
+ expect(cols[2]).toBeInTheDocument();
128
+ expect(cols[3]).toBeInTheDocument();
129
+ expect(cols[4]).toBeInTheDocument();
130
+ });
131
+
132
+ it("applies widthClass from column meta as cph-table__col-* class on col elements", () => {
133
+ const table = createMockTable();
134
+ const { container } = render(
135
+ <CphDataTable table={table}>
136
+ <thead />
137
+ <tbody />
138
+ </CphDataTable>,
139
+ );
140
+
141
+ const cols = container.querySelectorAll("col");
142
+ expect(cols[0]).toHaveClass("cph-table__col-source");
143
+ expect(cols[1]).toHaveClass("cph-table__col-type");
144
+ expect(cols[2]).toHaveClass("cph-table__col-collection");
145
+ expect(cols[3]).toHaveClass("cph-table__col-status");
146
+ expect(cols[4]).toHaveClass("cph-table__col-number");
147
+ });
148
+
149
+ it("omits class on col when widthClass is not provided", () => {
150
+ const table = createMockTable({
151
+ startVisibleLeafColumns: [createMockColumn("col-1")],
152
+ centerVisibleLeafColumns: [],
153
+ endVisibleLeafColumns: [],
154
+ });
155
+ const { container } = render(
156
+ <CphDataTable table={table}>
157
+ <thead />
158
+ <tbody />
159
+ </CphDataTable>,
160
+ );
161
+
162
+ const col = container.querySelector("col");
163
+ expect(col).not.toHaveClass("cph-table__col-source");
164
+ expect(col?.className).toBe("");
165
+ });
166
+
167
+ it("computes strictly increasing left offsets for multiple start-pinned columns", () => {
168
+ const table = createMockTable({
169
+ startLeafHeaders: [
170
+ createMockHeader("col-1", 100, "start", false),
171
+ createMockHeader("col-2", 120, "start", true),
172
+ ],
173
+ });
174
+ render(
175
+ <CphDataTable table={table}>
176
+ <thead />
177
+ <tbody />
178
+ </CphDataTable>,
179
+ );
180
+
181
+ // The offsets are computed internally; we verify via the context consumer
182
+ // by rendering a test component that uses usePinnedOffset
183
+ render(
184
+ <CphDataTable table={table}>
185
+ <OffsetTestConsumer headerId="col-1" />
186
+ <OffsetTestConsumer headerId="col-2" />
187
+ <thead />
188
+ <tbody />
189
+ </CphDataTable>,
190
+ );
191
+
192
+ const offset1 = JSON.parse(screen.getByTestId("offset-col-1").textContent ?? "null");
193
+ expect(offset1).toEqual({ left: 0, isLast: false });
194
+
195
+ const offset2 = JSON.parse(screen.getByTestId("offset-col-2").textContent ?? "null");
196
+ expect(offset2).toEqual({ left: 100, isLast: true });
197
+
198
+ // Verify strictly increasing
199
+ expect(offset2.left).toBeGreaterThan(offset1.left);
200
+ });
201
+
202
+ it("excludes unpinned columns from the offsets map but tracks both regions", () => {
203
+ const table = createMockTable({
204
+ startLeafHeaders: [
205
+ createMockHeader("col-1", 100, "start", true),
206
+ createMockHeader("col-2", 120, "end", false), // end-pinned, should be excluded
207
+ createMockHeader("col-3", 80, false, false), // not pinned, should be excluded
208
+ ],
209
+ });
210
+ render(
211
+ <CphDataTable table={table}>
212
+ <thead />
213
+ <tbody />
214
+ </CphDataTable>,
215
+ );
216
+
217
+ render(
218
+ <CphDataTable table={table}>
219
+ <OffsetTestConsumer headerId="col-1" mode="presence" />
220
+ <OffsetTestConsumer headerId="col-2" mode="presence" />
221
+ <OffsetTestConsumer headerId="col-3" mode="presence" />
222
+ <thead />
223
+ <tbody />
224
+ </CphDataTable>,
225
+ );
226
+
227
+ expect(screen.getByTestId("offset-col-1")).toHaveTextContent("found");
228
+ expect(screen.getByTestId("offset-col-2")).toHaveTextContent("found");
229
+ expect(screen.getByTestId("offset-col-3")).toHaveTextContent("undefined");
230
+ });
231
+
232
+ it("passes through additional props to the root div", () => {
233
+ const table = createMockTable();
234
+ render(
235
+ <CphDataTable table={table} data-testid="custom-root" id="my-table">
236
+ <thead />
237
+ <tbody />
238
+ </CphDataTable>,
239
+ );
240
+
241
+ expect(screen.getByTestId("custom-root")).toHaveAttribute("id", "my-table");
242
+ });
243
+
244
+ it("passes through className to the root div", () => {
245
+ const table = createMockTable();
246
+ render(
247
+ <CphDataTable table={table} className="cph-test-custom-class">
248
+ <thead data-testid="thead" />
249
+ <tbody />
250
+ </CphDataTable>,
251
+ );
252
+
253
+ expect(screen.getByTestId("thead").closest(".cph-table-root")).toHaveClass(
254
+ "cph-test-custom-class",
255
+ );
256
+ });
257
+
258
+ it("applies tableLabel as aria-label on the table element itself", () => {
259
+ const table = createMockTable();
260
+ render(
261
+ <CphDataTable table={table} tableLabel="Ledger register">
262
+ <thead />
263
+ <tbody />
264
+ </CphDataTable>,
265
+ );
266
+
267
+ const tableEl = screen.getByRole("table", { name: "Ledger register" });
268
+ expect(tableEl).toHaveClass("cph-table");
269
+ expect(tableEl.closest(".cph-table-root")).not.toHaveAttribute("aria-label");
270
+ });
271
+
272
+ it("omits the aria-label attribute when tableLabel is not provided", () => {
273
+ const table = createMockTable();
274
+ const { container } = render(
275
+ <CphDataTable table={table}>
276
+ <thead />
277
+ <tbody />
278
+ </CphDataTable>,
279
+ );
280
+
281
+ expect(container.querySelector("table.cph-table")).not.toHaveAttribute("aria-label");
282
+ });
283
+
284
+ it("sets data-density from context, defaulting to compact without a provider", () => {
285
+ const table = createMockTable();
286
+ render(
287
+ <CphDataTable table={table} data-testid="density-root">
288
+ <thead />
289
+ <tbody />
290
+ </CphDataTable>,
291
+ );
292
+
293
+ expect(screen.getByTestId("density-root")).toHaveAttribute("data-density", "compact");
294
+ });
295
+
296
+ it("sets data-density from an explicit provider value", () => {
297
+ const table = createMockTable();
298
+ render(
299
+ <CphTableDensityProvider density="dense">
300
+ <CphDataTable table={table} data-testid="density-root">
301
+ <thead />
302
+ <tbody />
303
+ </CphDataTable>
304
+ </CphTableDensityProvider>,
305
+ );
306
+
307
+ expect(screen.getByTestId("density-root")).toHaveAttribute("data-density", "dense");
308
+ });
309
+
310
+ it("renders summary tfoot when showSummary is true", () => {
311
+ const table = {
312
+ ...createMockTable(),
313
+ getCoreRowModel: vi.fn(() => ({ rows: [] })),
314
+ getFilteredRowModel: vi.fn(() => ({ rows: [] })),
315
+ getAllLeafColumns: vi.fn(() => []),
316
+ } as unknown as Table<CphTableFeatures, TestRow>;
317
+ const { container } = render(
318
+ <CphDataTable table={table} showSummary>
319
+ <thead />
320
+ <tbody />
321
+ </CphDataTable>,
322
+ );
323
+
324
+ expect(container.querySelector("tfoot.cph-table__summary")).toBeInTheDocument();
325
+ });
326
+
327
+ it("renders no tfoot when showSummary is false or absent", () => {
328
+ const table = createMockTable();
329
+ const { container, rerender } = render(
330
+ <CphDataTable table={table} showSummary={false}>
331
+ <thead />
332
+ <tbody />
333
+ </CphDataTable>,
334
+ );
335
+
336
+ expect(container.querySelector("tfoot")).not.toBeInTheDocument();
337
+
338
+ rerender(
339
+ <CphDataTable table={table}>
340
+ <thead />
341
+ <tbody />
342
+ </CphDataTable>,
343
+ );
344
+
345
+ expect(container.querySelector("tfoot")).not.toBeInTheDocument();
346
+ });
347
+ });
348
+
349
+ describe("computePinnedOffsets (pure function)", () => {
350
+ it("returns empty map for empty headers array", () => {
351
+ const result = computePinnedOffsets([]);
352
+ expect(result.size).toBe(0);
353
+ });
354
+
355
+ it("accumulates left offsets correctly for multiple start-pinned headers", () => {
356
+ const headers = [
357
+ createMockHeader("a", 100, "start", false),
358
+ createMockHeader("b", 120, "start", false),
359
+ createMockHeader("c", 80, "start", true),
360
+ ];
361
+ const result = computePinnedOffsets(headers);
362
+
363
+ expect(result.get("a")).toEqual({ left: 0, isLast: false });
364
+ expect(result.get("b")).toEqual({ left: 100, isLast: false });
365
+ expect(result.get("c")).toEqual({ left: 220, isLast: true });
366
+ });
367
+
368
+ it("skips unpinned headers but tracks both pinned regions", () => {
369
+ const headers = [
370
+ createMockHeader("a", 100, "start", false),
371
+ createMockHeader("b", 120, "end", false),
372
+ createMockHeader("c", 80, false, false),
373
+ createMockHeader("d", 90, "start", true),
374
+ ];
375
+ const result = computePinnedOffsets(headers);
376
+
377
+ expect(result.has("a")).toBe(true);
378
+ expect(result.has("b")).toBe(true);
379
+ expect(result.has("c")).toBe(false);
380
+ expect(result.has("d")).toBe(true);
381
+ expect(result.get("d")?.left).toBe(100); // only 'a' contributes to running total
382
+ expect(result.get("b")).toEqual({ left: 0, isLast: false, right: 0 });
383
+ });
384
+
385
+ it("accumulates right offsets for multiple end-pinned headers in reverse", () => {
386
+ const headers = [
387
+ createMockHeader("a", 100, "start", false),
388
+ createMockHeader("b", 80, false, false),
389
+ createMockHeader("c", 120, "end", false),
390
+ createMockHeader("d", 90, "end", true),
391
+ ];
392
+ const result = computePinnedOffsets(headers);
393
+
394
+ expect(result.get("d")).toEqual({ left: 0, isLast: true, right: 0 });
395
+ expect(result.get("c")).toEqual({ left: 0, isLast: false, right: 90 });
396
+ });
397
+
398
+ it("isLast comes from column.getIsLastColumn('start')", () => {
399
+ const headers = [
400
+ createMockHeader("a", 100, "start", false),
401
+ createMockHeader("b", 120, "start", true),
402
+ ];
403
+ const result = computePinnedOffsets(headers);
404
+
405
+ expect(result.get("a")?.isLast).toBe(false);
406
+ expect(result.get("b")?.isLast).toBe(true);
407
+ });
408
+ });
@@ -0,0 +1,121 @@
1
+ /** @packageDocumentation The main table container component. */
2
+
3
+ import type { Table, RowData, ColumnPinningPosition } from "@tanstack/react-table";
4
+ import { useMemo, type ReactNode } from "react";
5
+
6
+ import type { CphColumnMeta } from "../../table/column";
7
+ import type { CphTableFeatures } from "../../table/features";
8
+ import { useCphTableDensity } from "../../theme/cphTableDensityContext";
9
+ import { CphTableSummary } from "../Summary/CphTableSummary";
10
+ import {
11
+ computePinnedOffsets,
12
+ PinnedOffsetsContext,
13
+ type PinnedOffsetHeader,
14
+ } from "./pinnedOffsets";
15
+
16
+ export type { PinnedOffsetsContextValue } from "./pinnedOffsets";
17
+
18
+ export interface CphDataTableProps<
19
+ TData extends RowData,
20
+ > extends React.HTMLAttributes<HTMLDivElement> {
21
+ /** The TanStack table instance. */
22
+ table: Table<CphTableFeatures, TData>;
23
+ /** Header and row content (typically CphTableHead, CphTableBody, etc.). */
24
+ children: ReactNode;
25
+ /** Show summary footer when true. */
26
+ showSummary?: boolean;
27
+ /**
28
+ * Accessible name for the table, applied as `aria-label` on the
29
+ * `<table>` element (not the outer div, so it names the grid itself).
30
+ * Omitted entirely when not provided.
31
+ */
32
+ tableLabel?: string;
33
+ }
34
+
35
+ /**
36
+ * Scrollable table container with pinned column support.
37
+ *
38
+ * Renders:
39
+ * <div class="cph-table-root">
40
+ * <div class="cph-table-scroll">
41
+ * <table class="cph-table">
42
+ * <colgroup> — one <col> per visible leaf column
43
+ * {children} — header, body, footer
44
+ * </table>
45
+ * </div>
46
+ * </div>
47
+ *
48
+ * Pinned column offsets are computed from start-pinned leaf headers and
49
+ * published via {@link PinnedOffsetsContext} so {@link HeaderCell} can read
50
+ * its own `left` without prop drilling.
51
+ */
52
+ export function CphDataTable<TData extends RowData>({
53
+ table,
54
+ children,
55
+ showSummary = false,
56
+ tableLabel,
57
+ className,
58
+ ...props
59
+ }: Readonly<CphDataTableProps<TData>>) {
60
+ const density = useCphTableDensity();
61
+ // Collect all visible leaf columns in visual order: start, center, end
62
+ const visibleLeafColumns = [
63
+ ...table.getStartVisibleLeafColumns(),
64
+ ...table.getCenterVisibleLeafColumns(),
65
+ ...table.getEndVisibleLeafColumns(),
66
+ ];
67
+
68
+ // Get pinned leaf headers for offset computation (start walks forward,
69
+ // end walks in reverse inside computePinnedOffsets)
70
+ const startLeafHeaders = table.getStartLeafHeaders();
71
+ const endLeafHeaders = table.getEndLeafHeaders();
72
+
73
+ // Map TanStack headers to our minimal interface for offset computation
74
+ const offsetHeaders = [...startLeafHeaders, ...endLeafHeaders].map(
75
+ (header): PinnedOffsetHeader => ({
76
+ id: header.id,
77
+ getSize: () => header.getSize(),
78
+ column: {
79
+ getIsPinned: () => header.column.getIsPinned(),
80
+ getIsLastColumn: (position?: ColumnPinningPosition | "center") =>
81
+ header.column.getIsLastColumn(position),
82
+ },
83
+ }),
84
+ );
85
+
86
+ // Compute pinned offsets and publish via context
87
+ const pinnedOffsets = computePinnedOffsets(offsetHeaders);
88
+
89
+ const contextValue = useMemo(() => ({ offsets: pinnedOffsets }), [pinnedOffsets]);
90
+
91
+ return (
92
+ <PinnedOffsetsContext.Provider value={contextValue}>
93
+ <div {...props} className={`cph-table-root ${className ?? ""}`} data-density={density}>
94
+ <div className="cph-table-scroll">
95
+ <table className="cph-table" {...(tableLabel ? { "aria-label": tableLabel } : {})}>
96
+ <colgroup>
97
+ {visibleLeafColumns.map((column) => {
98
+ const meta = column.columnDef.meta as CphColumnMeta | undefined;
99
+ const widthClass = meta?.widthClass;
100
+ return (
101
+ <col
102
+ key={column.id}
103
+ className={widthClass ? `cph-table__col-${widthClass}` : undefined}
104
+ />
105
+ );
106
+ })}
107
+ </colgroup>
108
+ {children}
109
+ {showSummary ? (
110
+ <CphTableSummary
111
+ table={table}
112
+ showSummary
113
+ totalCount={table.getCoreRowModel().rows.length}
114
+ />
115
+ ) : null}
116
+ </table>
117
+ </div>
118
+ </div>
119
+ </PinnedOffsetsContext.Provider>
120
+ );
121
+ }
@@ -0,0 +1,94 @@
1
+ /** @packageDocumentation Pure pinned-column offset computation. */
2
+
3
+ import type { ColumnPinningPosition } from "@tanstack/react-table";
4
+ import { createContext, useContext } from "react";
5
+
6
+ /**
7
+ * Minimal structural interface for a leaf header used by offset computation.
8
+ * Keeps the function testable with plain objects — no TanStack table instance needed.
9
+ */
10
+ export interface PinnedOffsetHeader {
11
+ /** The header's unique identifier. */
12
+ id: string;
13
+ /** The associated column instance. */
14
+ column: {
15
+ /** Returns the logical pinned position: 'start', 'end', or false. */
16
+ getIsPinned: () => ColumnPinningPosition;
17
+ /** Returns true if this is the last visible column in the given region. */
18
+ getIsLastColumn: (position?: ColumnPinningPosition | "center") => boolean;
19
+ };
20
+ /** Returns the header's rendered size from its leaf columns. */
21
+ getSize: () => number;
22
+ }
23
+
24
+ /**
25
+ * Result entry for a pinned column.
26
+ */
27
+ export interface PinnedOffsetEntry {
28
+ /** Accumulated left offset in pixels (start-pinned columns). */
29
+ left: number;
30
+ /** Whether this is the last pinned column in the start region. */
31
+ isLast: boolean;
32
+ /**
33
+ * Accumulated right offset in pixels (end-pinned columns only).
34
+ * Absent for start-pinned entries so existing structural assertions hold.
35
+ */
36
+ right?: number;
37
+ }
38
+
39
+ /**
40
+ * Computes sticky offsets for pinned leaf headers.
41
+ *
42
+ * Walks visible leaf headers in order, accumulating `header.getSize()` for
43
+ * start-pinned columns into `left`, then walks in reverse accumulating `right`
44
+ * for end-pinned columns. `isLast` comes from `column.getIsLastColumn("start")`
45
+ * (or `"end"` for end-pinned entries).
46
+ * Unpinned columns are absent from the returned map.
47
+ */
48
+ export function computePinnedOffsets(
49
+ headers: ReadonlyArray<PinnedOffsetHeader>,
50
+ ): ReadonlyMap<string, PinnedOffsetEntry> {
51
+ const offsets = new Map<string, PinnedOffsetEntry>();
52
+ let runningLeft = 0;
53
+
54
+ for (const header of headers) {
55
+ const isPinned = header.column.getIsPinned();
56
+ if (isPinned !== "start") {
57
+ continue;
58
+ }
59
+
60
+ const isLast = header.column.getIsLastColumn("start");
61
+ offsets.set(header.id, { left: runningLeft, isLast });
62
+ runningLeft += header.getSize();
63
+ }
64
+
65
+ let runningRight = 0;
66
+ for (let index = headers.length - 1; index >= 0; index -= 1) {
67
+ const header = headers[index];
68
+ if (header === undefined || header.column.getIsPinned() !== "end") {
69
+ continue;
70
+ }
71
+
72
+ const isLast = header.column.getIsLastColumn("end");
73
+ offsets.set(header.id, { left: 0, isLast, right: runningRight });
74
+ runningRight += header.getSize();
75
+ }
76
+
77
+ return offsets;
78
+ }
79
+
80
+ /** Context value for pinned column offsets. */
81
+ export interface PinnedOffsetsContextValue {
82
+ offsets: ReadonlyMap<string, PinnedOffsetEntry>;
83
+ }
84
+
85
+ export const PinnedOffsetsContext = createContext<PinnedOffsetsContextValue | null>(null);
86
+
87
+ /**
88
+ * Consumes the pinned-offsets context published by {@link CphDataTable}.
89
+ * Returns the offset entry for the given header id, or undefined if not pinned.
90
+ */
91
+ export function usePinnedOffset(headerId: string): PinnedOffsetEntry | undefined {
92
+ const ctx = useContext(PinnedOffsetsContext);
93
+ return ctx?.offsets.get(headerId);
94
+ }